mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-06 03:59:09 +08:00
Call the scheduler from the fiber and leave async context handling as it was
The fiber now only tells its scheduler where it parks and hands it every effect that would run it again. A ParkingScheduler has park and resume together and keeps its own state per fiber. Schedulers without them run the fiber where it is resumed, as before. The fiber's AsyncResource handling is restored to what it was before this branch, and internal/scheduler.ts, Scheduler.Wait and the fiber's wait slot are removed. CloudflareScheduler keeps the owner promise of each parked fiber in its own table. A scheduler that parked a fiber is no longer told when Fiber.setContext replaces it while the fiber is parked.
This commit is contained in:
@@ -5,6 +5,6 @@
|
||||
|
||||
Add `CloudflareScheduler` so Worker fibers woken by another request resume in the request that owns them, and that request keeps running until they do, within Cloudflare's request lifetime limits.
|
||||
|
||||
It is built on the new unstable `Scheduler.ParkingScheduler` extension: a scheduler with a `park` method starts a `Scheduler.Wait` for each fiber that suspends, and decides how the fiber resumes. The wait keeps resuming the fiber if `Fiber.setContext` replaces its scheduler. Existing `Scheduler` implementations need no changes and keep the default behaviour.
|
||||
It is built on the new unstable `Scheduler.ParkingScheduler` extension: a scheduler with `park` and `resume` methods is told where each of its fibers parks, and decides where the fiber runs again. Existing `Scheduler` implementations need no changes.
|
||||
|
||||
An interrupt requested while a fiber is suspended now takes effect even if the fiber was woken with a value first. An `Effect.callback` that resumes with a resource must release it in its cancellation cleanup, because the fiber may never receive it.
|
||||
A fiber of a `ParkingScheduler` that is interrupted after it was woken, but before its scheduler runs it, is interrupted instead of receiving the value it was woken with. An `Effect.callback` that resumes with a resource must release it in its cancellation cleanup, because such a fiber may never receive it.
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
* @since 2.0.0
|
||||
*/
|
||||
import * as Context from "./Context.ts"
|
||||
import type { Effect } from "./Effect.ts"
|
||||
import type * as Fiber from "./Fiber.ts"
|
||||
|
||||
/**
|
||||
@@ -38,53 +39,33 @@ export interface Scheduler {
|
||||
}
|
||||
|
||||
/**
|
||||
* A `Scheduler` that also decides how its fibers resume after they park.
|
||||
* A `Scheduler` that also decides where its fibers resume.
|
||||
*
|
||||
* **When to use**
|
||||
*
|
||||
* Use to control how fibers resume in a runtime with its own way of resuming
|
||||
* a fiber, such as Cloudflare Workers, where async contexts belong to the
|
||||
* request that created them.
|
||||
* Use to resume fibers in a runtime with its own rules for where code may run,
|
||||
* such as Cloudflare Workers, where a fiber has to resume in the request that
|
||||
* owns it.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* A fiber parks when it stops running with more to do: it suspended, or it was
|
||||
* forked and its start is scheduled. It then calls `park` on its current
|
||||
* scheduler, which returns a `Wait` holding whatever the scheduler needs to
|
||||
* resume it, such as the context the fiber parked in. The first entry that
|
||||
* would make the fiber run again, the effect its wait produced, its start, or
|
||||
* an interrupt, ends the wait: the wait's `resume` is called with a task that
|
||||
* runs the fiber with that entry. Later entries are dropped until the fiber
|
||||
* runs.
|
||||
*
|
||||
* The wait belongs to the scheduler that started it. If `Fiber.setContext`
|
||||
* replaces the scheduler of a parked fiber, the same wait still resumes it,
|
||||
* and the new scheduler starts the fiber's next wait.
|
||||
*
|
||||
* An interrupt requested while the fiber is parked is recorded on the fiber
|
||||
* before it reaches `resume`, the same way as one requested while the fiber
|
||||
* is running. The fiber acts on it at its first interruptible step, so it
|
||||
* replaces the entry the fiber is run with, and a fork interrupted before it
|
||||
* starts never runs. Running the fiber with an entry therefore does not
|
||||
* guarantee the entry is delivered: a value woken before an interrupt but run
|
||||
* after it is dropped. A callback that hands a resource to the fiber keeps
|
||||
* owning it until the fiber runs, so it needs cancellation cleanup to release
|
||||
* a resource that is dropped.
|
||||
*
|
||||
* A scheduler is a `ParkingScheduler` when it has a `park` property; the
|
||||
* fiber checks this each time it parks. Fibers of any other scheduler park the
|
||||
* default way: where `node:async_hooks` is available, as in Node.js, Bun and
|
||||
* Deno, a fiber resumes inside an `AsyncResource` created where it parked, so
|
||||
* `AsyncLocalStorage` state is preserved. Elsewhere, such as in browsers, it
|
||||
* resumes in the caller's context.
|
||||
* forked and its start is scheduled. It calls `park` where it stops, and
|
||||
* passes every effect that would make it run again to `resume`: the result it
|
||||
* waited for, its start, or an interrupt. The scheduler keeps what it needs in
|
||||
* between. A fiber of a scheduler without these methods runs where it is
|
||||
* resumed.
|
||||
*
|
||||
* **Gotchas**
|
||||
*
|
||||
* - If a wait never runs its task, the fiber never resumes and cannot be
|
||||
* interrupted.
|
||||
* - A scheduler that wraps another one must define `park` only when the
|
||||
* wrapped scheduler does, and forward it, so that the wrapped scheduler's
|
||||
* choice is kept.
|
||||
* - A fiber that `resume` never runs cannot complete or be interrupted.
|
||||
* - An interrupt requested before `resume` runs a woken fiber still interrupts
|
||||
* it, so the effect it was woken with may never be delivered.
|
||||
* - `resume` is called on the scheduler the fiber has when it resumes. If
|
||||
* `Fiber.setContext` replaced the scheduler of a parked fiber, the scheduler
|
||||
* that parked it is not told.
|
||||
* - A scheduler that wraps another one forwards `park` and `resume` only if
|
||||
* the wrapped scheduler has them.
|
||||
*
|
||||
* @stability unstable
|
||||
* @category models
|
||||
@@ -92,38 +73,38 @@ export interface Scheduler {
|
||||
*/
|
||||
export interface ParkingScheduler extends Scheduler {
|
||||
/**
|
||||
* Called where a fiber parks, to start the wait that resumes it.
|
||||
* Called where a fiber parks.
|
||||
*
|
||||
* @stability unstable
|
||||
* @since 4.2.0
|
||||
*/
|
||||
park(fiber: Fiber.Fiber<unknown, unknown>): Wait
|
||||
park(fiber: ParkedFiber): void
|
||||
/**
|
||||
* Called with each effect that would make a fiber run again. Runs a parked
|
||||
* fiber once, with the first effect it is given, and any other fiber
|
||||
* immediately, by calling `fiber.run(effect)`.
|
||||
*
|
||||
* @stability unstable
|
||||
* @since 4.2.0
|
||||
*/
|
||||
resume(fiber: ParkedFiber, effect: Effect<unknown, unknown>): void
|
||||
}
|
||||
|
||||
/**
|
||||
* The wait of a parked fiber, started by `ParkingScheduler.park`.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `resume` is called once. Its task runs the fiber synchronously, until it
|
||||
* parks again or exits, and `resume` runs it either synchronously or later,
|
||||
* in whatever context the fiber should resume in. If the fiber was woken while
|
||||
* `park` was still running, for example by an `async_hooks` callback, it has
|
||||
* already run, and the task does nothing: the wait only needs to release what
|
||||
* it holds.
|
||||
* A fiber, as a `ParkingScheduler` sees it.
|
||||
*
|
||||
* @stability unstable
|
||||
* @category models
|
||||
* @since 4.2.0
|
||||
*/
|
||||
export interface Wait {
|
||||
export interface ParkedFiber extends Fiber.Fiber<unknown, unknown> {
|
||||
/**
|
||||
* Ends the wait by running `task`, which resumes the fiber.
|
||||
* Runs the fiber synchronously until it parks again or exits.
|
||||
*
|
||||
* @stability unstable
|
||||
* @since 4.2.0
|
||||
*/
|
||||
resume(task: () => void): void
|
||||
run(effect: Effect<unknown, unknown>): void
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -101,7 +101,6 @@ import {
|
||||
TracerTimingEnabled,
|
||||
UnhandledLogLevel
|
||||
} from "./references.ts"
|
||||
import * as InternalScheduler from "./scheduler.ts"
|
||||
import { getStackTraceLimit, setStackTraceLimit } from "./stackTraceLimit.ts"
|
||||
import { addSpanStackTrace, makeStackCleaner } from "./tracer.ts"
|
||||
|
||||
@@ -500,6 +499,34 @@ const fiberVariance = {
|
||||
|
||||
const fiberIdStore = { id: 0 }
|
||||
|
||||
interface AsyncContext {
|
||||
runInAsyncScope<This, Arg, R>(fn: (this: This, arg: Arg) => R, thisArg: This, arg: Arg): R
|
||||
emitDestroy(): void
|
||||
}
|
||||
|
||||
const AsyncResource: (new(type: string) => AsyncContext) | undefined = (() => {
|
||||
try {
|
||||
return (globalThis as any).process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
})()
|
||||
|
||||
const captureAsyncContext = (): AsyncContext | undefined =>
|
||||
AsyncResource === undefined ? undefined : new AsyncResource("effect/Fiber")
|
||||
|
||||
type Parking = Pick<Scheduler.ParkingScheduler, "park" | "resume">
|
||||
|
||||
const noParking: Parking = {
|
||||
park() {},
|
||||
resume(fiber, effect) {
|
||||
fiber.run(effect)
|
||||
}
|
||||
}
|
||||
|
||||
const parking = (scheduler: Scheduler.Scheduler): Parking =>
|
||||
"park" in scheduler ? scheduler as Scheduler.ParkingScheduler : noParking
|
||||
|
||||
/** @internal */
|
||||
export const SupervisorKey = "effect/Supervisor"
|
||||
|
||||
@@ -527,7 +554,7 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
this._running = false
|
||||
this._deferredInterrupt = false
|
||||
this._parent = undefined
|
||||
this._wait = undefined
|
||||
this._asyncContext = undefined
|
||||
this.cache.runtimeMetrics?.recordFiberStart(this.context)
|
||||
this.supervisor = this.cache.supervisor
|
||||
this.supervisor?.onStart(this, parent)
|
||||
@@ -551,8 +578,7 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
declare _running: boolean
|
||||
declare _deferredInterrupt: boolean
|
||||
declare _parent: FiberImpl<any, any> | undefined
|
||||
// Owned by internal/scheduler.ts
|
||||
declare _wait: Scheduler.Wait | null | undefined
|
||||
declare _asyncContext: AsyncContext | undefined
|
||||
|
||||
// set in setContext
|
||||
declare context: Context.Context<never>
|
||||
@@ -600,8 +626,8 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
? causeAddInterrupts(this._interruptedCause, cause)
|
||||
: cause
|
||||
if (this.interruptible) {
|
||||
// A fiber that is not running acts on the interrupt when it next runs,
|
||||
// even if its scheduler resumes it with another effect
|
||||
// A scheduler may already hold another effect for a parked fiber, so the
|
||||
// fiber acts on the interrupt whichever effect it runs with
|
||||
this._deferredInterrupt = true
|
||||
if (!this._running) {
|
||||
this.evaluate(failCause(this._interruptedCause) as any)
|
||||
@@ -612,21 +638,30 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
return this._exit
|
||||
}
|
||||
evaluate(effect: Primitive): void {
|
||||
InternalScheduler.resume(this, effect)
|
||||
parking(this.cache.scheduler).resume(this, effect as any)
|
||||
}
|
||||
// Every effect a scheduler resumes the fiber with is a primitive
|
||||
run(effect: Primitive | Effect.Effect<unknown, unknown>): void {
|
||||
if (this._exit) {
|
||||
return
|
||||
}
|
||||
if (this._yielded !== undefined) {
|
||||
} else if (this._asyncContext !== undefined) {
|
||||
const asyncContext = this._asyncContext
|
||||
this._asyncContext = undefined
|
||||
try {
|
||||
return asyncContext.runInAsyncScope(this.run, this, effect)
|
||||
} finally {
|
||||
// Each captured context is resumed once, so release it for async_hooks
|
||||
// consumers like vitest's detectAsyncLeaks.
|
||||
asyncContext.emitDestroy()
|
||||
}
|
||||
} else if (this._yielded !== undefined) {
|
||||
const yielded = this._yielded as () => void
|
||||
this._yielded = undefined
|
||||
yielded()
|
||||
}
|
||||
const exit = this.runLoop(effect as Primitive)
|
||||
if (exit === Yield) {
|
||||
InternalScheduler.park(this.cache.scheduler, this)
|
||||
this._asyncContext = captureAsyncContext()
|
||||
parking(this.cache.scheduler).park(this)
|
||||
return
|
||||
}
|
||||
// the interruptChildren middleware is added in Effect.forkChild, so it can be
|
||||
@@ -636,7 +671,7 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
if (interruptChildren !== undefined) {
|
||||
// uninterruptible, so a pending interrupt cannot replace the exit during the wait
|
||||
this.interruptible = false
|
||||
return this.run(flatMap(interruptChildren, () => exit))
|
||||
return this.evaluate(flatMap(interruptChildren, () => exit) as any)
|
||||
}
|
||||
|
||||
this._exit = exit
|
||||
@@ -4634,7 +4669,7 @@ const makeCachedUnsafe = <A, E, R>(
|
||||
current = run
|
||||
// Join before evaluating, which may synchronously re-enter and interrupt other awaiters.
|
||||
const joined = join(fiber, run)
|
||||
run.fiber.run(
|
||||
run.fiber.evaluate(
|
||||
onExitPrimitive(self, (exit_) => {
|
||||
run.done = true
|
||||
// A detached run must not publish its result or clear a replacement run.
|
||||
@@ -5663,10 +5698,11 @@ export const forkUnsafe = <FA, FE, A, E, R>(
|
||||
child._parent = parentRuntime
|
||||
}
|
||||
if (immediate) {
|
||||
child.run(effect as any)
|
||||
child.evaluate(effect as any)
|
||||
} else {
|
||||
// Preserve the fork context rather than the dispatcher's context.
|
||||
InternalScheduler.park(child.cache.scheduler, child)
|
||||
child._asyncContext = captureAsyncContext()
|
||||
parking(child.cache.scheduler).park(child)
|
||||
// Cancel the deferred start if an interrupt runs first.
|
||||
let resumed = false
|
||||
child.yieldWith(() => {
|
||||
@@ -5824,7 +5860,7 @@ export const runForkWith = <R>(context: Context.Context<R>) =>
|
||||
options?.scheduler ? Context.add(context, Scheduler.Scheduler, options.scheduler) : context,
|
||||
options?.uninterruptible !== true
|
||||
)
|
||||
fiber.run(effect as any)
|
||||
fiber.evaluate(effect as any)
|
||||
if (fiber._exit) return fiber
|
||||
|
||||
if (options?.signal) {
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import type * as Fiber from "../Fiber.ts"
|
||||
import type * as Scheduler from "../Scheduler.ts"
|
||||
|
||||
// The scheduler side of parking a fiber. A fiber parks by asking its
|
||||
// scheduler for a wait, and hands every entry that would make it run again,
|
||||
// the effect its wait produced, its start, or an interrupt, back here. The
|
||||
// fiber only provides the slot this module keeps its wait in.
|
||||
|
||||
/** @internal */
|
||||
export interface ParkableFiber extends Fiber.Fiber<unknown, unknown> {
|
||||
run(effect: unknown): void
|
||||
// The outstanding wait of the fiber, kept here whatever its scheduler is
|
||||
// now, so the wait resumes it even after Fiber.setContext replaces its
|
||||
// scheduler. null once an entry has been passed to the wait, until the
|
||||
// fiber runs: later entries are dropped, and an interrupt among them is
|
||||
// already recorded on the fiber. Only this module reads or writes it.
|
||||
_wait: Scheduler.Wait | null | undefined
|
||||
}
|
||||
|
||||
interface AsyncResource {
|
||||
runInAsyncScope(fn: () => void): void
|
||||
emitDestroy(): void
|
||||
}
|
||||
|
||||
const AsyncResource: (new(type: string) => AsyncResource) | undefined = (() => {
|
||||
try {
|
||||
return (globalThis as any).process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
})()
|
||||
|
||||
// The wait of a scheduler that does not implement ParkingScheduler, where
|
||||
// node:async_hooks is available: an async resource created where the fiber
|
||||
// parked, which runs the fiber inside it. Elsewhere, such as in browsers,
|
||||
// there is no wait and the fiber resumes in the caller's context.
|
||||
const DefaultWait: (new(type: string) => Scheduler.Wait) | undefined = AsyncResource && class extends AsyncResource {
|
||||
resume(task: () => void) {
|
||||
// Each wait is resumed once, so the resource ends here, before the task
|
||||
// runs: even if the task throws, async_hooks consumers do not see it as
|
||||
// live until it is collected. Node queues destroy hooks and runs them
|
||||
// after the current task, so they still follow the before and after
|
||||
// hooks of this run, and cannot re-enter the fiber.
|
||||
this.emitDestroy()
|
||||
this.runInAsyncScope(task)
|
||||
}
|
||||
}
|
||||
|
||||
// The fiber whose wait is being created. Creating it can run code that wakes
|
||||
// the fiber, such as async_hooks init callbacks, before the wait is stored.
|
||||
let installing: ParkableFiber | undefined
|
||||
|
||||
/** @internal */
|
||||
export const park = (scheduler: Scheduler.Scheduler, fiber: ParkableFiber): void => {
|
||||
const parking = (scheduler as Partial<Scheduler.ParkingScheduler>).park !== undefined
|
||||
if (!parking && DefaultWait === undefined) return
|
||||
const previous = installing
|
||||
installing = fiber
|
||||
const wait = parking ? (scheduler as Scheduler.ParkingScheduler).park(fiber) : new DefaultWait!("effect/Fiber")
|
||||
const resumed = installing !== fiber
|
||||
installing = previous
|
||||
if (resumed) {
|
||||
// The fiber already ran where it parked, so the wait only needs ending
|
||||
wait.resume(noop)
|
||||
} else {
|
||||
fiber._wait = wait
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const resume = (fiber: ParkableFiber, effect: unknown): void => {
|
||||
const wait = fiber._wait
|
||||
if (wait) {
|
||||
fiber._wait = null
|
||||
wait.resume(() => {
|
||||
fiber._wait = undefined
|
||||
fiber.run(effect)
|
||||
})
|
||||
} else if (wait === undefined) {
|
||||
// Woken while its wait is being created, the fiber is still where it
|
||||
// parked. Otherwise it is not parked: it has not started, has exited, or
|
||||
// has no wait in this runtime.
|
||||
if (installing === fiber) installing = undefined
|
||||
fiber.run(effect)
|
||||
}
|
||||
}
|
||||
|
||||
const noop = (): void => {}
|
||||
@@ -512,14 +512,16 @@ class TrackingScheduler implements Scheduler.Scheduler {
|
||||
readonly parent: Scheduler.Scheduler
|
||||
readonly executionMode: Scheduler.Scheduler["executionMode"]
|
||||
declare readonly park?: Scheduler.ParkingScheduler["park"]
|
||||
declare readonly resume?: Scheduler.ParkingScheduler["resume"]
|
||||
constructor(clock: TestClockImpl, parent: Scheduler.Scheduler) {
|
||||
this.clock = clock
|
||||
this.parent = parent
|
||||
this.executionMode = parent.executionMode
|
||||
// Parks only when the parent does, so its fibers keep the default otherwise
|
||||
const parking = parent as Partial<Scheduler.ParkingScheduler>
|
||||
if (parking.park) {
|
||||
this.park = (fiber) => parking.park!(fiber)
|
||||
// Parks fibers only if the parent does, so they keep the default otherwise
|
||||
if ("park" in parent) {
|
||||
const parking = parent as Scheduler.ParkingScheduler
|
||||
this.park = (fiber) => parking.park(fiber)
|
||||
this.resume = (fiber, effect) => parking.resume(fiber, effect)
|
||||
}
|
||||
}
|
||||
shouldYield(fiber: Fiber.Fiber<unknown, unknown>): boolean {
|
||||
|
||||
@@ -5686,279 +5686,6 @@ describe("Effect", () => {
|
||||
describe("AsyncLocalStorage", () => {
|
||||
const storage = new AsyncLocalStorage<string>()
|
||||
const current = () => storage.getStore() ?? "none"
|
||||
// Bun's async_hooks report no trigger ids, before or destroy events
|
||||
const itWithAsyncHooks = it.skipIf(process.versions.bun !== undefined)
|
||||
|
||||
describe("ParkingScheduler", () => {
|
||||
// Runs each parked fiber in the "owner" store when `land` runs, like a
|
||||
// scheduler that hands fibers back to the request that owns them. It
|
||||
// throws if a wait is resumed twice. Its state is in instance fields, so
|
||||
// wrappers must keep the receiver.
|
||||
const makeScheduler = () => {
|
||||
const scheduler = new class extends Scheduler.MixedScheduler implements Scheduler.ParkingScheduler {
|
||||
readonly pending: Array<() => void> = []
|
||||
park(): Scheduler.Wait {
|
||||
let resumed = false
|
||||
return {
|
||||
resume: (task) => {
|
||||
if (resumed) throw new Error("resumed twice")
|
||||
resumed = true
|
||||
this.pending.push(() => storage.run("owner", task))
|
||||
}
|
||||
}
|
||||
}
|
||||
}("sync")
|
||||
const land = async () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await Promise.resolve()
|
||||
while (scheduler.pending.length > 0) scheduler.pending.shift()!()
|
||||
}
|
||||
}
|
||||
return { scheduler, land }
|
||||
}
|
||||
|
||||
it("resumes and starts forks in the owner's context, including under TestClock", async () => {
|
||||
const { land, scheduler } = makeScheduler()
|
||||
const deferred = Deferred.makeUnsafe<void>()
|
||||
const fiber = Effect.runFork(
|
||||
Effect.gen(function*() {
|
||||
const child = yield* Effect.forkChild(Effect.sync(current))
|
||||
yield* Deferred.await(deferred)
|
||||
return [yield* Fiber.join(child), current()]
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
{ scheduler }
|
||||
)
|
||||
await land()
|
||||
storage.run("waker", () => Effect.runSync(Deferred.succeed(deferred, undefined)))
|
||||
await land()
|
||||
assert.deepStrictEqual(fiber.pollUnsafe(), Exit.succeed(["owner", "owner"]))
|
||||
})
|
||||
|
||||
it("acts on an interrupt requested before a woken fiber runs at its first interruptible step", async () => {
|
||||
// Not at its next suspension: the continuation of the wait never runs.
|
||||
// Replacing the fiber's scheduler in between changes neither where it
|
||||
// runs nor how often, so the woken entry does not end the wait of its
|
||||
// cleanup.
|
||||
const { land, scheduler } = makeScheduler()
|
||||
const seen: Array<string> = []
|
||||
let wake!: () => void
|
||||
let finish!: () => void
|
||||
const fiber = Effect.runFork(
|
||||
Effect.callback<void>((resume) => {
|
||||
wake = () => resume(Effect.void)
|
||||
return Effect.callback<void>((resume) => {
|
||||
finish = () => resume(Effect.void)
|
||||
}).pipe(Effect.andThen(Effect.sync(() => seen.push(`cleaned in ${current()}`))))
|
||||
}).pipe(
|
||||
Effect.andThen(Effect.sync(() => seen.push("continued"))),
|
||||
Effect.andThen(Effect.yieldNow),
|
||||
Effect.andThen(Effect.sync(() => seen.push("suspended")))
|
||||
),
|
||||
{ scheduler }
|
||||
)
|
||||
await land()
|
||||
storage.run("waker", () => {
|
||||
wake()
|
||||
fiber.setContext(Context.add(fiber.context, Scheduler.Scheduler, new Scheduler.MixedScheduler("sync")))
|
||||
fiber.interruptUnsafe()
|
||||
})
|
||||
await land()
|
||||
assert.deepStrictEqual(seen, [])
|
||||
assert.isUndefined(fiber.pollUnsafe())
|
||||
storage.run("waker", finish)
|
||||
assert.deepStrictEqual(seen, ["cleaned in owner"])
|
||||
assert.isTrue(Exit.hasInterrupts(fiber.pollUnsafe()!))
|
||||
})
|
||||
|
||||
it("resumes a parked fiber through its wait after setContext replaces its scheduler", async () => {
|
||||
const { land, scheduler } = makeScheduler()
|
||||
const parkAndMove = (from: Scheduler.Scheduler, to: Scheduler.Scheduler) => {
|
||||
let wake!: () => void
|
||||
const fiber = storage.run("parker", () =>
|
||||
Effect.runFork(
|
||||
Effect.callback<void>((resume) => {
|
||||
wake = () => resume(Effect.void)
|
||||
}).pipe(Effect.andThen(Effect.sync(current))),
|
||||
{ scheduler: from }
|
||||
))
|
||||
fiber.setContext(Context.add(fiber.context, Scheduler.Scheduler, to))
|
||||
storage.run("waker", wake)
|
||||
return fiber
|
||||
}
|
||||
const fromDefault = parkAndMove(new Scheduler.MixedScheduler("sync"), scheduler)
|
||||
const toDefault = parkAndMove(scheduler, new Scheduler.MixedScheduler("sync"))
|
||||
await land()
|
||||
assert.deepStrictEqual(fromDefault.pollUnsafe(), Exit.succeed("parker"))
|
||||
assert.deepStrictEqual(toDefault.pollUnsafe(), Exit.succeed("owner"))
|
||||
})
|
||||
|
||||
it.skipIf(process.versions.bun !== undefined || process.versions.deno !== undefined)(
|
||||
"does not retain the async resource of a wait after the fiber exits",
|
||||
async () => {
|
||||
let reference: WeakRef<object> | undefined
|
||||
const hook = createHook({
|
||||
init(_asyncId, type, _triggerAsyncId, resource) {
|
||||
if (type === "effect/Fiber") reference = new WeakRef(resource)
|
||||
}
|
||||
})
|
||||
let wake!: () => void
|
||||
hook.enable()
|
||||
const fiber = Effect.runFork(Effect.callback<void>((resume) => {
|
||||
wake = () => resume(Effect.void)
|
||||
}))
|
||||
hook.disable()
|
||||
wake()
|
||||
await Effect.runPromise(collectGarbage)
|
||||
assert.isTrue(Exit.isSuccess(fiber.pollUnsafe()!))
|
||||
assert.isUndefined(reference!.deref())
|
||||
}
|
||||
)
|
||||
|
||||
itWithAsyncHooks("ends the async resource of a wait even if resuming the fiber throws", async () => {
|
||||
const created = new Set<number>()
|
||||
const destroyed: Array<number> = []
|
||||
let tracking = false
|
||||
const hook = createHook({
|
||||
init(asyncId, type) {
|
||||
if (tracking && type === "effect/Fiber") created.add(asyncId)
|
||||
},
|
||||
destroy(asyncId) {
|
||||
if (created.has(asyncId)) destroyed.push(asyncId)
|
||||
}
|
||||
})
|
||||
hook.enable()
|
||||
try {
|
||||
let wake!: () => void
|
||||
tracking = true
|
||||
const fiber = Effect.runFork(Effect.callback<void>((resume) => {
|
||||
wake = () => resume(Effect.void)
|
||||
}))
|
||||
tracking = false
|
||||
fiber.addObserver(() => {
|
||||
throw new Error("observer")
|
||||
})
|
||||
assert.throws(wake, "observer")
|
||||
// Node runs destroy callbacks asynchronously
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
assert.strictEqual(created.size, 1)
|
||||
assert.deepStrictEqual(destroyed, [...created])
|
||||
} finally {
|
||||
hook.disable()
|
||||
}
|
||||
})
|
||||
|
||||
describe("an entry from an async_hooks init callback during the next park", () => {
|
||||
// The fiber resumes from its first wait and parks in a second one. The
|
||||
// second wait's resource is created synchronously in park, so its init
|
||||
// callback runs before the wait is installed. Every wait resource
|
||||
// created meanwhile must also be destroyed.
|
||||
const parkTwice = async (onSecondPark: (fiber: Fiber.Fiber<number>, wake: (n: number) => void) => void) => {
|
||||
let fiber: Fiber.Fiber<number> | undefined
|
||||
let wakeFirst!: () => void
|
||||
let wakeSecond!: (n: number) => void
|
||||
let armed = false
|
||||
let tracking = false
|
||||
// Held strongly, so a resource is not destroyed by garbage collection
|
||||
const live = new Map<number, object>()
|
||||
const hook = createHook({
|
||||
init(asyncId, type, _triggerAsyncId, resource) {
|
||||
if (!tracking || type !== "effect/Fiber") return
|
||||
live.set(asyncId, resource)
|
||||
if (armed) {
|
||||
armed = false
|
||||
onSecondPark(fiber!, wakeSecond)
|
||||
}
|
||||
},
|
||||
destroy(asyncId) {
|
||||
live.delete(asyncId)
|
||||
}
|
||||
})
|
||||
fiber = Effect.runFork(
|
||||
Effect.callback<void>((resume) => {
|
||||
wakeFirst = () => resume(Effect.void)
|
||||
}).pipe(Effect.andThen(Effect.callback<number>((resume) => {
|
||||
wakeSecond = (n) => resume(Effect.succeed(n))
|
||||
})))
|
||||
)
|
||||
hook.enable()
|
||||
try {
|
||||
armed = tracking = true
|
||||
wakeFirst()
|
||||
tracking = false
|
||||
assert.isFalse(armed)
|
||||
// Node runs destroy callbacks asynchronously
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
} finally {
|
||||
hook.disable()
|
||||
}
|
||||
return { exit: fiber.pollUnsafe(), live: [...live.keys()] }
|
||||
}
|
||||
|
||||
itWithAsyncHooks("delivers the value", async () => {
|
||||
const { exit, live } = await parkTwice((_, wake) => wake(42))
|
||||
assert.deepStrictEqual(exit, Exit.succeed(42))
|
||||
assert.deepStrictEqual(live, [])
|
||||
})
|
||||
|
||||
itWithAsyncHooks("delivers the interrupt", async () => {
|
||||
const { exit, live } = await parkTwice((fiber) => fiber.interruptUnsafe())
|
||||
assert.isTrue(exit !== undefined && Exit.hasInterrupts(exit))
|
||||
assert.deepStrictEqual(live, [])
|
||||
})
|
||||
|
||||
itWithAsyncHooks("keeps the wait when setContext replaces the scheduler", async () => {
|
||||
const { exit, live } = await parkTwice((fiber, wake) => {
|
||||
fiber.setContext(Context.add(fiber.context, Scheduler.Scheduler, makeScheduler().scheduler))
|
||||
queueMicrotask(() => wake(42))
|
||||
})
|
||||
assert.deepStrictEqual(exit, Exit.succeed(42))
|
||||
assert.deepStrictEqual(live, [])
|
||||
})
|
||||
})
|
||||
|
||||
itWithAsyncHooks("runs an interrupt requested while entering a native context before the value", () => {
|
||||
// An async_hooks `before` callback runs inside runInAsyncScope, before
|
||||
// the fiber runs, so the interrupt replaces the value. The value is not
|
||||
// delivered to the wait in the interrupted fiber's finalizer either.
|
||||
const fiberResources = new Set<number>()
|
||||
let capturing = false
|
||||
let fiber: Fiber.Fiber<number> | undefined
|
||||
const hook = createHook({
|
||||
init(asyncId, type) {
|
||||
if (capturing && type === "effect/Fiber") fiberResources.add(asyncId)
|
||||
},
|
||||
before(asyncId) {
|
||||
if (fiber !== undefined && fiberResources.delete(asyncId)) fiber.interruptUnsafe()
|
||||
}
|
||||
})
|
||||
let wake!: (effect: Effect.Effect<number>) => void
|
||||
let finish!: (effect: Effect.Effect<void>) => void
|
||||
let continued = false
|
||||
hook.enable()
|
||||
try {
|
||||
capturing = true
|
||||
fiber = Effect.runFork(
|
||||
Effect.callback<number>((resume) => {
|
||||
wake = resume
|
||||
return Effect.callback<void>((resume) => {
|
||||
finish = resume
|
||||
})
|
||||
}).pipe(Effect.tap(() => Effect.sync(() => (continued = true))))
|
||||
)
|
||||
capturing = false
|
||||
assert.strictEqual(fiberResources.size, 1)
|
||||
wake(Effect.succeed(42))
|
||||
} finally {
|
||||
hook.disable()
|
||||
}
|
||||
assert.strictEqual(fiberResources.size, 0)
|
||||
assert.isFalse(continued)
|
||||
assert.isUndefined(fiber.pollUnsafe())
|
||||
finish(Effect.void)
|
||||
assert.isFalse(continued)
|
||||
assert.isTrue(Exit.hasInterrupts(fiber.pollUnsafe()!))
|
||||
})
|
||||
})
|
||||
|
||||
const runWithStore = <A, E>(store: string | undefined, effect: Effect.Effect<A, E>): Promise<A> =>
|
||||
store === undefined ? Effect.runPromise(effect) : storage.run(store, () => Effect.runPromise(effect))
|
||||
@@ -6027,6 +5754,10 @@ describe("Effect", () => {
|
||||
})
|
||||
}
|
||||
|
||||
// Bun's async_hooks report no trigger ids or destroy events, so any process.nextTick
|
||||
// in the worker, including from concurrent tests, would count as a leak.
|
||||
const itWithAsyncHooks = it.skipIf(process.versions.bun !== undefined)
|
||||
|
||||
itWithAsyncHooks("does not leave async resources open after the effect completes", async () => {
|
||||
// Mirrors vitest's detectAsyncLeaks: track every resource descended from a root scope
|
||||
// and report the ones that are still pending once the effect has completed.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { assert, describe, it, vi } from "@effect/vitest"
|
||||
import { Effect, Exit } from "effect"
|
||||
import { Deferred, Effect, Exit, Fiber } from "effect"
|
||||
import * as Scheduler from "effect/Scheduler"
|
||||
import * as TestClock from "effect/testing/TestClock"
|
||||
|
||||
describe("Scheduler", () => {
|
||||
it("runSyncExit does not create a dispatcher for synchronous effects", () => {
|
||||
@@ -190,4 +191,72 @@ describe("Scheduler", () => {
|
||||
setImmediate.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
describe("ParkingScheduler", () => {
|
||||
// Runs each parked fiber when `land` is called, like a scheduler that hands
|
||||
// fibers back to the request that owns them
|
||||
const makeScheduler = () => {
|
||||
const pending: Array<() => void> = []
|
||||
let landing = false
|
||||
const scheduler = new class extends Scheduler.MixedScheduler implements Scheduler.ParkingScheduler {
|
||||
readonly resumed = new Map<Scheduler.ParkedFiber, boolean>()
|
||||
park(fiber: Scheduler.ParkedFiber): void {
|
||||
this.resumed.set(fiber, false)
|
||||
}
|
||||
resume(fiber: Scheduler.ParkedFiber, effect: Effect.Effect<unknown, unknown>): void {
|
||||
const resumed = this.resumed.get(fiber)
|
||||
if (resumed === undefined) return fiber.run(effect)
|
||||
if (resumed) return
|
||||
this.resumed.set(fiber, true)
|
||||
pending.push(() => {
|
||||
this.resumed.delete(fiber)
|
||||
fiber.run(effect)
|
||||
})
|
||||
}
|
||||
}("sync")
|
||||
const land = async () => {
|
||||
await Promise.resolve()
|
||||
landing = true
|
||||
while (pending.length > 0) pending.shift()!()
|
||||
landing = false
|
||||
}
|
||||
return { scheduler, land, isLanding: Effect.sync(() => landing) }
|
||||
}
|
||||
|
||||
it("runs parked and forked fibers when it chooses, including under TestClock", async () => {
|
||||
const { isLanding, land, scheduler } = makeScheduler()
|
||||
const deferred = Deferred.makeUnsafe<void>()
|
||||
const fiber = Effect.runFork(
|
||||
Effect.gen(function*() {
|
||||
const child = yield* Effect.forkChild(isLanding)
|
||||
yield* Deferred.await(deferred)
|
||||
return [yield* Fiber.join(child), yield* isLanding]
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
{ scheduler }
|
||||
)
|
||||
await land()
|
||||
Effect.runSync(Deferred.succeed(deferred, undefined))
|
||||
assert.isUndefined(fiber.pollUnsafe())
|
||||
await land()
|
||||
assert.deepStrictEqual(fiber.pollUnsafe(), Exit.succeed([true, true]))
|
||||
})
|
||||
|
||||
it("interrupts a fiber woken before the interrupt, once it runs", async () => {
|
||||
const { land, scheduler } = makeScheduler()
|
||||
let wake!: () => void
|
||||
let continued = false
|
||||
const fiber = Effect.runFork(
|
||||
Effect.callback<void>((resume) => {
|
||||
wake = () => resume(Effect.void)
|
||||
}).pipe(Effect.andThen(Effect.sync(() => (continued = true)))),
|
||||
{ scheduler }
|
||||
)
|
||||
wake()
|
||||
fiber.interruptUnsafe()
|
||||
assert.isUndefined(fiber.pollUnsafe())
|
||||
await land()
|
||||
assert.isFalse(continued)
|
||||
assert.isTrue(Exit.hasInterrupts(fiber.pollUnsafe()!))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,49 +5,26 @@
|
||||
* @since 4.2.0
|
||||
*/
|
||||
import { waitUntil } from "cloudflare:workers"
|
||||
import type { Effect } from "effect/Effect"
|
||||
import * as Layer from "effect/Layer"
|
||||
import * as Scheduler from "effect/Scheduler"
|
||||
|
||||
const compatibilityFlags: Record<string, boolean | undefined> | undefined = (globalThis as any).Cloudflare
|
||||
?.compatibilityFlags
|
||||
|
||||
// Each parked fiber waits on a promise created in the request it parked in,
|
||||
// kept here by the function that settles it. workerd runs the reactions of a
|
||||
// promise in the request that created it, with the AsyncLocalStorage state
|
||||
// they were registered in, so settling it from any request runs the fiber in
|
||||
// its owner. workerd cannot tell which request is running, so a fiber woken by
|
||||
// its owner takes the same path, a microtask later.
|
||||
//
|
||||
// Every instance shares these, so a fiber keeps its owner if its scheduler is
|
||||
// replaced by another CloudflareScheduler.
|
||||
const waits = new WeakMap<Scheduler.ParkedFiber, (run: () => void) => void>()
|
||||
|
||||
const noop = (): void => {}
|
||||
|
||||
// The longest delay a timer accepts. It only marks pending work, so it is
|
||||
// cleared before it fires.
|
||||
const maxTimerMillis = 2_147_483_647
|
||||
|
||||
const setPendingTimer = (): ReturnType<typeof setTimeout> | undefined => {
|
||||
try {
|
||||
return setTimeout(noop, maxTimerMillis)
|
||||
} catch {
|
||||
// Workers do not allow timers in global scope
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
const keepOwnerAlive = (promise: Promise<void>): void => {
|
||||
try {
|
||||
waitUntil(promise)
|
||||
} catch {
|
||||
// Outside a request, for example in global scope, there is no owner to keep
|
||||
}
|
||||
}
|
||||
|
||||
// Each wait is a promise created in the request the fiber parks in, which owns
|
||||
// it. Resuming settles it, and the fiber runs in a reaction to it: workerd
|
||||
// runs promise reactions in the request that created the promise, with the
|
||||
// AsyncLocalStorage state they were registered in, so the fiber has the
|
||||
// owner's I/O objects, timers and store.
|
||||
//
|
||||
// The owner waits on that promise with waitUntil, so it keeps running after it
|
||||
// responds. workerd still cancels a request whose only pending work is a
|
||||
// promise another request settles, so a timer set in the owner marks the fiber
|
||||
// as pending work. The owner clears it when the promise settles.
|
||||
//
|
||||
// workerd has no way to ask which request is running, so a fiber woken by its
|
||||
// owner also resumes through the promise, a microtask later.
|
||||
|
||||
/**
|
||||
* A synchronous scheduler that resumes each fiber in the Worker request that
|
||||
* owns it, and keeps that request running while the fiber waits.
|
||||
@@ -97,6 +74,10 @@ const keepOwnerAlive = (promise: Promise<void>): void => {
|
||||
* compatibility flag, enabled by default from 2024-10-14; the constructor
|
||||
* throws without it.
|
||||
*
|
||||
* A fiber keeps its owner only while its scheduler is a `CloudflareScheduler`.
|
||||
* If `Fiber.setContext` gives a parked fiber another kind of scheduler, the
|
||||
* fiber resumes in the request that wakes it.
|
||||
*
|
||||
* Synchronous execution does not yield to the event loop, so CPU-heavy work
|
||||
* delays other requests.
|
||||
*
|
||||
@@ -121,23 +102,42 @@ export class CloudflareScheduler extends Scheduler.MixedScheduler implements Sch
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a wait owned by the current request.
|
||||
* Makes the current request the owner of a parked fiber.
|
||||
*
|
||||
* @stability unstable
|
||||
* @since 4.2.0
|
||||
*/
|
||||
park(): Scheduler.Wait {
|
||||
const timer = setPendingTimer()
|
||||
let resume!: (task: () => void) => void
|
||||
keepOwnerAlive(
|
||||
new Promise<() => void>((resolve) => {
|
||||
resume = resolve
|
||||
}).then((task) => {
|
||||
if (timer !== undefined) clearTimeout(timer)
|
||||
task()
|
||||
})
|
||||
)
|
||||
return { resume }
|
||||
park(fiber: Scheduler.ParkedFiber): void {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const resumed = new Promise<() => void>((resolve) => {
|
||||
waits.set(fiber, resolve)
|
||||
}).then((run) => {
|
||||
clearTimeout(timer)
|
||||
waits.delete(fiber)
|
||||
run()
|
||||
})
|
||||
try {
|
||||
// workerd cancels a request whose only pending work is a promise that
|
||||
// another request settles. A timer is pending work, so this one marks
|
||||
// the fiber. It has the longest delay a timer accepts and never fires.
|
||||
timer = setTimeout(noop, 2_147_483_647)
|
||||
waitUntil(resumed)
|
||||
} catch {
|
||||
// Workers allow neither in global scope, where no request owns the fiber
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a parked fiber in the request that owns it.
|
||||
*
|
||||
* @stability unstable
|
||||
* @since 4.2.0
|
||||
*/
|
||||
resume(fiber: Scheduler.ParkedFiber, effect: Effect<unknown, unknown>): void {
|
||||
const settle = waits.get(fiber)
|
||||
if (settle === undefined) return fiber.run(effect)
|
||||
// A promise settles once, so only the first effect runs the fiber
|
||||
settle(() => fiber.run(effect))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,9 +74,7 @@ describe("CloudflareScheduler", () => {
|
||||
})
|
||||
})
|
||||
|
||||
// The wait the fiber parked in still resumes it, and its next wait, started
|
||||
// by the new scheduler while it runs in the owner, is owned there too
|
||||
it("keeps the owner of a fiber that setContext moves to another scheduler", async () => {
|
||||
it("keeps the owner of a fiber that setContext moves to another CloudflareScheduler", async () => {
|
||||
assert.deepStrictEqual(await json("/park?id=move"), [])
|
||||
await sleep(100)
|
||||
assert.strictEqual(await json("/wake?id=move&move"), "woken")
|
||||
|
||||
Reference in New Issue
Block a user