This repository has been archived by the owner on Jan 30, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathevent_emitter.go
228 lines (193 loc) · 5.6 KB
/
event_emitter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package common
import (
"context"
"sync"
)
const (
// Browser
EventBrowserDisconnected string = "disconnected"
// BrowserContext
EventBrowserContextPage string = "page"
// Connection
EventConnectionClose string = "close"
// Frame
EventFrameNavigation string = "navigation"
EventFrameAddLifecycle string = "addlifecycle"
// Page
EventPageClose string = "close"
EventPageConsole string = "console"
EventPageCrash string = "crash"
EventPageDialog string = "dialog"
EventPageDownload string = "download"
EventPageFilechooser string = "filechooser"
EventPageFrameAttached string = "frameattached"
EventPageFrameDetached string = "framedetached"
EventPageFrameNavigated string = "framenavigated"
EventPageError string = "pageerror"
EventPagePopup string = "popup"
EventPageRequest string = "request"
EventPageRequestFailed string = "requestfailed"
EventPageRequestFinished string = "requestfinished"
EventPageResponse string = "response"
EventPageWebSocket string = "websocket"
EventPageWorker string = "worker"
// Session
EventSessionClosed string = "close"
// Worker
EventWorkerClose string = "close"
)
// Event as emitted by an EventEmiter.
type Event struct {
typ string
data any
}
// NavigationEvent is emitted when we receive a Page.frameNavigated or
// Page.navigatedWithinDocument CDP event.
// See:
// - https://chromedevtools.github.io/devtools-protocol/tot/Page/#event-frameNavigated
// - https://chromedevtools.github.io/devtools-protocol/tot/Page/#event-navigatedWithinDocument
type NavigationEvent struct {
newDocument *DocumentInfo
url string
name string
err error
}
type queue struct {
writeMutex sync.Mutex
write []Event
readMutex sync.Mutex
read []Event
}
type eventHandler struct {
ctx context.Context
ch chan Event
queue *queue
}
// EventEmitter that all event emitters need to implement.
type EventEmitter interface {
emit(event string, data any)
on(ctx context.Context, events []string, ch chan Event)
onAll(ctx context.Context, ch chan Event)
}
// syncFunc functions are passed through the syncCh for synchronously handling
// eventHandler requests.
type syncFunc func() (done chan struct{})
// BaseEventEmitter emits events to registered handlers.
type BaseEventEmitter struct {
handlers map[string][]*eventHandler
handlersAll []*eventHandler
queues map[chan Event]*queue
syncCh chan syncFunc
ctx context.Context
}
// NewBaseEventEmitter creates a new instance of a base event emitter.
func NewBaseEventEmitter(ctx context.Context) BaseEventEmitter {
bem := BaseEventEmitter{
handlers: make(map[string][]*eventHandler),
syncCh: make(chan syncFunc),
ctx: ctx,
queues: make(map[chan Event]*queue),
}
go bem.syncAll(ctx)
return bem
}
// syncAll receives work requests from BaseEventEmitter methods
// and processes them one at a time for synchronization.
//
// It returns when the BaseEventEmitter context is done.
func (e *BaseEventEmitter) syncAll(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case fn := <-e.syncCh:
// run the function and signal when it's done
done := fn()
done <- struct{}{}
}
}
}
// sync is a helper for sychronized access to the BaseEventEmitter.
func (e *BaseEventEmitter) sync(fn func()) {
done := make(chan struct{})
select {
case <-e.ctx.Done():
return
case e.syncCh <- func() chan struct{} {
fn()
return done
}:
}
// wait for the function to return
<-done
}
func (e *BaseEventEmitter) emit(event string, data any) {
emitEvent := func(eh *eventHandler) {
eh.queue.readMutex.Lock()
defer eh.queue.readMutex.Unlock()
// We try to read from the read queue (queue.read).
// If there isn't anything on the read queue, then there must
// be something being populated by the synched emitTo
// func below.
// Swap around the read queue with the write queue.
// Queue is now being populated again by emitTo, and all
// emitEvent goroutines can continue to consume from
// the read queue until that is again depleted.
if len(eh.queue.read) == 0 {
eh.queue.writeMutex.Lock()
eh.queue.read, eh.queue.write = eh.queue.write, eh.queue.read
eh.queue.writeMutex.Unlock()
}
select {
case eh.ch <- eh.queue.read[0]:
eh.queue.read = eh.queue.read[1:]
case <-eh.ctx.Done():
// TODO: handle the error
}
}
emitTo := func(handlers []*eventHandler) (updated []*eventHandler) {
for i := 0; i < len(handlers); {
handler := handlers[i]
select {
case <-handler.ctx.Done():
handlers = append(handlers[:i], handlers[i+1:]...)
continue
default:
handler.queue.writeMutex.Lock()
handler.queue.write = append(handler.queue.write, Event{typ: event, data: data})
handler.queue.writeMutex.Unlock()
go emitEvent(handler)
i++
}
}
return handlers
}
e.sync(func() {
e.handlers[event] = emitTo(e.handlers[event])
e.handlersAll = emitTo(e.handlersAll)
})
}
// On registers a handler for a specific event.
func (e *BaseEventEmitter) on(ctx context.Context, events []string, ch chan Event) {
e.sync(func() {
q, ok := e.queues[ch]
if !ok {
q = &queue{}
e.queues[ch] = q
}
for _, event := range events {
e.handlers[event] = append(e.handlers[event], &eventHandler{ctx: ctx, ch: ch, queue: q})
}
})
}
// OnAll registers a handler for all events.
func (e *BaseEventEmitter) onAll(ctx context.Context, ch chan Event) {
e.sync(func() {
q, ok := e.queues[ch]
if !ok {
q = &queue{}
e.queues[ch] = q
}
e.handlersAll = append(e.handlersAll, &eventHandler{ctx: ctx, ch: ch, queue: q})
})
}