-
Notifications
You must be signed in to change notification settings - Fork 0
/
loop.go
314 lines (265 loc) · 8.68 KB
/
loop.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package asyncigo
import (
"container/heap"
"context"
"log/slog"
"time"
)
type runningLoop struct{}
// RunningLoop returns the [EventLoop] running in the current context.
// If no EventLoop is running, this function will panic.
// This function should not generally be called from a manually launched goroutine.
func RunningLoop(ctx context.Context) *EventLoop {
return ctx.Value(runningLoop{}).(*EventLoop)
}
// RunningLoopMaybe returns the [EventLoop] running in the current context,
// or nil with ok == false if no loop is running.
func RunningLoopMaybe(ctx context.Context) (loop *EventLoop, ok bool) {
loop, ok = ctx.Value(runningLoop{}).(*EventLoop)
return loop, ok
}
// EventLoop implements the core mechanism for processing callbacks and I/O events.
type EventLoop struct {
pendingCallbacks callbackQueue
callbacksFromThread chan *Callback
callbacksDoneFut *Future[any]
poller Poller
currentTasks []tasker
}
// NewEventLoop constructs a new [EventLoop].
func NewEventLoop() *EventLoop {
return &EventLoop{
callbacksFromThread: make(chan *Callback, 100),
}
}
// Run starts the event loop with the given coroutine as the main task.
// The loop will exit once the main task has exited and there are no pending callbacks.
func (e *EventLoop) Run(ctx context.Context, main Coroutine1) error {
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
var err error
if e.poller, err = NewPoller(); err != nil {
return err
}
defer e.poller.Close()
ctx = context.WithValue(ctx, runningLoop{}, e)
mainTask := main.SpawnTask(ctx).Future().AddDoneCallback(func(err error) {
if err != nil {
cancel(err)
}
})
for ctx.Err() == nil {
e.addCallbacksFromThread(ctx)
e.runReadyCallbacks(ctx)
if e.callbacksDoneFut != nil && e.pendingCallbacks.Empty() {
e.callbacksDoneFut.SetResult(nil, nil)
e.callbacksDoneFut = nil
continue
}
if ctx.Err() != nil || (mainTask.HasResult() && e.pendingCallbacks.Empty()) {
break
}
timeout := time.Second * 30
if !e.pendingCallbacks.Empty() {
timeout = e.pendingCallbacks.TimeUntilNext()
}
if deadline, ok := ctx.Deadline(); ok {
untilDeadline := time.Until(deadline)
if untilDeadline < timeout {
timeout = untilDeadline
}
}
if err := e.poller.Wait(timeout); err != nil {
return err
}
}
return context.Cause(ctx)
}
func (e *EventLoop) addCallbacksFromThread(ctx context.Context) {
for ctx.Err() == nil {
select {
case callback := <-e.callbacksFromThread:
e.pendingCallbacks.Add(callback)
default:
return
}
}
}
func (e *EventLoop) runReadyCallbacks(ctx context.Context) {
for ctx.Err() == nil && e.pendingCallbacks.RunNext() {
}
}
// withTask pushes the currently executing task to the top of the task stack
// so that [EventLoop.Yield] knows what task's yielder to use.
func (e *EventLoop) withTask(t tasker, step func()) {
e.currentTasks = append(e.currentTasks, t)
step()
if e.currentTask() != t {
panic("context switched from unexpected task")
}
e.currentTasks = e.currentTasks[:len(e.currentTasks)-1]
}
func (e *EventLoop) currentTask() tasker {
return e.currentTasks[len(e.currentTasks)-1]
}
// Yield yields control to the event loop for one tick, allowing pending callbacks and I/O to be processed.
func (e *EventLoop) Yield(ctx context.Context, fut Futurer) error {
return e.currentTask().yield(ctx, fut)
}
// ScheduleCallback schedules a callback to be executed after the given duration.
func (e *EventLoop) ScheduleCallback(delay time.Duration, callback func()) *Callback {
handle := NewCallback(delay, callback)
e.pendingCallbacks.Add(handle)
return handle
}
// RunCallback schedules a callback for immediate execution by the event loop.
// Not threadsafe; use [EventLoop.RunCallbackThreadsafe] to schedule callbacks from other threads.
func (e *EventLoop) RunCallback(callback func()) {
e.ScheduleCallback(0, callback)
}
// RunCallbackThreadsafe schedules a callback for immediate execution on the event loop's thread.
func (e *EventLoop) RunCallbackThreadsafe(ctx context.Context, callback func()) {
e.callbacksFromThread <- NewCallback(0, callback)
if e.poller != nil {
if err := e.poller.WakeupThreadsafe(); err != nil {
slog.WarnContext(ctx, "could not wake up event loop from thread", slog.Any("error", err))
}
}
}
// WaitForCallbacks returns a [Future] that will complete once there are no pending callback functions.
func (e *EventLoop) WaitForCallbacks() *Future[any] {
if e.callbacksDoneFut == nil {
e.callbacksDoneFut = NewFuture[any]()
}
return e.callbacksDoneFut
}
// Pipe creates two streams, where writing to w will make the written data available from r.
func (e *EventLoop) Pipe() (r, w *AsyncStream, err error) {
rf, wf, err := e.poller.Pipe()
if err != nil {
return nil, nil, err
}
return NewAsyncStream(rf), NewAsyncStream(wf), nil
}
// Dial opens a new network connection.
func (e *EventLoop) Dial(ctx context.Context, network, address string) (*AsyncStream, error) {
f, err := e.poller.Dial(ctx, network, address)
if err != nil {
return nil, err
}
return NewAsyncStream(f), nil
}
// DialLines is a convenience method that calls [EventLoop.Dial] followed by [AsyncStream.Lines].
// The connection attempt will be deferred until the [AsyncIterable] is ranged over.
// If the connection fails, the connection error will be returned immediately on the first iteration.
func (e *EventLoop) DialLines(ctx context.Context, network, address string) AsyncIterable[[]byte] {
return AsyncIter(func(yield func([]byte) error) error {
stream, err := e.Dial(ctx, network, address)
if err != nil {
return err
}
return stream.Lines(ctx).YieldTo(yield)
})
}
// Callback is a handle to a callback scheduled to be run by an [EventLoop].
type Callback struct {
callback func()
when time.Time
// queue == nil && index < 0 if the callback has not been scheduled
// or has already run
queue *callbackQueue
index int
}
// NewCallback creates a new handle to a callback specified to run after the given amount of time.
//
// Calling this function will not actually schedule the callback to be run.
// Use EventLoop.ScheduleCallback instead.
func NewCallback(duration time.Duration, callback func()) *Callback {
return &Callback{
callback: callback,
when: time.Now().Add(duration),
index: -2,
}
}
// Cancel removes this callback from its callback queue, preventing it from being run.
// If this callback is not currently scheduled, this method is a no-op and will return false.
func (c *Callback) Cancel() bool {
if c.queue != nil {
return c.queue.Remove(c)
}
return false
}
// callbackQueue is a priority queue of callbacks
// sorted so the topmost callback is the one scheduled to run the soonest.
type callbackQueue []*Callback
// Len implements [heap.Interface].
func (r *callbackQueue) Len() int {
return len(*r)
}
// Less implements [heap.Interface].
func (r *callbackQueue) Less(i, j int) bool {
return (*r)[i].when.Before((*r)[j].when)
}
// Swap implements [heap.Interface].
func (r *callbackQueue) Swap(i, j int) {
(*r)[i].index = j
(*r)[j].index = i
(*r)[i], (*r)[j] = (*r)[j], (*r)[i]
}
// Push implements [heap.Interface].
func (r *callbackQueue) Push(x any) {
callback := x.(*Callback)
callback.index = r.Len()
callback.queue = r
*r = append(*r, callback)
}
// Pop implements [heap.Interface].
func (r *callbackQueue) Pop() (v any) {
n := len(*r)
callback := (*r)[n-1]
*r = (*r)[:n-1]
// remove association to the queue
// so Remove behaves correctly if called multiple times
callback.index = -1
callback.queue = nil
return v
}
// Remove removes a callback from the queue, effectively cancelling it.
// Returns true if the callback was successfully removed,
// and false if the callback is not in this queue.
func (r *callbackQueue) Remove(callback *Callback) bool {
if callback.queue == nil || callback.queue != r || callback.index < 0 {
return false
}
heap.Remove(r, callback.index)
return true
}
// Peek returns the next callback to run without modifying the queue.
// Will panic if the queue is empty.
func (r *callbackQueue) Peek() *Callback {
return (*r)[0]
}
// Add adds a new callback to the queue.
func (r *callbackQueue) Add(c *Callback) {
heap.Push(r, c)
}
// RunNext runs the topmost callback in the queue.
// Returns false if there are no callbacks pending
// or the topmost callback is not due.
func (r *callbackQueue) RunNext() bool {
if r.Empty() || r.TimeUntilNext() > 0 {
return false
}
head := r.Peek()
heap.Pop(r)
head.callback()
return true
}
// TimeUntilNext returns the time until the topmost callback in the queue is scheduled to run.
func (r *callbackQueue) TimeUntilNext() time.Duration {
return time.Until(r.Peek().when)
}
// Empty reports whether the queue is empty.
func (r *callbackQueue) Empty() bool {
return r.Len() == 0
}