import { Cause, Context, Effect, Exit, Fiber, Option, Supervisor } from "effect"; /** Observe Layer workers as well as operation children, including suspended work. */ export class DriverSupervisor extends Supervisor.AbstractSupervisor { private readonly roots = new Set(); private readonly active = new Map(); private readonly failures: Cause.Cause[] = []; private readonly children: Cause.Cause[] = []; override value: Effect.Effect = Effect.sync(() => this.active.size); registerRoot(fiber: Fiber.RuntimeFiber): void { this.roots.add(fiber.id().id); if (this.active.has(fiber.id().id)) this.active.set(fiber.id().id, true); } forgetRoot(fiber: Fiber.RuntimeFiber): void { this.roots.delete(fiber.id().id); } pending(): number { return this.active.size; } backgroundFailures(): readonly Cause.Cause[] { return [...this.failures]; } childFailures(): readonly Cause.Cause[] { return [...this.children]; } backgroundFailureCount(): number { return this.failures.filter(cause => !Cause.isInterruptedOnly(cause)).length; } override onStart( _context: Context.Context, _effect: Effect.Effect, parent: Parameters["onStart"]>[2], fiber: Fiber.RuntimeFiber, ): void { const parentId = Option.isSome(parent) ? parent.value.id().id : undefined; const operationOwned = this.roots.has(fiber.id().id) || (parentId !== undefined && (this.roots.has(parentId) || this.active.get(parentId) === true)); this.active.set(fiber.id().id, operationOwned); } override onEnd(exit: Exit.Exit, fiber: Fiber.RuntimeFiber): void { if (Exit.isFailure(exit) && !this.roots.has(fiber.id().id)) { if (this.active.get(fiber.id().id) === false) this.failures.push(exit.cause); else if (this.active.get(fiber.id().id) === true) this.children.push(exit.cause); } this.active.delete(fiber.id().id); } }