|
| 1 | +// Support for `JavaScriptEventLoop.yieldInterval`: a clock that measures how long one drain of the |
| 2 | +// job queue has run, and a scheduler that continues the drain in a new JavaScript task. |
| 3 | + |
| 4 | +import JavaScriptKit |
| 5 | +import _Concurrency |
| 6 | + |
| 7 | +#if compiler(>=5.5) |
| 8 | + |
| 9 | +@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) |
| 10 | +extension JavaScriptEventLoop { |
| 11 | + |
| 12 | + #if hasFeature(Embedded) |
| 13 | + /// A point in time for measuring a drain of the job queue, in milliseconds of `performance.now()`. |
| 14 | + typealias DrainInstant = Double |
| 15 | + |
| 16 | + // `ContinuousClock` is unavailable in Embedded Swift, so use the JavaScript clock. |
| 17 | + func drainClockNow() -> DrainInstant { |
| 18 | + if performanceNow == nil { |
| 19 | + let performance = JSObject.global.performance.object! |
| 20 | + performanceNow = (performance, performance.now.function!) |
| 21 | + } |
| 22 | + return performanceNow!.now(this: performanceNow!.performance).number! |
| 23 | + } |
| 24 | + |
| 25 | + func hasRun(since start: DrainInstant, for interval: Duration) -> Bool { |
| 26 | + let (seconds, attoseconds) = interval.components |
| 27 | + let intervalMilliseconds = Double(seconds) * 1_000 + Double(attoseconds) / 1_000_000_000_000_000 |
| 28 | + return drainClockNow() - start >= intervalMilliseconds |
| 29 | + } |
| 30 | + #else |
| 31 | + /// A point in time for measuring a drain of the job queue. |
| 32 | + typealias DrainInstant = ContinuousClock.Instant |
| 33 | + |
| 34 | + func drainClockNow() -> DrainInstant { |
| 35 | + ContinuousClock.now |
| 36 | + } |
| 37 | + |
| 38 | + func hasRun(since start: DrainInstant, for interval: Duration) -> Bool { |
| 39 | + start.duration(to: .now) >= interval |
| 40 | + } |
| 41 | + #endif |
| 42 | + |
| 43 | + /// Runs `body` in a new JavaScript task, after the JavaScript event loop had a chance to run |
| 44 | + /// other tasks. Uses `setImmediate` where available (Node.js, Bun), else a `MessageChannel` |
| 45 | + /// message (browsers, Web Workers, Deno), else `setTimeout(body, 0)`. |
| 46 | + func queueHostTask(_ body: @escaping () -> Void) { |
| 47 | + if hostTaskScheduler == nil { |
| 48 | + hostTaskScheduler = Self.makeHostTaskScheduler() |
| 49 | + } |
| 50 | + hostTaskScheduler!(body) |
| 51 | + } |
| 52 | + |
| 53 | + private static func makeHostTaskScheduler() -> (@escaping () -> Void) -> Void { |
| 54 | + let global = JSObject.global |
| 55 | + if let setImmediate = global.setImmediate.function { |
| 56 | + return { body in |
| 57 | + _ = setImmediate( |
| 58 | + JSOneshotClosure { _ in |
| 59 | + body() |
| 60 | + return .undefined |
| 61 | + } |
| 62 | + ) |
| 63 | + } |
| 64 | + } |
| 65 | + if let messageChannel = global.MessageChannel.function { |
| 66 | + // Unlike `setTimeout`, a message is not clamped to 4 ms when timers nest. |
| 67 | + let channel = messageChannel.new(arguments: [JSValue]()) |
| 68 | + let sender = channel.port1.object! |
| 69 | + let postMessage = sender.postMessage.function! |
| 70 | + let pending = PendingHostTasks() |
| 71 | + let receiver = JSClosure { _ in |
| 72 | + pending.runAll() |
| 73 | + return .undefined |
| 74 | + } |
| 75 | + channel.port2.object!.onmessage = .object(receiver) |
| 76 | + return { body in |
| 77 | + pending.bodies.append(body) |
| 78 | + // The scheduler owns `receiver`, which the channel calls. |
| 79 | + withExtendedLifetime(receiver) { |
| 80 | + _ = postMessage(this: sender, JSValue.undefined) |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + let setTimeout = global.setTimeout.function! |
| 85 | + return { body in |
| 86 | + _ = setTimeout( |
| 87 | + JSOneshotClosure { _ in |
| 88 | + body() |
| 89 | + return .undefined |
| 90 | + }, |
| 91 | + 0 |
| 92 | + ) |
| 93 | + } |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +/// Bodies that wait for the `MessageChannel` message of `JavaScriptEventLoop.queueHostTask(_:)`. |
| 98 | +private final class PendingHostTasks { |
| 99 | + var bodies: [() -> Void] = [] |
| 100 | + |
| 101 | + func runAll() { |
| 102 | + let bodies = self.bodies |
| 103 | + self.bodies = [] |
| 104 | + for body in bodies { |
| 105 | + body() |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +#endif |
0 commit comments