Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/webkit-scheduler-message-channel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

Improve `MixedScheduler` yield performance in Safari/WebKit by using `MessageChannel` to avoid nested-timer delays. This fallback applies in browser contexts without `setImmediate` or `scheduler.postTask`.
44 changes: 42 additions & 2 deletions packages/effect/src/Scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ const setMicrotask = (f: () => void) => {

type TaskScheduler = { readonly postTask: (task: () => void) => unknown }

type BrowserGlobal = {
readonly scheduler?: Partial<TaskScheduler>
readonly MessageChannel?: typeof MessageChannel
readonly window?: unknown
readonly importScripts?: unknown
}

// Browsers clamp nested `setTimeout(f, 0)` calls to 4ms, so a fiber that
// yields repeatedly would wait that long on every yield. The Prioritized Task
// Scheduling API queues an unclamped task, in FIFO order with other tasks of
Expand All @@ -139,6 +146,31 @@ const postTask = (scheduler: TaskScheduler, f: () => void) => {
}
}

interface ChannelTask {
f: (() => void) | undefined
next: ChannelTask | undefined
}

const makeChannel = (channel: MessageChannel) => {
let head: ChannelTask = { f: undefined, next: undefined }
let tail = head
channel.port1.onmessage = () => {
head = head.next!
const f = head.f
head.f = undefined
f?.()
}
return (f: () => void) => {
channel.port2.postMessage(undefined)
const task: ChannelTask = tail = tail.next = { f, next: undefined }
return (): void => {
task.f = undefined
}
}
}

let postChannel: ((f: () => void) => () => void) | undefined

const setTimer: (f: () => void) => () => void =
typeof (globalThis as { setImmediate?: unknown }).setImmediate === "function"
? (f) => {
Expand All @@ -148,8 +180,16 @@ const setTimer: (f: () => void) => () => void =
return (): void => globalThis.clearImmediate(timer)
}
: (f) => {
const scheduler = (globalThis as { scheduler?: Partial<TaskScheduler> }).scheduler
if (typeof scheduler?.postTask === "function") return postTask(scheduler as TaskScheduler, f)
const global = globalThis as BrowserGlobal
if (typeof global.scheduler?.postTask === "function") return postTask(global.scheduler as TaskScheduler, f)
// Keep Cloudflare Workers on timers: they are unclamped there, and their
// global-scope errors trigger the microtask fallback in `setImmediate` below.
if (
typeof global.MessageChannel === "function" &&
(typeof global.window === "object" || typeof global.importScripts === "function")
) {
return (postChannel ??= makeChannel(new global.MessageChannel()))(f)
}
const timer = setTimeout(f, 0)
return (): void => clearTimeout(timer)
}
Expand Down
38 changes: 38 additions & 0 deletions packages/effect/test/Scheduler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ describe("Scheduler", () => {

it("yields through scheduler.postTask and cancels a run made redundant by flush", () => {
const posted: Array<() => void> = []
vi.stubGlobal("window", {})
vi.stubGlobal("scheduler", { postTask: (task: () => void) => posted.push(task) })
const dispatcher = new Browser.MixedScheduler().makeDispatcher()
let runs = 0
Expand All @@ -219,6 +220,33 @@ describe("Scheduler", () => {
assert.strictEqual(runs, 1)
})

it.each([
["window", {}],
["importScripts", () => {}]
])("falls back to MessageChannel in browser contexts (%s)", (globalName, value) => {
// The module keeps the first channel it opens, so each case reuses it
messages.length = 0
vi.stubGlobal("scheduler", undefined)
vi.stubGlobal(globalName, value)
vi.stubGlobal("MessageChannel", FakeMessageChannel)

const d1 = new Browser.MixedScheduler().makeDispatcher()
const d2 = new Browser.MixedScheduler().makeDispatcher()
const order: Array<string> = []

d1.scheduleTask(() => order.push("d1"), 0)
d2.scheduleTask(() => order.push("d2"), 0)

d1.flush()
d1.scheduleTask(() => order.push("d1-next"), 0)

messages[0]()
assert.deepStrictEqual(order, ["d1"])
messages[1]()
messages[2]()
assert.deepStrictEqual(order, ["d1", "d2", "d1-next"])
})

it.each([undefined, {}])("falls back to a cancellable setTimeout (scheduler: %o)", (scheduler) => {
vi.stubGlobal("scheduler", scheduler)
const setTimeout = vi.spyOn(globalThis, "setTimeout")
Expand All @@ -245,6 +273,16 @@ describe("Scheduler", () => {
})
})

const messages: Array<() => void> = []
class FakeMessageChannel {
port1: { onmessage: (() => void) | null } = { onmessage: null }
port2 = {
postMessage: () => {
messages.push(() => this.port1.onmessage?.())
}
}
}

// The timer function is chosen when the module loads, so load a separate copy
// of the module while setImmediate is missing.
const Browser: typeof Scheduler = await (async () => {
Expand Down
Loading