diff --git a/.changeset/cloudflare-cross-request-scheduler.md b/.changeset/cloudflare-cross-request-scheduler.md index 7d2f278612..6d261117b5 100644 --- a/.changeset/cloudflare-cross-request-scheduler.md +++ b/.changeset/cloudflare-cross-request-scheduler.md @@ -3,4 +3,4 @@ "@effect/platform-cloudflare": minor --- -Add `CloudflareScheduler` and `Scheduler.captureAsyncContext` so Worker fibers woken by a later request resume in the request that owns them. +Add `CloudflareScheduler` and `Scheduler.captureAsyncContext` so Worker fibers woken by another request resume in the request that owns them, and that request keeps running until they do. diff --git a/packages/effect/src/Scheduler.ts b/packages/effect/src/Scheduler.ts index 7f8708587a..f356d00391 100644 --- a/packages/effect/src/Scheduler.ts +++ b/packages/effect/src/Scheduler.ts @@ -64,8 +64,8 @@ export interface Scheduler { * Each captured context resumes its fiber once. `runInAsyncScope` either calls * `fn` synchronously, or arranges to call it exactly once later and returns. * A fiber whose resumption is still pending defers interrupts, and other - * resumptions, until it lands. `emitDestroy` is called when `runInAsyncScope` - * returns. + * resumptions, until it lands. A fiber interrupted before its start lands never + * runs. `emitDestroy` is called when `runInAsyncScope` returns. * * **Gotchas** * diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index dd64fa8a8f..d87ccbbe8f 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -544,6 +544,7 @@ export class FiberImpl implements Fiber.Fiber { this._asyncContext = undefined this._resuming = false this._overtaken = undefined + this._pendingStart = false this.cache.runtimeMetrics?.recordFiberStart(this.context) this.supervisor = this.cache.supervisor this.supervisor?.onStart(this, parent) @@ -572,6 +573,8 @@ export class FiberImpl implements Fiber.Fiber { declare _resuming: boolean // A resumption that arrived while an interrupt was still landing declare _overtaken: Primitive | undefined + // The fiber's start was handed to the captured async context and has not run + declare _pendingStart: boolean // set in setContext declare context: Context.Context @@ -716,6 +719,14 @@ export class FiberImpl implements Fiber.Fiber { this._overtaken = undefined interrupt = this._interruptedCause !== undefined } + if (this._pendingStart) { + // A fiber interrupted before it starts never runs, whichever landed first + this._pendingStart = false + if (interrupt) { + interrupt = false + effect = failCause(this._interruptedCause!) as any + } + } this.evaluate(effect) if (interrupt && this._exit === undefined && this.interruptible && !this._running) { this.evaluate(failCause(this._interruptedCause!) as any) @@ -5725,6 +5736,7 @@ export const forkUnsafe = ( } else { // Preserve the fork context rather than the dispatcher's context. child._asyncContext = captureAsyncContext(child.cache.scheduler) + child._pendingStart = child._asyncContext !== undefined && child._asyncContext.constructor !== AsyncResource // Cancel the deferred start if an interrupt runs first. let resumed = false child.yieldWith(() => { diff --git a/packages/effect/test/Effect.test.ts b/packages/effect/test/Effect.test.ts index 44388ec020..b8dc1829e4 100644 --- a/packages/effect/test/Effect.test.ts +++ b/packages/effect/test/Effect.test.ts @@ -5750,6 +5750,32 @@ describe("Effect", () => { assert.isTrue(Exit.hasInterrupts(fiber.pollUnsafe()!)) }) } + for (const dispatched of [false, true]) { + it(`interrupts a fork before it starts, ${dispatched ? "after" : "before"} its start is dispatched`, async () => { + const { land, scheduler } = makeScheduler() + const seen: Array = [] + let child!: Fiber.Fiber + Effect.runFork( + Effect.forkDetach(Effect.sync(() => { + seen.push(current()) + return 42 + })).pipe(Effect.tap((fiber) => + Effect.sync(() => { + child = fiber + if (!dispatched) fiber.interruptUnsafe() + }) + )), + { scheduler } + ) + if (dispatched) { + await Promise.resolve() + storage.run("waker", () => child.interruptUnsafe()) + } + await land() + assert.deepStrictEqual(seen, []) + assert.isTrue(Exit.hasInterrupts(child.pollUnsafe()!)) + }) + } }) const runWithStore = (store: string | undefined, effect: Effect.Effect): Promise => diff --git a/packages/platform/cloudflare/src/CloudflareScheduler.ts b/packages/platform/cloudflare/src/CloudflareScheduler.ts index 9028639d54..1368d67377 100644 --- a/packages/platform/cloudflare/src/CloudflareScheduler.ts +++ b/packages/platform/cloudflare/src/CloudflareScheduler.ts @@ -4,7 +4,7 @@ * @stability stable * @since 4.2.0 */ -import * as Duration from "effect/Duration" +import { waitUntil } from "cloudflare:workers" import * as Layer from "effect/Layer" import * as Scheduler from "effect/Scheduler" @@ -16,19 +16,23 @@ const AsyncResource: (new(type: string) => Scheduler.AsyncContext) | undefined = } })() -const defaultKeepAliveMillis = 30_000 -// Longer delays overflow to an immediate timer -const maxTimerMillis = 2_147_483_647 +const compatibilityFlags: Record | undefined = (globalThis as any).Cloudflare + ?.compatibilityFlags + +// Entering another request's AsyncResource only fails when AsyncLocalStorage +// snapshots are bound to their request. Otherwise it succeeds in the wrong +// request, so every resumption goes through the owner's promise instead. +const canEnter = AsyncResource !== undefined && + compatibilityFlags?.bind_asynclocalstorage_snapshot_to_request !== false const run = (task: () => void): void => task() const noop = (): void => {} -const setKeepAlive = (millis: number): unknown => { +const keepOwnerAlive = (promise: Promise): void => { try { - return setTimeout(noop, millis) + waitUntil(promise) } catch { - // Workers do not allow timers in global scope - return undefined + // Outside a request, for example in global scope, there is no owner to keep } } @@ -36,57 +40,55 @@ const setKeepAlive = (millis: number): unknown => { // Entering the AsyncResource resumes the fiber synchronously with the owner's // AsyncLocalStorage state. workerd refuses that from any other request, so the // resumption is then handed to a promise the owner created: workerd runs its -// reactions in the owner's IoContext, or drops them if the owner has ended. -class RequestContext implements Scheduler.AsyncContext { - readonly resource: Scheduler.AsyncContext +// reactions in the owner's IoContext. The owner waits on that promise, so it +// stays alive after responding until the fiber resumes. +class OwnerContext implements Scheduler.AsyncContext { + readonly resource: Scheduler.AsyncContext | undefined readonly resolve: (task: () => void) => void - // Keeps the owner from being cancelled as hung while the fiber waits. Timers - // belong to the request that set them, so only the owner clears it. - readonly timer: unknown - constructor(Resource: new(type: string) => Scheduler.AsyncContext, keepAliveMillis: number | undefined) { - this.resource = new Resource("effect/Fiber") + constructor() { + this.resource = AsyncResource === undefined ? undefined : new AsyncResource("effect/Fiber") let resolve!: (task: () => void) => void - new Promise<() => void>((resolve_) => { - resolve = resolve_ - }).then(run) + keepOwnerAlive( + new Promise<() => void>((resolve_) => { + resolve = resolve_ + }).then(run) + ) this.resolve = resolve - this.timer = keepAliveMillis === undefined ? undefined : setKeepAlive(keepAliveMillis) } runInAsyncScope(fn: (this: This, arg: Arg) => void, thisArg: This, arg: Arg): void { - let entered = false - try { - this.resource.runInAsyncScope( - () => { - entered = true - this.clearKeepAlive() - fn.call(thisArg, arg) - }, - undefined, - undefined - ) - } catch (error) { - if (entered) throw error - this.resolve(() => { - this.clearKeepAlive() - fn.call(thisArg, arg) - }) + const resource = this.resource + if (canEnter) { + let entered = false + try { + resource!.runInAsyncScope( + () => { + entered = true + fn.call(thisArg, arg) + }, + undefined, + undefined + ) + return this.resolve(noop) + } catch (error) { + if (entered) { + this.resolve(noop) + throw error + } + } } - } - - clearKeepAlive(): void { - if (this.timer !== undefined) clearTimeout(this.timer as any) + this.resolve(() => resource === undefined ? fn.call(thisArg, arg) : resource.runInAsyncScope(fn, thisArg, arg)) } emitDestroy(): void { - this.resource.emitDestroy() + this.resource?.emitDestroy() } } /** * A synchronous scheduler that resumes each fiber in the Worker request that - * owns it. + * owns it, and keeps that request running while the fiber waits. * * **When to use** * @@ -94,7 +96,7 @@ class RequestContext implements Scheduler.AsyncContext { * a module-scope `ManagedRuntime`, `Deferred`, `Queue`, `PubSub`, or * `Semaphore`. Pass an instance as the `scheduler` option to Effect runners. * For a shared runtime, build it with - * `ManagedRuntime.make(AppLayer.pipe(Layer.provideMerge(CloudflareScheduler.layer())))`. + * `ManagedRuntime.make(AppLayer.pipe(Layer.provideMerge(CloudflareScheduler.layer)))`. * Also pass `{ scheduler: new CloudflareScheduler() }` to the runtime runners, * including `runFork` and `runPromise`: the layer alone does not configure callers * waiting for lazy initialization. To initialize explicitly, run @@ -109,53 +111,50 @@ class RequestContext implements Scheduler.AsyncContext { * waking request continues without waiting for it. Inside a Durable Object, * requests share these, so fibers resume immediately. * - * While a fiber waits, a timer keeps workerd from cancelling its owner as hung - * for up to `keepAlive` (30 seconds by default). Without it, a request that - * awaits only work another request will finish is cancelled, because a pending - * promise does not count as pending work. The timer does not extend a request - * that has already responded; use `ctx.waitUntil` for that. Pass - * `keepAlive: false` to disable it. + * Each waiting fiber is registered with its owner through `waitUntil` from + * `cloudflare:workers`, so the owner keeps running after it responds until + * the fiber resumes. The module imports `cloudflare:workers`, so it only loads + * in workerd. * * **Gotchas** * - * A fiber whose owner has ended cannot resume: workerd drops the resumption and - * logs a warning, and the fiber never completes or runs its finalizers. - * Anything handed to it, such as a `Semaphore` permit or a `Queue` item, is - * lost. Keep the owner alive with `ctx.waitUntil` while its fibers may still - * be woken, or interrupt them before it ends. + * workerd cancels a request once nothing it waits on can make progress, and + * another request's fibers do not count. Then: * - * Owner resumption needs `node:async_hooks`, available with the `nodejs_compat` - * or `nodejs_als` compatibility flags, or a compatibility date of 2026-08-15 or - * later. Without it, fibers resume in the request that wakes them, and the - * owner's I/O objects cannot be used there. + * - A request that only waits on another request's work, such as a shared + * runtime's initialization, fails as hung. Give it work of its own to wait on. + * - A fiber whose owner was cancelled, or has finished after responding, can no + * longer resume. workerd drops the resumption and logs a warning, and the + * fiber never completes or runs its finalizers. Anything handed to it, such + * as a `Semaphore` permit or a `Queue` item, is lost. Interrupt such fibers + * before their owner runs out of work. * - * In a Durable Object, the keep-alive timer delays hibernation; consider - * `keepAlive: false` there. Synchronous execution does not yield to the event - * loop, so CPU-heavy work delays other requests. + * `waitUntil` work is also subject to the platform's limit on how long a + * request may run after responding. + * + * Owner resumption needs the `handle_cross_request_promise_resolution` + * compatibility flag, enabled by default from 2024-10-14; the constructor + * throws without it. `AsyncLocalStorage` state is restored with + * `node:async_hooks`, available with the `nodejs_compat` or `nodejs_als` + * flags. Without the `bind_asynclocalstorage_snapshot_to_request` flag, enabled + * by default from 2025-06-16, every resumption is handed to the owner, so fibers + * woken by their own request also resume a microtask later. + * + * Synchronous execution does not yield to the event loop, so CPU-heavy work + * delays other requests. * * @stability stable * @category models * @since 4.2.0 */ export class CloudflareScheduler extends Scheduler.MixedScheduler { - readonly keepAliveMillis: number | undefined - - constructor(options?: { - /** - * How long a waiting fiber keeps its owner request alive, or `false` to - * not keep it alive. - * - * @default "30 seconds" - */ - readonly keepAlive?: Duration.Input | false | undefined - }) { + constructor() { super("sync") - const keepAlive = options?.keepAlive - this.keepAliveMillis = keepAlive === false - ? undefined - : keepAlive === undefined - ? defaultKeepAliveMillis - : Math.min(Duration.toMillis(Duration.fromInputUnsafe(keepAlive)), maxTimerMillis) + if (compatibilityFlags?.handle_cross_request_promise_resolution === false) { + throw new Error( + "CloudflareScheduler requires the handle_cross_request_promise_resolution compatibility flag" + ) + } } /** @@ -163,19 +162,17 @@ export class CloudflareScheduler extends Scheduler.MixedScheduler { * * @since 4.2.0 */ - captureAsyncContext(): Scheduler.AsyncContext | undefined { - return AsyncResource === undefined ? undefined : new RequestContext(AsyncResource, this.keepAliveMillis) + captureAsyncContext(): Scheduler.AsyncContext { + return new OwnerContext() } } /** - * Creates a layer that installs a `CloudflareScheduler` for an application and - * its fibers. + * A layer that installs a `CloudflareScheduler` for an application and its + * fibers. * * @stability stable * @category layers * @since 4.2.0 */ -export const layer = (options?: { - readonly keepAlive?: Duration.Input | false | undefined -}): Layer.Layer => Layer.succeed(Scheduler.Scheduler, new CloudflareScheduler(options)) +export const layer: Layer.Layer = Layer.sync(Scheduler.Scheduler, () => new CloudflareScheduler()) diff --git a/packages/platform/cloudflare/test/CloudflareScheduler.test.ts b/packages/platform/cloudflare/test/CloudflareScheduler.test.ts index 8ae4646d25..55af2d8ea9 100644 --- a/packages/platform/cloudflare/test/CloudflareScheduler.test.ts +++ b/packages/platform/cloudflare/test/CloudflareScheduler.test.ts @@ -5,7 +5,41 @@ import * as path from "node:path" const sleep = (millis: number) => new Promise((resolve) => setTimeout(resolve, millis)) -describe("CloudflareScheduler", () => { +const bundle = (stdin?: string) => + esbuild.build({ + ...(stdin === undefined + ? { entryPoints: [path.join(import.meta.dirname, "fixtures/scheduler-worker.ts")] } + : { stdin: { contents: stdin, resolveDir: import.meta.dirname, loader: "ts" } }), + bundle: true, + format: "esm", + platform: "neutral", + write: false, + external: ["cloudflare:workers", "node:*"], + alias: { + "@effect/platform-cloudflare": path.join(import.meta.dirname, "../src") + } + }).then((result) => result.outputFiles[0].text) + +const makeMiniflare = (contents: string, compatibilityDate: string) => + new Miniflare({ + workers: [{ + config: { + name: "scheduler", + manifest: { + mainModule: "worker.mjs", + modules: { "worker.mjs": { type: "esm", contents } } + }, + compatibilityDate, + compatibilityFlags: ["nodejs_compat"], + env: { ROOM: { type: "durable-object", worker: "scheduler", exportName: "Room" } }, + exports: { Room: { type: "durable-object", storage: "sqlite" } } + } + }] + }) + +// Before 2025-06-16, workerd lets a request enter another request's +// AsyncResource, so owner detection cannot rely on it refusing +describe.each(["2026-07-01", "2025-01-01"])("CloudflareScheduler (compatibility date %s)", (compatibilityDate) => { let miniflare: Miniflare const get = (path: string) => miniflare.dispatchFetch(`http://localhost${path}`) const json = async (path: string) => { @@ -13,9 +47,9 @@ describe("CloudflareScheduler", () => { assert.strictEqual(response.status, 200, await response.clone().text()) return response.json() } - // Waits until `path` responds, then returns its body - const poll = async (path: string, until: (body: any) => boolean = () => true) => { - for (let i = 0; i < 100; i++) { + // Waits until `path` responds with a body matching `until` + const poll = async (path: string, until: (body: any) => boolean): Promise => { + for (let i = 0; i < 250; i++) { const response = await get(path) const body = response.status === 200 ? await response.json() : await response.arrayBuffer() if (response.status === 200 && until(body)) return body @@ -23,13 +57,7 @@ describe("CloudflareScheduler", () => { } throw new Error(`${path} did not respond in time`) } - // Request A parks a fiber, then request B wakes it - const park = async (park: string, wake: string) => { - const owner = get(park) - await poll(wake.replace("/wake", "/log")) - const waker = await json(wake) - return { owner: await owner, waker } - } + const logged = (count: number) => (body: { log: Array }) => body.log.length >= count const resumed = [ { at: "resumed", store: "A", io: "owner" }, @@ -37,32 +65,7 @@ describe("CloudflareScheduler", () => { ] beforeAll(async () => { - const bundle = await esbuild.build({ - entryPoints: [path.join(import.meta.dirname, "fixtures/scheduler-worker.ts")], - bundle: true, - format: "esm", - platform: "neutral", - write: false, - external: ["cloudflare:workers", "node:*"], - alias: { - "@effect/platform-cloudflare": path.join(import.meta.dirname, "../src") - } - }) - miniflare = new Miniflare({ - workers: [{ - config: { - name: "scheduler", - manifest: { - mainModule: "worker.mjs", - modules: { "worker.mjs": { type: "esm", contents: bundle.outputFiles[0].text } } - }, - compatibilityDate: "2026-07-01", - compatibilityFlags: ["nodejs_compat"], - env: { ROOM: { type: "durable-object", worker: "scheduler", exportName: "Room" } }, - exports: { Room: { type: "durable-object", storage: "sqlite" } } - } - }] - }) + miniflare = makeMiniflare(await bundle(), compatibilityDate) }, 30_000) afterAll(() => miniflare?.dispose()) @@ -71,30 +74,45 @@ describe("CloudflareScheduler", () => { assert.strictEqual(await json("/same"), "X") }) - it("resumes a fiber in the request that owns it", async () => { - const { owner, waker } = await park("/park?id=resume&join", "/wake?id=resume") - assert.strictEqual(waker, "woken") - assert.strictEqual(owner.status, 200) - assert.deepStrictEqual(await owner.json(), resumed) + it("keeps a request's fibers running after it responds", async () => { + assert.deepStrictEqual(await json("/background?id=background"), []) + assert.deepStrictEqual(await poll("/log?id=background", logged(1)), { + log: [{ at: "slept", store: "A", io: "owner" }], + exited: true + }) + }) + + it("resumes a fiber in the request that owns it, after the owner responds", async () => { + assert.deepStrictEqual(await json("/park?id=resume&work=5000"), []) + assert.strictEqual(await json("/wake?id=resume"), "woken") + assert.deepStrictEqual((await poll("/log?id=resume", logged(2))).log, resumed) + }) + + it("resumes a fiber in the request that owns it, while the owner waits for it", async () => { + const owner = get("/park?id=join&join&work=5000") + await poll("/log?id=join", () => true) + assert.strictEqual(await json("/wake?id=join"), "woken") + const response = await owner + assert.strictEqual(response.status, 200) + assert.deepStrictEqual(await response.json(), resumed) }) it("interrupts a fiber in the request that owns it", async () => { - const { owner } = await park("/park?id=interrupt&join", "/wake?id=interrupt&interrupt") - assert.deepStrictEqual(await owner.json(), [{ at: "interrupted", store: "A", io: "owner" }]) + assert.deepStrictEqual(await json("/park?id=interrupt&work=5000"), []) + assert.strictEqual(await json("/wake?id=interrupt&interrupt"), "woken") + assert.deepStrictEqual(await poll("/log?id=interrupt", logged(1)), { + log: [{ at: "interrupted", store: "A", io: "owner" }], + exited: true + }) }) - it("lets a waiting owner be cancelled as hung with keepAlive: false", async () => { - const owner = await get("/park?id=hung&join&scheduler=noKeepAlive") - assert.strictEqual(owner.status, 500) - assert.match(await owner.text(), /hung/) - }) - - it("leaves a fiber suspended when its owner has ended", async () => { - assert.deepStrictEqual(await json("/park?id=ended"), []) + it("leaves a fiber suspended when nothing keeps its owner running", async () => { + // workerd cancels the owner once it only waits on another request + assert.deepStrictEqual(await json("/park?id=idle"), []) await sleep(50) - assert.strictEqual(await json("/wake?id=ended"), "woken") + assert.strictEqual(await json("/wake?id=idle"), "woken") await sleep(100) - assert.deepStrictEqual(await json("/log?id=ended"), { log: [], exited: false }) + assert.deepStrictEqual(await json("/log?id=idle"), { log: [], exited: false }) }) it("resumes a Durable Object fiber after its request has ended", async () => { @@ -104,9 +122,39 @@ describe("CloudflareScheduler", () => { assert.deepStrictEqual(await poll("/room/log?id=room", (body) => body.exited), { log: resumed, exited: true }) }) - it("initializes a shared runtime from a later request", async () => { + it("finishes initializing a shared runtime after the request that started it responds", async () => { assert.strictEqual(await json("/runtime/start"), false) - assert.strictEqual(await json("/runtime/ready"), "ready") + // workerd cancels a request that only waits on another request's work + const waiter = await get("/runtime/join") + assert.strictEqual(waiter.status, 500) + assert.match(await waiter.text(), /hung/) assert.strictEqual(await poll("/runtime/status", (initialized) => initialized), true) + assert.strictEqual(await json("/runtime/join"), "B") }) }) + +describe("CloudflareScheduler without cross-request promise resolution", () => { + it("cannot be constructed", async () => { + const worker = await bundle(` + import { CloudflareScheduler } from "@effect/platform-cloudflare/CloudflareScheduler" + export class Room {} + export default { + fetch() { + try { + new CloudflareScheduler() + return new Response("constructed") + } catch (error) { + return new Response(String(error)) + } + } + } + `) + const miniflare = makeMiniflare(worker, "2024-09-01") + try { + const response = await miniflare.dispatchFetch("http://localhost/") + assert.match(await response.text(), /requires the handle_cross_request_promise_resolution compatibility flag/) + } finally { + await miniflare.dispose() + } + }, 30_000) +}) diff --git a/packages/platform/cloudflare/test/fixtures/scheduler-worker.ts b/packages/platform/cloudflare/test/fixtures/scheduler-worker.ts index 0e7ded24c1..ca163518b1 100644 --- a/packages/platform/cloudflare/test/fixtures/scheduler-worker.ts +++ b/packages/platform/cloudflare/test/fixtures/scheduler-worker.ts @@ -5,10 +5,7 @@ import { AsyncLocalStorage } from "node:async_hooks" declare const WebSocketPair: new() => Record<0 | 1, { readyState: number }> const als = new AsyncLocalStorage() -const schedulers = { - default: new CloudflareScheduler(), - noKeepAlive: new CloudflareScheduler({ keepAlive: false }) -} +const scheduler = new CloudflareScheduler() // I/O objects can only be used by the request that created them const makeIoProbe = () => { @@ -25,16 +22,16 @@ const makeIoProbe = () => { interface Slot { readonly log: Array<{ readonly at: string; readonly store: string | undefined; readonly io: string }> readonly deferred: Deferred.Deferred - fiber?: Fiber.Fiber + fiber?: Fiber.Fiber } const slots = new Map() -// Request A parks a fiber on a Deferred that request B completes +// Request A runs a fiber that request B wakes or interrupts const handle = async (url: URL): Promise => { const id = url.searchParams.get("id")! - const scheduler = schedulers[url.searchParams.get("scheduler") as keyof typeof schedulers ?? "default"] switch (url.pathname) { - case "/park": { + case "/park": + case "/background": { const slot: Slot = { log: [], deferred: Deferred.makeUnsafe() } slots.set(id, slot) return als.run("A", async () => { @@ -43,15 +40,21 @@ const handle = async (url: URL): Promise => { Effect.sync(() => { slot.log.push({ at, store: als.getStore(), io: probe() }) }) - const fiber = slot.fiber = Effect.runFork( - Deferred.await(slot.deferred).pipe( - Effect.andThen(note("resumed")), - Effect.andThen(Effect.sleep(20)), - Effect.andThen(note("slept")), - Effect.onInterrupt(() => note("interrupted")) - ), - { scheduler } + const parked = Deferred.await(slot.deferred).pipe( + Effect.andThen(note("resumed")), + Effect.andThen(Effect.sleep(20)), + Effect.andThen(note("slept")) ) + // Work of the owner's own, which keeps it running while it waits + const work = url.searchParams.get("work") + const program = url.pathname === "/background" + ? Effect.sleep(20).pipe(Effect.andThen(note("slept"))) + : work === null + ? parked + : Effect.race(parked, Effect.sleep(Number(work)).pipe(Effect.andThen(Effect.never))) + const fiber = slot.fiber = Effect.runFork(program.pipe(Effect.onInterrupt(() => note("interrupted"))), { + scheduler + }) if (url.searchParams.has("join")) { await Effect.runPromise(Fiber.await(fiber), { scheduler }) } @@ -69,8 +72,10 @@ const handle = async (url: URL): Promise => { return Response.json("woken") }) case "/log": { - const slot = slots.get(id)! - return Response.json({ log: slot.log, exited: slot.fiber!.pollUnsafe() !== undefined }) + const slot = slots.get(id) + return slot === undefined + ? new Response("not found", { status: 404 }) + : Response.json({ log: slot.log, exited: slot.fiber!.pollUnsafe() !== undefined }) } case "/same": { // Woken by the same request, from another AsyncLocalStorage scope @@ -87,10 +92,8 @@ const handle = async (url: URL): Promise => { return new Response("not found", { status: 404 }) } -const ready = Deferred.makeUnsafe() -const runtime = ManagedRuntime.make( - Layer.effectDiscard(Deferred.await(ready)).pipe(Layer.provideMerge(layer())) -) +// A shared runtime whose initialization takes a while +const runtime = ManagedRuntime.make(Layer.effectDiscard(Effect.sleep(100)).pipe(Layer.provideMerge(layer))) let initialized = false // Requests to a Durable Object share one I/O context @@ -108,25 +111,27 @@ export default { idFromName(name: string): unknown get(id: unknown): { fetch(request: Request): Promise } } - }, - ctx: { waitUntil(promise: Promise): void } + } ) { const url = new URL(request.url) switch (url.pathname) { - // A shared runtime whose initialization waits for a later request + // Starts initializing the runtime and responds without waiting for it case "/runtime/start": { - const run = runtime.runPromise( - Effect.sync(() => { - initialized = true - }), - { scheduler: schedulers.default } - ) - ctx.waitUntil(run) + als.run("A", () => + runtime.runFork( + Effect.sync(() => { + initialized = true + }), + { scheduler } + )) return Response.json(initialized) } - case "/runtime/ready": - await Effect.runPromise(Deferred.succeed(ready, undefined), { scheduler: schedulers.default }) - return Response.json("ready") + // Waits for the initialization another request started + case "/runtime/join": + return als.run( + "B", + async () => Response.json(await runtime.runPromise(Effect.sync(() => als.getStore()), { scheduler })) + ) case "/runtime/status": return Response.json(initialized) }