-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheventloop.go
More file actions
625 lines (569 loc) · 14.8 KB
/
eventloop.go
File metadata and controls
625 lines (569 loc) · 14.8 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
package ramune
import (
"context"
"fmt"
"time"
)
// pendingPollDefault is the wakeCh poll interval used when hasPendingLocked
// reports work in flight but no JS-side timer drives the next deadline.
// Without it, the loop spins as fast as r.dispatch can complete (which is
// JS-eval bounded). Wake() is called by every async manager and the native
// Promise bridge, so this is mostly just a safety-net cap if Wake races.
const pendingPollDefault = 10 * time.Millisecond
// installEventLoop sets up the JavaScript event loop infrastructure.
// Must be called on the dedicated JSC goroutine.
func (r *Runtime) installEventLoop() error {
return r.execLocked(eventLoopJSSource())
}
// Wake signals the event loop to process events immediately.
// Safe to call from any goroutine. Non-blocking.
func (r *Runtime) Wake() {
select {
case r.wakeCh <- struct{}{}:
default:
}
}
// Tick processes one round of the event loop (immediates + ready timers).
// Returns true if there are still pending timers or immediates.
func (r *Runtime) Tick() (bool, error) {
if r.closed.Load() {
return false, ErrAlreadyClosed
}
var pending bool
var err error
r.dispatch(func() {
r.tickManagers()
if e := r.execLocked("__eventLoop.tick()"); e != nil {
err = e
return
}
r.drainMicrotasks()
pending = r.hasPendingLocked()
})
return pending, err
}
// tickManagers drains events from all async I/O managers.
// Must be called on the dedicated JSC goroutine.
func (r *Runtime) tickManagers() {
if r.bunSrv != nil {
r.bunSrv.processRequests(r)
if r.bunSrv.wsEnabled {
r.bunSrv.processWSEvents(r)
}
}
if r.fsMgr != nil {
r.fsMgr.processEvents(r)
}
if r.fswatchMgr != nil {
r.fswatchMgr.processEvents(r)
}
if r.procMgr != nil {
r.procMgr.processEvents(r)
}
// TCP server events must be processed before socket events so that
// accepted connections are registered in __activeSockets before
// their data events arrive.
if r.tcpSrvMgr != nil {
r.tcpSrvMgr.processEvents(r)
}
if r.sockMgr != nil {
r.sockMgr.processEvents(r)
}
if r.udpMgr != nil {
r.udpMgr.processEvents(r)
}
if r.webviewMgr != nil {
r.webviewMgr.processEvents(r)
}
if r.workerMgr != nil {
r.workerMgr.processEvents(r)
}
if r.http2Mgr != nil {
r.http2Mgr.processEvents(r)
}
// Process fetch events before stream events so ReadableStream
// controllers are registered before chunks arrive.
if r.fetchMgr != nil {
r.fetchMgr.processEvents(r)
}
if r.streamMgr != nil {
r.streamMgr.processEvents(r)
}
for _, m := range r.customTickMgrs {
m.ProcessEvents(r)
}
}
// RunEventLoop processes the event loop until all pending operations complete.
// For short-lived scripts (timers, promises), the default timeout is 30 seconds.
// If an HTTP server (Ramune.serve) is active, the loop runs indefinitely.
func (r *Runtime) RunEventLoop() error {
timeout := 30 * time.Second
if r.bunSrv != nil && r.bunSrv.hasActive() {
timeout = 365 * 24 * time.Hour
}
return r.RunEventLoopFor(timeout)
}
// RunEventLoopFor processes the event loop until all timers complete
// or the timeout is reached.
func (r *Runtime) RunEventLoopFor(timeout time.Duration) error {
if r.closed.Load() {
return ErrAlreadyClosed
}
deadline := time.Now().Add(timeout)
for {
var pending bool
var delay time.Duration
var err error
r.dispatch(func() {
r.tickManagers()
if e := r.execLocked("__eventLoop.tick()"); e != nil {
err = e
return
}
pending = r.hasPendingLocked()
if pending {
delay = r.nextDelayLocked()
if delay <= 0 {
delay = pendingPollDefault
}
}
})
if err != nil {
return err
}
if !pending {
r.fireOnReady()
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("ramune: event loop timeout after %v", timeout)
}
if delay > 0 {
remaining := time.Until(deadline)
if delay > remaining {
delay = remaining
}
timer := time.NewTimer(delay)
select {
case <-r.wakeCh:
timer.Stop()
case <-timer.C:
}
}
}
}
// EvalAsync evaluates JavaScript code that may return a Promise,
// runs the event loop until the Promise resolves, and returns the result.
func (r *Runtime) EvalAsync(code string) (*Value, error) {
if r.closed.Load() {
return nil, ErrAlreadyClosed
}
// Set up promise resolution tracking and wrap in Promise.resolve
// so both sync values and Promises are handled uniformly.
setup := fmt.Sprintf(
`globalThis.__asyncDone=false;globalThis.__asyncResult=undefined;globalThis.__asyncError=undefined;`+
`Promise.resolve(%s).then(`+
`function(v){globalThis.__asyncResult=v;globalThis.__asyncDone=true;},`+
`function(e){globalThis.__asyncError=String(e);globalThis.__asyncDone=true;});`,
code)
if err := r.Exec(setup); err != nil {
return nil, err
}
return r.awaitAsyncResult(30 * time.Second)
}
// awaitAsyncResult polls the event loop until __asyncDone is true.
func (r *Runtime) awaitAsyncResult(timeout time.Duration) (*Value, error) {
deadline := time.Now().Add(timeout)
for {
var done bool
var hasErr bool
var errMsg string
var result *Value
var evalErr error
var pending bool
var delay time.Duration
var needRecheck bool
r.dispatch(func() {
r.tickManagers()
done = r.evalBoolLocked("globalThis.__asyncDone")
if done {
hasErr = !r.evalIsUndefinedLocked("globalThis.__asyncError")
if hasErr {
errMsg = r.evalStringLocked("globalThis.__asyncError")
} else {
result, evalErr = r.evalLocked("globalThis.__asyncResult")
}
return
}
if e := r.execLocked("__eventLoop.tick()"); e != nil {
evalErr = e
return
}
done = r.evalBoolLocked("globalThis.__asyncDone")
if done {
needRecheck = true
return
}
pending = r.hasPendingLocked()
if pending {
delay = r.nextDelayLocked()
if delay <= 0 {
delay = pendingPollDefault
}
}
})
if evalErr != nil {
return nil, evalErr
}
if done && !needRecheck {
if hasErr {
return nil, &JSError{Context: "EvalAsync", Message: errMsg}
}
return result, evalErr
}
if needRecheck {
continue
}
if !pending {
return nil, &JSError{Context: "EvalAsync", Message: "Promise did not resolve and no pending timers"}
}
if time.Now().After(deadline) {
return nil, &JSError{Context: "EvalAsync", Message: "timeout waiting for Promise"}
}
if delay > 0 {
remaining := time.Until(deadline)
if delay > remaining {
delay = remaining
}
timer := time.NewTimer(delay)
select {
case <-r.wakeCh:
timer.Stop()
case <-timer.C:
}
}
}
}
// RunEventLoopWithContext processes the event loop until all timers complete
// or the context is cancelled/expired.
func (r *Runtime) RunEventLoopWithContext(ctx context.Context) error {
if r.closed.Load() {
return ErrAlreadyClosed
}
deadline, ok := ctx.Deadline()
if !ok {
deadline = time.Now().Add(30 * time.Second)
}
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
var pending bool
var delay time.Duration
var err error
r.dispatch(func() {
r.tickManagers()
if e := r.execLocked("__eventLoop.tick()"); e != nil {
err = e
return
}
pending = r.hasPendingLocked()
if pending {
delay = r.nextDelayLocked()
if delay <= 0 {
delay = pendingPollDefault
}
}
})
if err != nil {
return err
}
if !pending {
r.fireOnReady()
return nil
}
if time.Now().After(deadline) {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ramune: event loop timeout")
}
if delay > 0 {
remaining := time.Until(deadline)
if delay > remaining {
delay = remaining
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-r.wakeCh:
timer.Stop()
case <-timer.C:
}
}
}
}
// EvalAsyncWithContext evaluates JavaScript code that may return a Promise,
// runs the event loop until the Promise resolves or the context is
// cancelled/expired, and returns the result.
func (r *Runtime) EvalAsyncWithContext(ctx context.Context, code string) (*Value, error) {
if r.closed.Load() {
return nil, ErrAlreadyClosed
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
// Set up promise resolution tracking and wrap in Promise.resolve
// so both sync values and Promises are handled uniformly.
setup := fmt.Sprintf(
`globalThis.__asyncDone=false;globalThis.__asyncResult=undefined;globalThis.__asyncError=undefined;`+
`Promise.resolve(%s).then(`+
`function(v){globalThis.__asyncResult=v;globalThis.__asyncDone=true;},`+
`function(e){globalThis.__asyncError=String(e);globalThis.__asyncDone=true;});`,
code)
if err := r.Exec(setup); err != nil {
return nil, err
}
deadline, hasDeadline := ctx.Deadline()
if !hasDeadline {
deadline = time.Now().Add(30 * time.Second)
}
timeout := time.Until(deadline)
return r.awaitAsyncResultWithContext(ctx, timeout)
}
// awaitAsyncResultWithContext polls the event loop until __asyncDone is true
// or the context is cancelled/expired.
func (r *Runtime) awaitAsyncResultWithContext(ctx context.Context, timeout time.Duration) (*Value, error) {
deadline := time.Now().Add(timeout)
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
var done bool
var hasErr bool
var errMsg string
var result *Value
var evalErr error
var pending bool
var delay time.Duration
var needRecheck bool
r.dispatch(func() {
r.tickManagers()
done = r.evalBoolLocked("globalThis.__asyncDone")
if done {
hasErr = !r.evalIsUndefinedLocked("globalThis.__asyncError")
if hasErr {
errMsg = r.evalStringLocked("globalThis.__asyncError")
} else {
result, evalErr = r.evalLocked("globalThis.__asyncResult")
}
return
}
if e := r.execLocked("__eventLoop.tick()"); e != nil {
evalErr = e
return
}
done = r.evalBoolLocked("globalThis.__asyncDone")
if done {
needRecheck = true
return
}
pending = r.hasPendingLocked()
if pending {
delay = r.nextDelayLocked()
if delay <= 0 {
delay = pendingPollDefault
}
}
})
if evalErr != nil {
return nil, evalErr
}
if done && !needRecheck {
if hasErr {
return nil, &JSError{Context: "EvalAsyncWithContext", Message: errMsg}
}
return result, evalErr
}
if needRecheck {
continue
}
if !pending {
return nil, &JSError{Context: "EvalAsyncWithContext", Message: "Promise did not resolve and no pending timers"}
}
if time.Now().After(deadline) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, &JSError{Context: "EvalAsyncWithContext", Message: "timeout waiting for Promise"}
}
if delay > 0 {
remaining := time.Until(deadline)
if delay > remaining {
delay = remaining
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return nil, ctx.Err()
case <-r.wakeCh:
timer.Stop()
case <-timer.C:
}
}
}
}
// --- internal helpers (must be called on the dedicated JSC goroutine) ---
// hasPendingLocked returns true if there are pending timers, immediates,
// or active async processes.
func (r *Runtime) hasPendingLocked() bool {
if r.evalBoolLocked("__eventLoop.hasPending()") {
return true
}
// Check for active async processes.
if r.procMgr != nil && r.procMgr.hasActive() {
return true
}
// Check for active async sockets.
if r.sockMgr != nil && r.sockMgr.hasActive() {
return true
}
// Check for active TCP servers.
if r.tcpSrvMgr != nil && r.tcpSrvMgr.hasActive() {
return true
}
// Check for active UDP sockets.
if r.udpMgr != nil && r.udpMgr.hasActive() {
return true
}
// Check for active webview windows.
if r.webviewMgr != nil && r.webviewMgr.hasActive() {
return true
}
// Check for active Bun server.
if r.bunSrv != nil && r.bunSrv.hasActive() {
return true
}
// Check for active workers.
if r.workerMgr != nil && r.workerMgr.hasActive() {
return true
}
// Check for active HTTP/2 sessions.
if r.http2Mgr != nil && r.http2Mgr.hasActive() {
return true
}
// Check for pending Atomics.waitAsync operations.
if r.waitAsyncCount.Load() > 0 {
return true
}
// Check for in-flight Go *promise.Promise[T] -> JS Promise bridges.
// Without this, RunEventLoopFor can return before the bridge goroutine
// dispatches its resolve/reject when the JS side has no other pending
// timers/managers.
if r.nativePromiseCount.Load() > 0 {
return true
}
// Check for pending async fs operations.
if r.fsMgr != nil && r.fsMgr.hasActive() {
return true
}
// Check for active streams.
if r.streamMgr != nil && r.streamMgr.hasActive() {
return true
}
// Check for active fetch requests.
if r.fetchMgr != nil && r.fetchMgr.hasActive() {
return true
}
for _, m := range r.customTickMgrs {
if m.HasActive() {
return true
}
}
return false
}
func eventLoopJSSource() string {
return `
(function() {
var __timers = {};
var __nextId = 1;
var __immediates = [];
globalThis.__eventLoop = {
tick: function() {
// Process immediates first (like Node.js setImmediate).
var imms = __immediates.slice();
__immediates = [];
for (var i = 0; i < imms.length; i++) {
try { imms[i](); } catch(e) {}
}
// Process ready timers.
var now = Date.now();
var ids = Object.keys(__timers);
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var t = __timers[id];
if (t && now >= t.fireAt) {
if (t.interval) {
t.fireAt = now + t.delay;
} else {
delete __timers[id];
}
try { t.fn(); } catch(e) {}
}
}
},
hasPending: function() {
return Object.keys(__timers).length > 0 || __immediates.length > 0;
},
nextDelay: function() {
if (__immediates.length > 0) return 0;
var now = Date.now();
var min = Infinity;
var ids = Object.keys(__timers);
for (var i = 0; i < ids.length; i++) {
var t = __timers[ids[i]];
if (t) {
var d = t.fireAt - now;
if (d < min) min = d;
}
}
return min === Infinity ? -1 : Math.max(0, min);
}
};
globalThis.setTimeout = function(fn, delay) {
if (typeof fn !== 'function') return 0;
var id = __nextId++;
__timers[id] = { fn: fn, fireAt: Date.now() + (delay || 0), interval: false };
return id;
};
globalThis.clearTimeout = function(id) { delete __timers[id]; };
globalThis.setInterval = function(fn, delay) {
if (typeof fn !== 'function') return 0;
var id = __nextId++;
__timers[id] = { fn: fn, fireAt: Date.now() + (delay || 0), delay: delay || 0, interval: true };
return id;
};
globalThis.clearInterval = function(id) { delete __timers[id]; };
globalThis.setImmediate = function(fn) {
if (typeof fn === 'function') __immediates.push(fn);
return __nextId++;
};
globalThis.clearImmediate = function() {};
if (typeof globalThis.queueMicrotask === 'undefined') {
globalThis.queueMicrotask = function(fn) {
if (typeof fn !== 'function') throw new TypeError('Failed to execute queueMicrotask: parameter 1 is not of type Function');
Promise.resolve().then(fn);
};
}
})();
`
}