mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-04 03:35:36 +08:00
Let the scheduler own parking, with no parking state on the fiber
The fiber now only calls its current scheduler: park(fiber) when it parks, and resume(fiber, effect) for every entry. It has no parking field; main's _asyncContext slot is gone. Each scheduler keys its waits by fiber and owns capture, run-once and cleanup: - The default for schedulers without park keeps one AsyncResource per wait in a WeakMap, marks the wait resumed while the fiber runs, and runs a fiber it did not park directly. - CloudflareScheduler keeps each settle function in a WeakMap until the fiber's reaction runs, and ends a stale wait when it parks the fiber again. When Fiber.setContext replaces the scheduler of a parked fiber, the new scheduler now resumes it directly.
This commit is contained in:
@@ -49,15 +49,20 @@ export interface Scheduler {
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* A fiber parks when it stops running with more to do: it suspended, or it was
|
||||
* forked and its start is scheduled. `park` starts that wait, and the
|
||||
* scheduler keeps any state it needs for it, such as the context the fiber
|
||||
* parked in. The first thing that would make the fiber run again, the effect
|
||||
* its wait produced, its start, or an interrupt, ends the wait and is passed
|
||||
* to `resume`, once per call to `park`. `resume` runs the fiber with it by
|
||||
* The fiber only calls its current scheduler; the scheduler owns everything
|
||||
* about a wait. A fiber parks when it stops running with more to do: it
|
||||
* suspended, or it was forked and its start is scheduled. `park` starts that
|
||||
* wait, and the scheduler keeps the state it needs for it, such as the context
|
||||
* the fiber parked in, keyed by fiber. Everything that would make the fiber run
|
||||
* again, the effect its wait produced, its start, or an interrupt, is passed
|
||||
* to `resume`. `resume` runs the fiber once per wait, with the first entry, by
|
||||
* calling `fiber.run(effect)`, either synchronously or later, in whatever
|
||||
* context it chooses. The scheduler that parked a fiber also resumes it, even
|
||||
* if the fiber's scheduler has changed since.
|
||||
* context it chooses, and ignores later entries until the fiber runs.
|
||||
*
|
||||
* `resume` is also called for a fiber the scheduler did not park: one that has
|
||||
* not started, one that has exited, or one whose scheduler `Fiber.setContext`
|
||||
* replaced while it was parked. It runs such a fiber directly, which does
|
||||
* nothing once the fiber has exited.
|
||||
*
|
||||
* 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
|
||||
@@ -70,7 +75,7 @@ export interface Scheduler {
|
||||
* 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
|
||||
* fiber checks this each time it parks or is resumed. 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
|
||||
@@ -80,9 +85,13 @@ export interface Scheduler {
|
||||
*
|
||||
* - If `fiber.run` is never called, the fiber never resumes and cannot be
|
||||
* interrupted.
|
||||
* - The fiber does not hold the state of a wait, so `resume` must release it.
|
||||
* A fiber that is never resumed stays parked, so key the state weakly, for
|
||||
* example in a `WeakMap`, to let such a fiber be garbage collected.
|
||||
* - The fiber does not hold the state of a wait, so the scheduler must release
|
||||
* it once the fiber runs. A fiber that is never woken stays parked, so key
|
||||
* the state weakly, for example in a `WeakMap`, to let such a fiber be
|
||||
* garbage collected.
|
||||
* - When `Fiber.setContext` replaces the scheduler of a parked fiber, the new
|
||||
* scheduler resumes it, and the wait the old scheduler started is never
|
||||
* resumed. The old scheduler can release it when it next parks the fiber.
|
||||
* - A scheduler that wraps another one must define `park` and `resume` only
|
||||
* when the wrapped scheduler does, and forward both, so that the wrapped
|
||||
* scheduler's choice is kept.
|
||||
@@ -100,8 +109,9 @@ export interface ParkingScheduler extends Scheduler {
|
||||
*/
|
||||
park(fiber: Fiber.Fiber<unknown, unknown>): void
|
||||
/**
|
||||
* Called once for each wait `park` started, with the entry that ends it.
|
||||
* Runs the fiber with that entry.
|
||||
* Called with each entry for a fiber whose scheduler is this one. Runs the
|
||||
* fiber once per wait, with the first entry, or directly if this scheduler
|
||||
* did not park it.
|
||||
*
|
||||
* @stability unstable
|
||||
* @since 4.2.0
|
||||
|
||||
@@ -498,11 +498,13 @@ const fiberVariance = {
|
||||
|
||||
const fiberIdStore = { id: 0 }
|
||||
|
||||
type Resumer = Pick<Scheduler.ParkingScheduler, "resume">
|
||||
type Parking = Pick<Scheduler.ParkingScheduler, "park" | "resume">
|
||||
|
||||
// Resumes a fiber that is not parked: runs it if it has not started, and does
|
||||
// nothing once it has exited
|
||||
const runDirectly: Resumer = {
|
||||
// How fibers park when their scheduler does not implement ParkingScheduler,
|
||||
// in runtimes without node:async_hooks: a fiber resumes in the caller's async
|
||||
// context
|
||||
const directParking: Parking = {
|
||||
park: constVoid,
|
||||
resume(fiber, effect) {
|
||||
fiber.run(effect)
|
||||
}
|
||||
@@ -521,31 +523,45 @@ const AsyncResource:
|
||||
}
|
||||
})()
|
||||
|
||||
// The default wait where node:async_hooks is available: an async resource
|
||||
// created where the fiber parked, which resumes the fiber inside it
|
||||
const FiberResource = AsyncResource && class extends AsyncResource implements Resumer {
|
||||
resume(fiber: Scheduler.ParkedFiber, effect: Effect.Effect<unknown, unknown>) {
|
||||
try {
|
||||
this.runInAsyncScope(fiber.run, fiber, effect)
|
||||
} finally {
|
||||
// The wait has ended, even if the run threw. Node calls destroy hooks
|
||||
// later, so this cannot re-enter the fiber. Without it, async_hooks
|
||||
// consumers would see the resource as live until it is garbage collected.
|
||||
this.emitDestroy()
|
||||
// How fibers park when their scheduler does not implement ParkingScheduler,
|
||||
// where node:async_hooks is available: each wait is an async resource created
|
||||
// where the fiber parked, and the fiber resumes inside it. Waits are keyed
|
||||
// weakly by fiber, so a fiber that is never woken can still be collected.
|
||||
const defaultParking: Parking = AsyncResource === undefined ? directParking : (() => {
|
||||
// null marks a wait that has been resumed, while the fiber runs
|
||||
const waits = new WeakMap<Fiber.Fiber<unknown, unknown>, InstanceType<typeof AsyncResource> | null>()
|
||||
return {
|
||||
park(fiber) {
|
||||
waits.set(fiber, new AsyncResource("effect/Fiber"))
|
||||
},
|
||||
resume(fiber, effect) {
|
||||
const wait = waits.get(fiber)
|
||||
if (wait === undefined) {
|
||||
// Not parked here: the fiber has not started, has exited, or was parked
|
||||
// by the scheduler it had before setContext replaced it
|
||||
return fiber.run(effect)
|
||||
}
|
||||
// Only an interrupt can arrive while the fiber enters the resource, for
|
||||
// example from an async_hooks `before` callback, and the fiber has
|
||||
// already recorded it
|
||||
if (wait === null) return
|
||||
waits.set(fiber, null)
|
||||
try {
|
||||
wait.runInAsyncScope(fiber.run, fiber, effect)
|
||||
} finally {
|
||||
// The wait has ended, even if the run threw. Node calls destroy hooks
|
||||
// later, so this cannot re-enter the fiber. Without it, async_hooks
|
||||
// consumers would see the resource as live until it is collected.
|
||||
wait.emitDestroy()
|
||||
if (waits.get(fiber) === null) waits.delete(fiber)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
// Starts a wait and returns its owner. A ParkingScheduler keeps the state of
|
||||
// the wait itself; otherwise the fiber waits the default way.
|
||||
const park = (fiber: FiberImpl): Resumer => {
|
||||
const scheduler = fiber.cache.scheduler as Partial<Scheduler.ParkingScheduler>
|
||||
if (scheduler.park) {
|
||||
scheduler.park(fiber)
|
||||
return scheduler as Scheduler.ParkingScheduler
|
||||
}
|
||||
return FiberResource ? new FiberResource("effect/Fiber") : runDirectly
|
||||
}
|
||||
// The scheduler decides how a fiber parks and resumes
|
||||
const parkingOf = (scheduler: Scheduler.Scheduler): Parking =>
|
||||
(scheduler as Partial<Parking>).park ? scheduler as Scheduler.ParkingScheduler : defaultParking
|
||||
|
||||
/** @internal */
|
||||
export const getCurrentFiber = (): Fiber.Fiber<any, any> | undefined => (globalThis as any)[currentFiberTypeId]
|
||||
@@ -570,7 +586,6 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
this._running = false
|
||||
this._deferredInterrupt = false
|
||||
this._parent = undefined
|
||||
this._parkedBy = runDirectly
|
||||
this.cache.runtimeMetrics?.recordFiberStart(this.context)
|
||||
}
|
||||
|
||||
@@ -591,12 +606,6 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
declare _running: boolean
|
||||
declare _deferredInterrupt: boolean
|
||||
declare _parent: FiberImpl<any, any> | undefined
|
||||
// The owner of the current wait, which resumes it even if setContext changes
|
||||
// the fiber's scheduler before the wait ends. Cleared once the wait is
|
||||
// resumed: an entry that arrives before the fiber runs, such as an interrupt
|
||||
// the fiber has already recorded, does nothing, and an exited fiber does not
|
||||
// keep the owner alive.
|
||||
declare _parkedBy: Resumer | undefined
|
||||
|
||||
// set in setContext
|
||||
declare context: Context.Context<never>
|
||||
@@ -656,9 +665,7 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
return this._exit
|
||||
}
|
||||
evaluate(effect: Primitive): void {
|
||||
const parkedBy = this._parkedBy
|
||||
this._parkedBy = undefined
|
||||
parkedBy?.resume(this, effect as any)
|
||||
parkingOf(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 {
|
||||
@@ -672,7 +679,7 @@ export class FiberImpl<A = any, E = any> implements Fiber.Fiber<A, E> {
|
||||
}
|
||||
const exit = this.runLoop(effect as Primitive)
|
||||
if (exit === Yield) {
|
||||
this._parkedBy = park(this)
|
||||
parkingOf(this.cache.scheduler).park(this)
|
||||
return
|
||||
}
|
||||
// the interruptChildren middleware is added in Effect.forkChild, so it can be
|
||||
@@ -5667,7 +5674,7 @@ export const forkUnsafe = <FA, FE, A, E, R>(
|
||||
child.run(effect as any)
|
||||
} else {
|
||||
// Preserve the fork context rather than the dispatcher's context.
|
||||
child._parkedBy = park(child)
|
||||
parkingOf(child.cache.scheduler).park(child)
|
||||
parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect as any), 0)
|
||||
}
|
||||
return child
|
||||
|
||||
@@ -5449,19 +5449,26 @@ describe("Effect", () => {
|
||||
|
||||
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. Its
|
||||
// state is in instance fields, so wrappers must keep the receiver, and it
|
||||
// throws if a wait is resumed more than once.
|
||||
// scheduler that hands fibers back to the request that owns them, and
|
||||
// runs it once per wait. 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 parked = new Set<Fiber.Fiber<unknown, unknown>>()
|
||||
// true once the wait is resumed, until the fiber runs
|
||||
readonly waits = new Map<Fiber.Fiber<unknown, unknown>, boolean>()
|
||||
readonly pending: Array<() => void> = []
|
||||
park(fiber: Fiber.Fiber<unknown, unknown>) {
|
||||
this.parked.add(fiber)
|
||||
this.waits.set(fiber, false)
|
||||
}
|
||||
resume(fiber: Scheduler.ParkedFiber, effect: Effect.Effect<unknown, unknown>) {
|
||||
if (!this.parked.delete(fiber)) throw new Error("not parked")
|
||||
this.pending.push(() => storage.run("owner", () => fiber.run(effect)))
|
||||
const resumed = this.waits.get(fiber)
|
||||
if (resumed === undefined) return fiber.run(effect)
|
||||
if (resumed) return
|
||||
this.waits.set(fiber, true)
|
||||
this.pending.push(() => {
|
||||
this.waits.delete(fiber)
|
||||
storage.run("owner", () => fiber.run(effect))
|
||||
})
|
||||
}
|
||||
}("sync")
|
||||
const land = async () => {
|
||||
@@ -5515,7 +5522,8 @@ describe("Effect", () => {
|
||||
assert.isTrue(Exit.hasInterrupts(fiber.pollUnsafe()!))
|
||||
})
|
||||
|
||||
it("resumes a wait through the scheduler that parked it after the fiber's scheduler changes", async () => {
|
||||
it("resumes a parked fiber through the scheduler that replaced the one it parked with", async () => {
|
||||
// The new scheduler did not park the fiber, so it runs it directly
|
||||
const { land, scheduler } = makeScheduler()
|
||||
let wake!: () => void
|
||||
const fiber = Effect.runFork(
|
||||
@@ -5527,8 +5535,7 @@ describe("Effect", () => {
|
||||
await land()
|
||||
fiber.setContext(Context.add(fiber.context, Scheduler.Scheduler, new Scheduler.MixedScheduler("sync")))
|
||||
storage.run("waker", wake)
|
||||
await land()
|
||||
assert.deepStrictEqual(fiber.pollUnsafe(), Exit.succeed("owner"))
|
||||
assert.deepStrictEqual(fiber.pollUnsafe(), Exit.succeed("waker"))
|
||||
})
|
||||
|
||||
it.skipIf(process.versions.bun !== undefined || process.versions.deno !== undefined)(
|
||||
|
||||
@@ -108,7 +108,8 @@ type Settle = (task: () => void) => void
|
||||
* @since 4.2.0
|
||||
*/
|
||||
export class CloudflareScheduler extends Scheduler.MixedScheduler implements Scheduler.ParkingScheduler {
|
||||
// Weak, so a fiber that is never resumed can still be garbage collected
|
||||
// The wait of each parked fiber, until it runs. Weak, so a fiber that is
|
||||
// never woken can still be garbage collected.
|
||||
readonly #waits = new WeakMap<Fiber.Fiber<unknown, unknown>, Settle>()
|
||||
|
||||
/**
|
||||
@@ -134,14 +135,19 @@ export class CloudflareScheduler extends Scheduler.MixedScheduler implements Sch
|
||||
*/
|
||||
park(fiber: Fiber.Fiber<unknown, unknown>): void {
|
||||
const timer = setPendingTimer()
|
||||
let settle!: Settle
|
||||
keepOwnerAlive(
|
||||
new Promise<() => void>((resolve) => {
|
||||
this.#waits.set(fiber, resolve)
|
||||
settle = resolve
|
||||
}).then((task) => {
|
||||
if (timer !== undefined) clearTimeout(timer)
|
||||
if (this.#waits.get(fiber) === settle) this.#waits.delete(fiber)
|
||||
task()
|
||||
})
|
||||
)
|
||||
// A wait left by a scheduler replacement ends without running the fiber
|
||||
this.#waits.get(fiber)?.(noop)
|
||||
this.#waits.set(fiber, settle)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,9 +157,16 @@ export class CloudflareScheduler extends Scheduler.MixedScheduler implements Sch
|
||||
* @since 4.2.0
|
||||
*/
|
||||
resume(fiber: Scheduler.ParkedFiber, effect: Effect<unknown, unknown>): void {
|
||||
// Removed before the fiber runs, as it may park again
|
||||
const settle = this.#waits.get(fiber)!
|
||||
this.#waits.delete(fiber)
|
||||
const settle = this.#waits.get(fiber)
|
||||
if (settle === undefined) {
|
||||
// Not parked here: the fiber has not started, has exited, or was parked
|
||||
// by the scheduler it had before setContext replaced it
|
||||
fiber.run(effect)
|
||||
return
|
||||
}
|
||||
// The wait stays until the fiber runs. Only the first call settles the
|
||||
// promise, so the fiber runs once, with the first entry. An interrupt
|
||||
// arriving later is already recorded on it.
|
||||
settle(() => fiber.run(effect))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user