@mark1russell7/service 0.8.20 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/build/builder.js +2 -2
- package/build/builder.js.map +1 -1
- package/build/channel.js.map +1 -1
- package/build/client/core.js.map +1 -1
- package/build/clock.d.ts +2 -2
- package/build/clock.js +1 -1
- package/build/conformance.js +3 -4
- package/build/conformance.js.map +1 -1
- package/build/health.js +4 -2
- package/build/health.js.map +1 -1
- package/build/heartbeat.d.ts +5 -1
- package/build/heartbeat.js.map +1 -1
- package/build/host/group.js +11 -4
- package/build/host/group.js.map +1 -1
- package/build/http/transport.js +1 -0
- package/build/http/transport.js.map +1 -1
- package/build/http-client/client.js.map +1 -1
- package/build/http-client/session.js +2 -2
- package/build/http-client/session.js.map +1 -1
- package/build/index.d.ts +2 -2
- package/build/index.js +2 -2
- package/build/latch.js.map +1 -1
- package/build/lifecycle.js.map +1 -1
- package/build/poller.js +2 -0
- package/build/poller.js.map +1 -1
- package/build/rabbitmq/client.js.map +1 -1
- package/build/redis/client.js +2 -2
- package/build/redis/client.js.map +1 -1
- package/build/requests.js.map +1 -1
- package/build/retrier.js.map +1 -1
- package/build/units.js.map +1 -1
- package/build/watchdog.d.ts +5 -1
- package/build/watchdog.js +5 -1
- package/build/watchdog.js.map +1 -1
- package/build/websocket/client.js +2 -2
- package/build/websocket/client.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -317,11 +317,15 @@ The clock, the heartbeat and the backoff have their own entries. Each entry impo
|
|
|
317
317
|
|
|
318
318
|
| Entry | Exports |
|
|
319
319
|
| --- | --- |
|
|
320
|
-
| `@mark1russell7/service/clock` | `Clock`, `Cancel`, `realClock`, `platformClock` |
|
|
320
|
+
| `@mark1russell7/service/clock` | `Clock`, `Cancel`, `realClock`, `platformClock`, `unrefClock` |
|
|
321
321
|
| `@mark1russell7/service/heartbeat` | `heartbeat`, `detectionTime` |
|
|
322
322
|
| `@mark1russell7/service/backoff` | `backoffDelay`, `backoffBand`, `backoffProblems` |
|
|
323
323
|
|
|
324
|
-
- **The clock.** `platformClock({ unref })` gives a clock on `performance.now()` and `setTimeout`. With `unref: true`, its timers do not keep a Node process alive. `realClock` is
|
|
324
|
+
- **The clock.** `platformClock({ unref })` gives a clock on `performance.now()` and `setTimeout`. With `unref: true`, its timers do not keep a Node process alive. `realClock` is `platformClock()`: its timers keep the process alive, as `setTimeout` does. Each cancel also has `unref`, for one timer.
|
|
325
|
+
- **The rule of `unref`.** The service uses the `unref` of a timer only when a socket, a child process or the hold of the lifecycle keeps the process alive. Each other timer stays referenced. Thus a wait that a caller awaits, for example `retry` or `within`, ends before the process exits.
|
|
326
|
+
- **The timers that do not keep the process alive.** These timers only watch other work. Examples are the heartbeat of a connection, the checks and the watchdog of a service, and the sweep of a listener. The timers of a supervisor for a live child are also examples. `unrefClock(clock)` gives a part such a clock.
|
|
327
|
+
- **The timers that keep the process alive.** These timers are work, or they bound work that a caller awaits. Examples are a retry, a ticker, the sleeps of a worker loop and the polls of `watchTargets`. The owner stops each one.
|
|
328
|
+
- **Before 0.9.0.** The default clock did not keep the process alive. Thus a command-line tool ended in the wait of a retry, with the code 0 and lost work.
|
|
325
329
|
- **The home of the clock.** The clock lives in `@mark1russell7/algebra/clock`, beside its fake. This entry gives the same functions. Thus a package that the service imports, for example collections, can use the clock with no cycle.
|
|
326
330
|
- **The heartbeat.** `heartbeat(options)` sends a ping each interval, and a timeout bounds each ping. A ping without an answer at its timeout is a miss. The last of `misses` misses in sequence starts `onDead`.
|
|
327
331
|
- **Two kinds of ping.** A ping gives its answer as a promise, as a request and its reply do. Or the answer comes later through `answer()`, as a pong message does.
|
package/build/builder.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { FORMAT } from "./description.js";
|
|
2
|
-
import { realClock } from "./clock.js";
|
|
2
|
+
import { realClock, unrefClock } from "./clock.js";
|
|
3
3
|
import { limiterProblems } from "./limiter/policy.js";
|
|
4
4
|
import { healthRuntime } from "./health.js";
|
|
5
5
|
import { logEvents } from "./logger.js";
|
|
@@ -135,7 +135,7 @@ const service = (name) => {
|
|
|
135
135
|
const dogs = [];
|
|
136
136
|
const all = new Map(runs);
|
|
137
137
|
for (const spec of watchdogs) {
|
|
138
|
-
const dog = watchdog(clock, spec, (from, to, on) => options.record?.({
|
|
138
|
+
const dog = watchdog(unrefClock(clock), spec, (from, to, on) => options.record?.({
|
|
139
139
|
at: clock.now(),
|
|
140
140
|
machine: "watchdog",
|
|
141
141
|
instance: spec.name,
|
package/build/builder.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder.js","names":[],"sources":["../src/builder.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, valueIn } from \"@mark1russell7/quantity\";\nimport type {\n Check,\n Controller,\n CooperativeFloor,\n Coupling,\n Dependency,\n ExitCodes,\n Gate,\n MessageTrigger,\n Phase,\n RepeatSignal,\n ServiceDescription,\n Transport,\n} from \"./description.ts\";\nimport { FORMAT } from \"./description.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { Health, Runtime, StartOptions } from \"./health.ts\";\nimport type { Limiter, LimiterSpec } from \"./limiter/policy.ts\";\nimport { limiterProblems } from \"./limiter/policy.ts\";\nimport { healthRuntime } from \"./health.ts\";\nimport { logEvents } from \"./logger.ts\";\nimport type {\n Components,\n DependencyHandle,\n HealthServer,\n Lifecycle,\n PhaseWork,\n RunOptions,\n TransportImpl,\n} from \"./lifecycle.ts\";\nimport { STAGES, lifecycle, lifecycleProblems, stageRank, uncaughtProblems } from \"./lifecycle.ts\";\nimport type { Operation } from \"./operation.ts\";\nimport { operationProblems } from \"./operation.ts\";\nimport type { CheckFn } from \"./poller.ts\";\nimport type { ExitTrigger, ProcessTrigger } from \"./process.ts\";\nimport { EXIT_SIGNALS, PROCESS_TRIGGERS, isExitCode, isExitSignal, isMessageShape } from \"./process.ts\";\nimport type { Profile } from \"./profiles.ts\";\nimport type { OperationOf, RoutePattern } from \"./routes.ts\";\nimport { routePatternProblems } from \"./routes.ts\";\nimport type { Timing } from \"./timing.ts\";\nimport type { Watchdog, WatchdogSpec } from \"./watchdog.ts\";\nimport { watchdog } from \"./watchdog.ts\";\n\n/**\n * The caller composes a service with plain method uses before it starts. The builder is imperative, and\n * it holds static knowledge. The service does not use an `init` function that gives registrations.\n *\n * const svc = service(\"app\");\n * svc.dependency(\"weather\", {\n * system: null,\n * knobs: { request_timeout },\n * operations: { \"GET /v1/forecast\": { idempotent: true } },\n * });\n * svc.controller(\"forecast\").requires(\"weather\").route(\"GET /api/forecast\", { idempotent: true });\n * svc.check({ name: \"weather.round-trip\", dependency: \"weather\", … }, roundTrip);\n * svc.describe(); // the whole graph as data, with nothing started\n * const health = await svc.start();\n *\n * The graph has one source, thus its parts cannot disagree. A dependency or a check can join\n * after the start. It starts tripped, and the export is partial. The runtime has no defaults of\n * its own. Thus `describe()` refuses a service that does not declare a policy, its startup budget\n * or its shutdown, and it tells which. The shutdown includes what a repeat signal does.\n *\n * `start()` starts only the health runtime. `run()` starts the whole lifecycle: the startup in its\n * sequence, the exit signals, the capped phases of the shutdown, and the exit of the process.\n */\nexport interface ControllerBuilder {\n /** This method declares the dependencies that its routes need. The controller is ready only while they are ready. */\n requires(...dependencies: string[]): ControllerBuilder;\n /** This method declares a route that the controller serves, and if its callers can send it again. */\n route(route: string, operation: Operation): ControllerBuilder;\n /**\n * This method declares a route pattern, the operations that its requests can be, and the function\n * that picks the operation of each request. A pattern with one operation needs no function.\n */\n pattern(pattern: string, operations: Readonly<Record<string, Operation>>, operationOf?: OperationOf): ControllerBuilder;\n}\n\n/** A service builder composes a service, gives it as data, and starts it. */\nexport interface ServiceBuilder {\n readonly name: string;\n /** This method declares a dependency, and the handle that connects to it and closes it, if it has one. */\n dependency(name: string, spec: Omit<Dependency, \"name\">, handle?: DependencyHandle): ServiceBuilder;\n /** This method declares a server, and its implementation. `run()` needs the implementation. */\n server(name: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl): ServiceBuilder;\n consumer(name: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl): ServiceBuilder;\n worker(name: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl): ServiceBuilder;\n /** This method gives the server of the probes. It starts first and closes last. */\n healthServer(server: HealthServer): ServiceBuilder;\n /** This method adds work to a declared phase of the shutdown: the owner of the work registers it. */\n onPhase(phase: string, work: PhaseWork): ServiceBuilder;\n /** This method declares a watchdog of the event loop, as a check on the state of the process. */\n watchdog(spec: WatchdogSpec): ServiceBuilder;\n controller(name: string): ControllerBuilder;\n /** This method declares a check, and the function that measures its step. `start()` needs the function. */\n check(check: Check, run?: CheckFn): ServiceBuilder;\n /**\n * This method declares a keyed limiter as data: its key, its policy, its store and the bound on its\n * keys. `describe()` shows it and refuses a part that is absent, because a limiter has no defaults.\n * `keyedLimiter(name, spec, store)` makes its runtime from the same spec.\n */\n limiter(name: string, spec: LimiterSpec): ServiceBuilder;\n readiness(timing: Timing): ServiceBuilder;\n liveness(timing: Timing): ServiceBuilder;\n startup(budget: Quantity): ServiceBuilder;\n couple(coupling: Coupling): ServiceBuilder;\n phase(name: string, cap: Quantity): ServiceBuilder;\n cooperativeWindow(window: Extent): ServiceBuilder;\n /** This method declares the earliest time of the cooperative abort: half the cap of the drain, or no floor. */\n cooperativeFloor(floor: CooperativeFloor): ServiceBuilder;\n /** This method declares what an exit signal does while the shutdown runs: nothing, or an exit at once. */\n onRepeatSignal(policy: RepeatSignal): ServiceBuilder;\n /** This method declares process triggers that start the shutdown, in addition to the exit signals. */\n trigger(...triggers: ProcessTrigger[]): ServiceBuilder;\n /**\n * This method declares a message of the IPC channel that starts the shutdown, as data. With `as`,\n * the message is that exit signal: `svc.trigger(\"ipc-message\", { match: \"shutdown\", as: \"SIGTERM\" })`.\n */\n trigger(trigger: \"ipc-message\", message: MessageTrigger): ServiceBuilder;\n /** This method declares the exit code of a clean shutdown that a trigger starts, in place of 0. */\n exitCode(trigger: ExitTrigger, code: number): ServiceBuilder;\n /** This method declares each field of a profile, as the method of that field does. */\n profile(profile: Profile): ServiceBuilder;\n /** This method gives the service as data, and it starts nothing. */\n describe(): ServiceDescription;\n /**\n * This method closes the composition, starts the health runtime, and gives it after one warm-up\n * sweep of each check. A part that joins after it starts tripped, and it makes the export\n * partial. A second use gives the same runtime.\n */\n start(options?: StartOptions): Promise<Health>;\n /**\n * This method starts the whole lifecycle and gives it when its startup ends: the service operates,\n * or its startup failed and it shuts down. It refuses a declaration that it cannot start: a transport\n * without its implementation, or a stage with work and no declared phase.\n */\n run(options?: RunOptions): Promise<Lifecycle>;\n /**\n * This value is the health runtime from the time that `start()` begins, or null before. Thus the\n * probes can answer during the warm-up sweep: the startup probe fails until the sweep ends.\n */\n readonly health: Health | null;\n /**\n * This value is the lifecycle from the time that `run()` begins, or null before. Its request\n * tracking operates while the transports start, before `run()` gives it.\n */\n readonly lifecycle: Lifecycle | null;\n}\n\nconst isTime = (amount: Extent): boolean => convertible(amount.unit, \"s\");\nconst above = (amount: Extent): boolean =>\n amount.value === \"infinite\" || (isTime(amount) && valueIn(amount as Quantity, \"s\") > 0);\nconst whole = (count: number): boolean => Number.isInteger(count) && count >= 1;\n/** This function copies a check, with its poll and the loops that mark it. */\nconst copyCheck = (check: Check): Check => ({\n ...check,\n poll: { ...check.poll },\n ...(check.marks === undefined ? {} : { marks: { loops: [...check.marks.loops], stall: { ...check.marks.stall } } }),\n});\n/** This function gives the problems of the loops that mark a check. `lint()` compares the stall time with the loops. */\nconst marksProblems = (check: Check): string[] => {\n const marks = check.marks;\n if (marks === undefined) return [];\n const problems: string[] = [];\n if (check.step !== \"progress\")\n problems.push(`check ${check.name} names the loops that mark it, but its step is ${check.step}, not progress`);\n if (marks.loops.length === 0) problems.push(`check ${check.name} names no loop that marks it`);\n // a description from JSON can give a stall time without a bound, which is not a stall time\n if (typeof marks.stall.value !== \"number\" || !above(marks.stall))\n problems.push(`check ${check.name} has a stall time that is not a time above zero`);\n return problems;\n};\n\n/** This function gives the problems of a timing: a zero interval or count fails decoding. */\nconst timingProblems = (policy: Gate, timing: Timing): string[] => {\n if (timing.type === \"debounce\") {\n const problems: string[] = [];\n if (!above(timing.interval)) problems.push(`the ${policy} debounce polls at an interval that is not above zero`);\n if (!whole(timing.failAfter)) problems.push(`the ${policy} debounce fails after ${timing.failAfter} polls, not a whole number above zero`);\n if (!whole(timing.recoverAfter)) problems.push(`the ${policy} debounce recovers after ${timing.recoverAfter} polls, not a whole number above zero`);\n return problems;\n }\n const negative = (amount: Quantity | undefined): boolean =>\n amount !== undefined && (!isTime(amount) || valueIn(amount, \"s\") < 0);\n return negative(timing.failAfter) || negative(timing.recoverAfter)\n ? [`the ${policy} window is not a time of zero or more`]\n : [];\n};\n\n/** This function gives the problems of the rules of the shutdown: an unknown name, or an exit code that a process cannot give. */\nconst shutdownProblems = (\n floor: CooperativeFloor | undefined,\n repeat: RepeatSignal | undefined,\n triggers: readonly ProcessTrigger[],\n exitCodes: ExitCodes,\n messages: readonly MessageTrigger[],\n): string[] => {\n const problems: string[] = [];\n if (floor !== undefined && floor !== \"half\" && floor !== \"none\")\n problems.push(`the cooperative floor ${String(floor)} is not \"half\" or \"none\"`);\n if (repeat !== undefined && repeat !== \"ignore\" && repeat !== \"exit\")\n problems.push(`the policy of a repeat signal ${String(repeat)} is not \"ignore\" or \"exit\"`);\n for (const trigger of triggers)\n if (!PROCESS_TRIGGERS.includes(trigger))\n problems.push(`the trigger ${String(trigger)} is not a process trigger (${PROCESS_TRIGGERS.join(\", \")})`);\n if (triggers.includes(\"ipc-message\") && messages.length === 0)\n problems.push(`the trigger ipc-message has no message to match: declare it with svc.trigger(\"ipc-message\", { match })`);\n for (const message of messages) {\n if (!isMessageShape(message.match))\n problems.push(`the match of a message trigger is not a value of JSON: ${String(message.match)}`);\n if (message.as !== undefined && !isExitSignal(message.as))\n problems.push(`a message trigger stands for ${String(message.as)}, not an exit signal (${EXIT_SIGNALS.join(\", \")})`);\n }\n for (const [trigger, code] of Object.entries(exitCodes)) {\n const known = (EXIT_SIGNALS as readonly string[]).includes(trigger) || triggers.includes(trigger as ProcessTrigger);\n if (!known) problems.push(`the exit code of ${trigger} names no exit signal and no declared trigger`);\n if (code === undefined || !isExitCode(code))\n problems.push(`the exit code of ${trigger} is ${String(code)}, not a whole number from 0 to 255`);\n }\n return problems;\n};\n\n/**\n * This function gives the options with one recorder for the recorder and the logger of the options.\n * Without a logger, it gives the same options.\n */\nconst withLogger = <O extends StartOptions>(options: O, description: ServiceDescription): O => {\n if (options.logger === undefined) return options;\n const given = options.record;\n const log = logEvents(options.logger, description);\n return {\n ...options,\n record: (event) => {\n given?.(event);\n log(event);\n },\n };\n};\n\n/** This function starts the composition of a service. */\nexport const service = (name: string): ServiceBuilder => {\n if (name.trim().length === 0) throw new Error(\"a service needs a name\");\n const transports: Transport[] = [];\n const dependencies: Dependency[] = [];\n const controllers: Array<{\n name: string;\n requires: string[];\n routes: Record<string, Operation>;\n patterns: RoutePattern[];\n }> = [];\n // the function of each route pattern, by controller and by pattern\n const choices = new Map<string, Map<string, OperationOf>>();\n const checks: Check[] = [];\n const runs = new Map<string, CheckFn>();\n const limiters: Limiter[] = [];\n const couplings: Coupling[] = [];\n const phases: Phase[] = [];\n let readiness: Timing | undefined;\n let liveness: Timing | undefined;\n let startup: Quantity | undefined;\n let cooperative: Extent | undefined;\n let floor: CooperativeFloor | undefined;\n let repeat: RepeatSignal | undefined;\n const triggers: ProcessTrigger[] = [];\n const messages: MessageTrigger[] = [];\n const exitCodes: Partial<Record<ExitTrigger, number>> = {};\n let started = false;\n let partial = false;\n let runtime: Promise<Health> | undefined;\n let live: Runtime | undefined;\n let running: Promise<Lifecycle> | undefined;\n let life: Lifecycle | undefined;\n const transportImpls = new Map<string, TransportImpl>();\n const handles = new Map<string, DependencyHandle>();\n const phaseWork = new Map<string, PhaseWork[]>();\n const watchdogs: WatchdogSpec[] = [];\n let probes: HealthServer | null = null;\n\n /** This function stops a change to the shape of the service after the start. */\n const composing = (what: string): void => {\n if (started) throw new Error(`${name} has started: ${what} is declared before svc.start()`);\n };\n const once = (list: ReadonlyArray<{ name: string }>, entry: string, what: string): void => {\n if (list.some((held) => held.name === entry))\n throw new Error(`${name} already has a ${what} named ${entry}`);\n };\n const transport =\n (kind: Transport[\"kind\"]) =>\n (entry: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl) => {\n composing(`a ${kind}`);\n once(transports, entry, \"transport\");\n transports.push({ name: entry, kind, knobs: { ...knobs } });\n if (impl !== undefined) transportImpls.set(entry, impl);\n return builder;\n };\n\n /** This function makes the runtime of the declaration: its checks, and a watchdog for each spec. */\n const makeRuntime = <O extends StartOptions>(\n given: O,\n ): { runtime: Runtime; description: ServiceDescription; stopPollers: () => void; options: O } => {\n const description = builder.describe();\n // the logger is one sink of the stream of the recorder: each machine writes to both\n const options = withLogger(given, description);\n const clock = options.clock ?? realClock;\n const dogs: Watchdog[] = [];\n const all = new Map(runs);\n for (const spec of watchdogs) {\n const dog = watchdog(clock, spec, (from, to, on) =>\n options.record?.({ at: clock.now(), machine: \"watchdog\", instance: spec.name, from, to, on }),\n );\n dogs.push(dog);\n all.set(spec.name, () => dog.check());\n }\n const stopPollers = (): void => {\n for (const dog of dogs) dog.stop();\n };\n let made: Runtime;\n try {\n made = healthRuntime(description, all, options);\n } catch (error) {\n stopPollers();\n throw error;\n }\n // the stop of the health runtime also stops the watchdogs\n const runtime: Runtime = {\n ...made,\n stop: () => {\n made.stop();\n stopPollers();\n },\n };\n return { runtime, description, stopPollers, options };\n };\n\n const builder: ServiceBuilder = {\n name,\n get health() {\n return live ?? null;\n },\n get lifecycle() {\n return life ?? null;\n },\n dependency(entry, spec, handle) {\n once(dependencies, entry, \"dependency\");\n // a dependency that joins after the start has no connection that the lifecycle opens\n if (handle !== undefined && !started) handles.set(entry, handle);\n dependencies.push({\n name: entry,\n ...spec,\n knobs: { ...spec.knobs },\n operations: { ...spec.operations },\n });\n if (started) {\n partial = true;\n live?.addDependency(entry);\n }\n return builder;\n },\n server: transport(\"server\"),\n consumer: transport(\"consumer\"),\n worker: transport(\"worker\"),\n controller(entry) {\n composing(\"a controller\");\n once(controllers, entry, \"controller\");\n const held = {\n name: entry,\n requires: [] as string[],\n routes: {} as Record<string, Operation>,\n patterns: [] as RoutePattern[],\n };\n controllers.push(held);\n const handle: ControllerBuilder = {\n requires(...needed) {\n composing(`what ${entry} requires`);\n held.requires.push(...needed);\n return handle;\n },\n route(served, operation) {\n composing(`${entry}'s routes`);\n if (held.routes[served] !== undefined)\n throw new Error(`${entry} already serves ${served}`);\n held.routes[served] = { ...operation };\n return handle;\n },\n pattern(pattern, operations, operationOf) {\n composing(`${entry}'s route patterns`);\n if (held.patterns.some((each) => each.pattern === pattern))\n throw new Error(`${entry} already has the route pattern ${pattern}`);\n // the function is not data, thus the builder checks it here, and describe() checks the rest\n if (operationOf === undefined && Object.keys(operations).length > 1)\n throw new Error(`${entry}'s pattern ${pattern} has ${Object.keys(operations).length} operations, thus it needs the function that picks one`);\n held.patterns.push({\n pattern,\n operations: Object.fromEntries(Object.entries(operations).map(([name, operation]) => [name, { ...operation }])),\n });\n if (operationOf !== undefined) {\n const mine = choices.get(entry) ?? new Map<string, OperationOf>();\n mine.set(pattern, operationOf);\n choices.set(entry, mine);\n }\n return handle;\n },\n };\n return handle;\n },\n check(check, run) {\n once(checks, check.name, \"check\");\n if (started && run === undefined)\n throw new Error(`check ${check.name} joins after the start, thus it needs its function`);\n checks.push(copyCheck(check));\n if (run !== undefined) runs.set(check.name, run);\n if (started) {\n partial = true;\n live?.addCheck(copyCheck(check), run!);\n }\n return builder;\n },\n limiter(entry, spec) {\n composing(`the limiter ${entry}`);\n once(limiters, entry, \"limiter\");\n // the spec is data: the builder keeps a copy, and describe() checks each part\n const given = (spec ?? {}) as Partial<LimiterSpec>;\n limiters.push({\n name: entry,\n ...given,\n ...(given.policy === undefined ? {} : { policy: { ...given.policy } }),\n ...(given.store === undefined ? {} : { store: { ...given.store } }),\n ...(given.evict === undefined ? {} : { evict: { ...given.evict } }),\n } as Limiter);\n return builder;\n },\n healthServer(server) {\n composing(\"the health server\");\n if (probes !== null) throw new Error(`${name} already has a health server`);\n probes = server;\n return builder;\n },\n onPhase(phase, work) {\n composing(`work for the phase ${phase}`);\n phaseWork.set(phase, [...(phaseWork.get(phase) ?? []), work]);\n return builder;\n },\n watchdog(spec) {\n composing(`the watchdog ${spec.name}`);\n once(checks, spec.name, \"check\");\n // the watchdog is a check on the state of the process itself, on its own connection\n checks.push({\n name: spec.name,\n dependency: null,\n step: \"local-state\",\n ownConnection: true,\n gates: spec.gates,\n poll: { ...spec.poll },\n });\n watchdogs.push(spec);\n return builder;\n },\n readiness(timing) {\n composing(\"readiness\");\n readiness = timing;\n return builder;\n },\n liveness(timing) {\n composing(\"liveness\");\n liveness = timing;\n return builder;\n },\n startup(budget) {\n composing(\"the startup budget\");\n startup = budget;\n return builder;\n },\n couple(coupling) {\n composing(\"a coupling\");\n couplings.push({ ...coupling });\n return builder;\n },\n phase(entry, cap) {\n composing(\"a shutdown phase\");\n once(phases, entry, \"shutdown phase\");\n phases.push({ name: entry, cap });\n return builder;\n },\n cooperativeWindow(window) {\n composing(\"the cooperative window\");\n cooperative = window;\n return builder;\n },\n cooperativeFloor(given) {\n composing(\"the cooperative floor\");\n floor = given;\n return builder;\n },\n onRepeatSignal(policy) {\n composing(\"the policy of a repeat signal\");\n repeat = policy;\n return builder;\n },\n trigger(...given: ReadonlyArray<ProcessTrigger | MessageTrigger>) {\n composing(\"a trigger\");\n const [first, message] = given;\n if (first === \"ipc-message\" && typeof message === \"object\" && message !== null) {\n if (!triggers.includes(\"ipc-message\")) triggers.push(\"ipc-message\");\n messages.push({ ...message });\n return builder;\n }\n for (const each of given) if (typeof each === \"string\" && !triggers.includes(each)) triggers.push(each);\n return builder;\n },\n exitCode(trigger, code) {\n composing(`the exit code of ${trigger}`);\n exitCodes[trigger] = code;\n return builder;\n },\n profile(given) {\n composing(\"a profile\");\n if (given.readiness !== undefined) builder.readiness(given.readiness);\n if (given.liveness !== undefined) builder.liveness(given.liveness);\n if (given.startup !== undefined) builder.startup(given.startup);\n for (const coupling of given.couplings ?? []) builder.couple(coupling);\n for (const each of given.phases ?? []) builder.phase(each.name, each.cap);\n if (given.cooperativeWindow !== undefined) builder.cooperativeWindow(given.cooperativeWindow);\n if (given.cooperativeFloor !== undefined) builder.cooperativeFloor(given.cooperativeFloor);\n if (given.onRepeatSignal !== undefined) builder.onRepeatSignal(given.onRepeatSignal);\n if (given.triggers !== undefined) builder.trigger(...given.triggers);\n for (const message of given.messages ?? []) builder.trigger(\"ipc-message\", message);\n for (const [trigger, code] of Object.entries(given.exitCodes ?? {}))\n if (code !== undefined) builder.exitCode(trigger as ExitTrigger, code);\n return builder;\n },\n describe() {\n const missing: string[] = [];\n if (readiness === undefined) missing.push(\"readiness (svc.readiness)\");\n if (liveness === undefined) missing.push(\"liveness (svc.liveness)\");\n if (startup === undefined) missing.push(\"a startup budget (svc.startup)\");\n if (phases.length === 0) missing.push(\"its shutdown phases (svc.phase)\");\n if (cooperative === undefined)\n missing.push(\"a cooperative window, or no bound (svc.cooperativeWindow)\");\n if (repeat === undefined)\n missing.push(`what a repeat signal does, \"ignore\" or \"exit\" (svc.onRepeatSignal)`);\n if (missing.length > 0)\n throw new Error(\n `${name} does not declare ${missing.join(\"; \")}: the runtime has no defaults`,\n );\n const known = new Set(dependencies.map((entry) => entry.name));\n const problems: string[] = [];\n const policies: Record<Gate, Timing> = { readiness: readiness!, liveness: liveness! };\n for (const gate of [\"readiness\", \"liveness\"] as const)\n problems.push(...timingProblems(gate, policies[gate]));\n for (const check of checks) {\n if (check.dependency !== null && !known.has(check.dependency)) {\n problems.push(\n `check ${check.name} exercises ${check.dependency}, which is not a dependency`,\n );\n }\n if (!isTime(check.poll.interval) || !isTime(check.poll.timeout)) {\n problems.push(`check ${check.name} polls in a unit that is not a time`);\n } else if (!above(check.poll.interval) || !above(check.poll.timeout)) {\n problems.push(`check ${check.name} polls with an interval or a timeout that is not above zero`);\n }\n if (!(check.poll.jitter >= 0 && check.poll.jitter < 1))\n problems.push(`check ${check.name} has a jitter of ${check.poll.jitter}, not a fraction below 1`);\n problems.push(...marksProblems(check));\n // a debounce counts the polls of each check that it gates, thus they poll at its interval\n const timing = check.gates === null ? null : policies[check.gates];\n if (\n timing?.type === \"debounce\" &&\n isTime(check.poll.interval) &&\n above(timing.interval) &&\n valueIn(check.poll.interval, \"s\") !== valueIn(timing.interval, \"s\")\n )\n problems.push(\n `check ${check.name} polls every ${valueIn(check.poll.interval, \"s\")} s, but the ${check.gates} debounce counts polls every ${valueIn(timing.interval, \"s\")} s`,\n );\n }\n for (const controller of controllers) {\n for (const needed of controller.requires) {\n if (!known.has(needed))\n problems.push(\n `controller ${controller.name} requires ${needed}, which is not a dependency`,\n );\n }\n for (const [route, operation] of Object.entries(controller.routes))\n problems.push(...operationProblems(`controller ${controller.name}`, route, operation));\n for (const declared of controller.patterns)\n problems.push(...routePatternProblems(`controller ${controller.name}`, declared));\n }\n for (const limiter of limiters) {\n const { name: entry, ...spec } = limiter;\n problems.push(...limiterProblems(entry, spec));\n if (limiter.store?.kind === \"shared\" && typeof limiter.store.dependency === \"string\" && !known.has(limiter.store.dependency))\n problems.push(`limiter ${entry} keeps its counts in ${limiter.store.dependency}, which is not a dependency`);\n }\n for (const dependency of dependencies)\n for (const [name, operation] of Object.entries(dependency.operations))\n problems.push(...operationProblems(`dependency ${dependency.name}`, name, operation));\n for (const phase of phases)\n if (!isTime(phase.cap)) problems.push(`phase ${phase.name}'s cap is not a time`);\n problems.push(...shutdownProblems(floor, repeat, triggers, exitCodes, messages));\n // the stages of the shutdown keep their sequence: readiness fails first, the health server closes last\n const ranked = phases.map((phase) => phase.name).filter((each) => stageRank(each) >= 0);\n for (let at = 1; at < ranked.length; at += 1)\n if (stageRank(ranked[at]!) < stageRank(ranked[at - 1]!))\n problems.push(\n `the phase \"${ranked[at]!}\" comes after \"${ranked[at - 1]!}\", but the stages go ${STAGES.join(\", \")}`,\n );\n if (problems.length > 0) throw new Error(`${name}: ${problems.join(\"; \")}`);\n const controllersOut: Controller[] = controllers.map((entry) => ({\n name: entry.name,\n requires: [...entry.requires],\n routes: { ...entry.routes },\n ...(entry.patterns.length === 0\n ? {}\n : { patterns: entry.patterns.map((each) => ({ pattern: each.pattern, operations: { ...each.operations } })) }),\n }));\n return {\n format: FORMAT,\n name,\n partial,\n transports: transports.map((entry) => ({ ...entry, knobs: { ...entry.knobs } })),\n dependencies: dependencies.map((entry) => ({\n ...entry,\n knobs: { ...entry.knobs },\n operations: { ...entry.operations },\n })),\n controllers: controllersOut,\n checks: checks.map(copyCheck),\n ...(limiters.length === 0\n ? {}\n : {\n limiters: limiters.map((entry) => ({\n ...entry,\n policy: { ...entry.policy },\n store: { ...entry.store },\n evict: { maxKeys: { ...entry.evict.maxKeys } },\n })),\n }),\n policies: { readiness: readiness!, liveness: liveness!, startup: startup! },\n couplings: couplings.map((entry) => ({ ...entry })),\n shutdown: {\n phases: phases.map((entry) => ({ ...entry })),\n cooperativeWindow: cooperative!,\n ...(floor === undefined ? {} : { cooperativeFloor: floor }),\n onRepeatSignal: repeat!,\n ...(triggers.length === 0 ? {} : { triggers: [...triggers] }),\n ...(messages.length === 0 ? {} : { messages: messages.map((each) => ({ ...each })) }),\n ...(Object.keys(exitCodes).length === 0 ? {} : { exitCodes: { ...exitCodes } }),\n },\n };\n },\n start(options = {}) {\n // the start needs the whole graph: describe() is the check, and the runtime reads it\n if (runtime !== undefined) return runtime;\n if (running !== undefined) return Promise.reject(new Error(`${name} runs its lifecycle: use its health`));\n let made: Runtime;\n try {\n made = makeRuntime(options).runtime;\n } catch (error) {\n return Promise.reject(error);\n }\n started = true;\n live = made;\n runtime = made.warmUp().then(() => made);\n return runtime;\n },\n run(options = {}) {\n if (running !== undefined) return running;\n if (runtime !== undefined) return Promise.reject(new Error(`${name} started its health only: run() starts the whole lifecycle`));\n try {\n const description = builder.describe();\n const components: Components = {\n transports: transportImpls,\n dependencies: handles,\n healthServer: probes,\n phaseWork,\n choices,\n stopPollers: () => {},\n };\n const problems = [...lifecycleProblems(description, components), ...uncaughtProblems(options.uncaught)];\n if (problems.length > 0) throw new Error(`${name}: ${problems.join(\"; \")}`);\n const made = makeRuntime(options);\n started = true;\n live = made.runtime;\n // the builder holds the lifecycle before the first transport starts\n const ran = lifecycle(made.description, made.runtime, { ...components, stopPollers: made.stopPollers }, made.options, (given) => {\n life = given;\n });\n running = ran.started.then(() => ran);\n } catch (error) {\n return Promise.reject(error);\n }\n return running;\n },\n };\n return builder;\n};\n"],"mappings":";;;;;;;;;;;;AAuJA,MAAM,UAAU,WAA4B,YAAY,OAAO,MAAM,GAAG;AACxE,MAAM,SAAS,WACb,OAAO,UAAU,cAAe,OAAO,MAAM,KAAK,QAAQ,QAAoB,GAAG,IAAI;AACvF,MAAM,SAAS,UAA2B,OAAO,UAAU,KAAK,KAAK,SAAS;;AAE9E,MAAM,aAAa,WAAyB;CAC1C,GAAG;CACH,MAAM,EAAE,GAAG,MAAM,KAAK;CACtB,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;EAAE,OAAO,CAAC,GAAG,MAAM,MAAM,KAAK;EAAG,OAAO,EAAE,GAAG,MAAM,MAAM,MAAM;CAAE,EAAE;AACnH;;AAEA,MAAM,iBAAiB,UAA2B;CAChD,MAAM,QAAQ,MAAM;CACpB,IAAI,UAAU,KAAA,GAAW,OAAO,CAAC;CACjC,MAAM,WAAqB,CAAC;CAC5B,IAAI,MAAM,SAAS,YACjB,SAAS,KAAK,SAAS,MAAM,KAAK,iDAAiD,MAAM,KAAK,eAAe;CAC/G,IAAI,MAAM,MAAM,WAAW,GAAG,SAAS,KAAK,SAAS,MAAM,KAAK,6BAA6B;CAE7F,IAAI,OAAO,MAAM,MAAM,UAAU,YAAY,CAAC,MAAM,MA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,OAAO,YAAY,OAAO,CAAC,CAAC;GAC9B,SAAS,OAAO;IACd,OAAO,QAAQ,OAAO,KAAK;GAC7B;GACA,UAAU;GACV,OAAO;GACP,UAAU,KAAK,OAAO,CAAC,CAAC,WAAW,IAAI;GACvC,OAAO;EACT;EACA,IAAI,UAAU,CAAC,GAAG;GAChB,IAAI,YAAY,KAAA,GAAW,OAAO;GAClC,IAAI,YAAY,KAAA,GAAW,OAAO,QAAQ,uBAAO,IAAI,MAAM,GAAG,KAAK,2DAA2D,CAAC;GAC/H,IAAI;IACF,MAAM,cAAc,QAAQ,SAAS;IACrC,MAAM,aAAyB;KAC7B,YAAY;KACZ,cAAc;KACd,cAAc;KACd;KACA;KACA,mBAAmB,CAAC;IACtB;IACA,MAAM,WAAW,CAAC,GAAG,kBAAkB,aAAa,UAAU,GAAG,GAAG,iBAAiB,QAAQ,QAAQ,CAAC;IACtG,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,IAAI,SAAS,KAAK,IAAI,GAAG;IAC1E,MAAM,OAAO,YAAY,OAAO;IAChC,UAAU;IACV,OAAO,KAAK;IAEZ,MAAM,MAAM,UAAU,KAAK,aAAa,KAAK,SAAS;KAAE,GAAG;KAAY,aAAa,KAAK;IAAY,GAAG,KAAK,UAAU,UAAU;KAC/H,OAAO;IACT,CAAC;IACD,UAAU,IAAI,QAAQ,WAAW,GAAG;GACtC,SAAS,OAAO;IACd,OAAO,QAAQ,OAAO,KAAK;GAC7B;GACA,OAAO;EACT;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"builder.js","names":[],"sources":["../src/builder.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, valueIn } from \"@mark1russell7/quantity\";\nimport type {\n Check,\n Controller,\n CooperativeFloor,\n Coupling,\n Dependency,\n ExitCodes,\n Gate,\n MessageTrigger,\n Phase,\n RepeatSignal,\n ServiceDescription,\n Transport,\n} from \"./description.ts\";\nimport { FORMAT } from \"./description.ts\";\nimport { realClock, unrefClock } from \"./clock.ts\";\nimport type { Health, Runtime, StartOptions } from \"./health.ts\";\nimport type { Limiter, LimiterSpec } from \"./limiter/policy.ts\";\nimport { limiterProblems } from \"./limiter/policy.ts\";\nimport { healthRuntime } from \"./health.ts\";\nimport { logEvents } from \"./logger.ts\";\nimport type {\n Components,\n DependencyHandle,\n HealthServer,\n Lifecycle,\n PhaseWork,\n RunOptions,\n TransportImpl,\n} from \"./lifecycle.ts\";\nimport { STAGES, lifecycle, lifecycleProblems, stageRank, uncaughtProblems } from \"./lifecycle.ts\";\nimport type { Operation } from \"./operation.ts\";\nimport { operationProblems } from \"./operation.ts\";\nimport type { CheckFn } from \"./poller.ts\";\nimport type { ExitTrigger, ProcessTrigger } from \"./process.ts\";\nimport { EXIT_SIGNALS, PROCESS_TRIGGERS, isExitCode, isExitSignal, isMessageShape } from \"./process.ts\";\nimport type { Profile } from \"./profiles.ts\";\nimport type { OperationOf, RoutePattern } from \"./routes.ts\";\nimport { routePatternProblems } from \"./routes.ts\";\nimport type { Timing } from \"./timing.ts\";\nimport type { Watchdog, WatchdogSpec } from \"./watchdog.ts\";\nimport { watchdog } from \"./watchdog.ts\";\n\n/**\n * The caller composes a service with plain method uses before it starts. The builder is imperative, and\n * it holds static knowledge. The service does not use an `init` function that gives registrations.\n *\n * const svc = service(\"app\");\n * svc.dependency(\"weather\", {\n * system: null,\n * knobs: { request_timeout },\n * operations: { \"GET /v1/forecast\": { idempotent: true } },\n * });\n * svc.controller(\"forecast\").requires(\"weather\").route(\"GET /api/forecast\", { idempotent: true });\n * svc.check({ name: \"weather.round-trip\", dependency: \"weather\", … }, roundTrip);\n * svc.describe(); // the whole graph as data, with nothing started\n * const health = await svc.start();\n *\n * The graph has one source, thus its parts cannot disagree. A dependency or a check can join\n * after the start. It starts tripped, and the export is partial. The runtime has no defaults of\n * its own. Thus `describe()` refuses a service that does not declare a policy, its startup budget\n * or its shutdown, and it tells which. The shutdown includes what a repeat signal does.\n *\n * `start()` starts only the health runtime. `run()` starts the whole lifecycle: the startup in its\n * sequence, the exit signals, the capped phases of the shutdown, and the exit of the process.\n */\nexport interface ControllerBuilder {\n /** This method declares the dependencies that its routes need. The controller is ready only while they are ready. */\n requires(...dependencies: string[]): ControllerBuilder;\n /** This method declares a route that the controller serves, and if its callers can send it again. */\n route(route: string, operation: Operation): ControllerBuilder;\n /**\n * This method declares a route pattern, the operations that its requests can be, and the function\n * that picks the operation of each request. A pattern with one operation needs no function.\n */\n pattern(pattern: string, operations: Readonly<Record<string, Operation>>, operationOf?: OperationOf): ControllerBuilder;\n}\n\n/** A service builder composes a service, gives it as data, and starts it. */\nexport interface ServiceBuilder {\n readonly name: string;\n /** This method declares a dependency, and the handle that connects to it and closes it, if it has one. */\n dependency(name: string, spec: Omit<Dependency, \"name\">, handle?: DependencyHandle): ServiceBuilder;\n /** This method declares a server, and its implementation. `run()` needs the implementation. */\n server(name: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl): ServiceBuilder;\n consumer(name: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl): ServiceBuilder;\n worker(name: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl): ServiceBuilder;\n /** This method gives the server of the probes. It starts first and closes last. */\n healthServer(server: HealthServer): ServiceBuilder;\n /** This method adds work to a declared phase of the shutdown: the owner of the work registers it. */\n onPhase(phase: string, work: PhaseWork): ServiceBuilder;\n /** This method declares a watchdog of the event loop, as a check on the state of the process. */\n watchdog(spec: WatchdogSpec): ServiceBuilder;\n controller(name: string): ControllerBuilder;\n /** This method declares a check, and the function that measures its step. `start()` needs the function. */\n check(check: Check, run?: CheckFn): ServiceBuilder;\n /**\n * This method declares a keyed limiter as data: its key, its policy, its store and the bound on its\n * keys. `describe()` shows it and refuses a part that is absent, because a limiter has no defaults.\n * `keyedLimiter(name, spec, store)` makes its runtime from the same spec.\n */\n limiter(name: string, spec: LimiterSpec): ServiceBuilder;\n readiness(timing: Timing): ServiceBuilder;\n liveness(timing: Timing): ServiceBuilder;\n startup(budget: Quantity): ServiceBuilder;\n couple(coupling: Coupling): ServiceBuilder;\n phase(name: string, cap: Quantity): ServiceBuilder;\n cooperativeWindow(window: Extent): ServiceBuilder;\n /** This method declares the earliest time of the cooperative abort: half the cap of the drain, or no floor. */\n cooperativeFloor(floor: CooperativeFloor): ServiceBuilder;\n /** This method declares what an exit signal does while the shutdown runs: nothing, or an exit at once. */\n onRepeatSignal(policy: RepeatSignal): ServiceBuilder;\n /** This method declares process triggers that start the shutdown, in addition to the exit signals. */\n trigger(...triggers: ProcessTrigger[]): ServiceBuilder;\n /**\n * This method declares a message of the IPC channel that starts the shutdown, as data. With `as`,\n * the message is that exit signal: `svc.trigger(\"ipc-message\", { match: \"shutdown\", as: \"SIGTERM\" })`.\n */\n trigger(trigger: \"ipc-message\", message: MessageTrigger): ServiceBuilder;\n /** This method declares the exit code of a clean shutdown that a trigger starts, in place of 0. */\n exitCode(trigger: ExitTrigger, code: number): ServiceBuilder;\n /** This method declares each field of a profile, as the method of that field does. */\n profile(profile: Profile): ServiceBuilder;\n /** This method gives the service as data, and it starts nothing. */\n describe(): ServiceDescription;\n /**\n * This method closes the composition, starts the health runtime, and gives it after one warm-up\n * sweep of each check. A part that joins after it starts tripped, and it makes the export\n * partial. A second use gives the same runtime.\n */\n start(options?: StartOptions): Promise<Health>;\n /**\n * This method starts the whole lifecycle and gives it when its startup ends: the service operates,\n * or its startup failed and it shuts down. It refuses a declaration that it cannot start: a transport\n * without its implementation, or a stage with work and no declared phase.\n */\n run(options?: RunOptions): Promise<Lifecycle>;\n /**\n * This value is the health runtime from the time that `start()` begins, or null before. Thus the\n * probes can answer during the warm-up sweep: the startup probe fails until the sweep ends.\n */\n readonly health: Health | null;\n /**\n * This value is the lifecycle from the time that `run()` begins, or null before. Its request\n * tracking operates while the transports start, before `run()` gives it.\n */\n readonly lifecycle: Lifecycle | null;\n}\n\nconst isTime = (amount: Extent): boolean => convertible(amount.unit, \"s\");\nconst above = (amount: Extent): boolean =>\n amount.value === \"infinite\" || (isTime(amount) && valueIn(amount as Quantity, \"s\") > 0);\nconst whole = (count: number): boolean => Number.isInteger(count) && count >= 1;\n/** This function copies a check, with its poll and the loops that mark it. */\nconst copyCheck = (check: Check): Check => ({\n ...check,\n poll: { ...check.poll },\n ...(check.marks === undefined ? {} : { marks: { loops: [...check.marks.loops], stall: { ...check.marks.stall } } }),\n});\n/** This function gives the problems of the loops that mark a check. `lint()` compares the stall time with the loops. */\nconst marksProblems = (check: Check): string[] => {\n const marks = check.marks;\n if (marks === undefined) return [];\n const problems: string[] = [];\n if (check.step !== \"progress\")\n problems.push(`check ${check.name} names the loops that mark it, but its step is ${check.step}, not progress`);\n if (marks.loops.length === 0) problems.push(`check ${check.name} names no loop that marks it`);\n // a description from JSON can give a stall time without a bound, which is not a stall time\n if (typeof marks.stall.value !== \"number\" || !above(marks.stall))\n problems.push(`check ${check.name} has a stall time that is not a time above zero`);\n return problems;\n};\n\n/** This function gives the problems of a timing: a zero interval or count fails decoding. */\nconst timingProblems = (policy: Gate, timing: Timing): string[] => {\n if (timing.type === \"debounce\") {\n const problems: string[] = [];\n if (!above(timing.interval)) problems.push(`the ${policy} debounce polls at an interval that is not above zero`);\n if (!whole(timing.failAfter)) problems.push(`the ${policy} debounce fails after ${timing.failAfter} polls, not a whole number above zero`);\n if (!whole(timing.recoverAfter)) problems.push(`the ${policy} debounce recovers after ${timing.recoverAfter} polls, not a whole number above zero`);\n return problems;\n }\n const negative = (amount: Quantity | undefined): boolean =>\n amount !== undefined && (!isTime(amount) || valueIn(amount, \"s\") < 0);\n return negative(timing.failAfter) || negative(timing.recoverAfter)\n ? [`the ${policy} window is not a time of zero or more`]\n : [];\n};\n\n/** This function gives the problems of the rules of the shutdown: an unknown name, or an exit code that a process cannot give. */\nconst shutdownProblems = (\n floor: CooperativeFloor | undefined,\n repeat: RepeatSignal | undefined,\n triggers: readonly ProcessTrigger[],\n exitCodes: ExitCodes,\n messages: readonly MessageTrigger[],\n): string[] => {\n const problems: string[] = [];\n if (floor !== undefined && floor !== \"half\" && floor !== \"none\")\n problems.push(`the cooperative floor ${String(floor)} is not \"half\" or \"none\"`);\n if (repeat !== undefined && repeat !== \"ignore\" && repeat !== \"exit\")\n problems.push(`the policy of a repeat signal ${String(repeat)} is not \"ignore\" or \"exit\"`);\n for (const trigger of triggers)\n if (!PROCESS_TRIGGERS.includes(trigger))\n problems.push(`the trigger ${String(trigger)} is not a process trigger (${PROCESS_TRIGGERS.join(\", \")})`);\n if (triggers.includes(\"ipc-message\") && messages.length === 0)\n problems.push(`the trigger ipc-message has no message to match: declare it with svc.trigger(\"ipc-message\", { match })`);\n for (const message of messages) {\n if (!isMessageShape(message.match))\n problems.push(`the match of a message trigger is not a value of JSON: ${String(message.match)}`);\n if (message.as !== undefined && !isExitSignal(message.as))\n problems.push(`a message trigger stands for ${String(message.as)}, not an exit signal (${EXIT_SIGNALS.join(\", \")})`);\n }\n for (const [trigger, code] of Object.entries(exitCodes)) {\n const known = (EXIT_SIGNALS as readonly string[]).includes(trigger) || triggers.includes(trigger as ProcessTrigger);\n if (!known) problems.push(`the exit code of ${trigger} names no exit signal and no declared trigger`);\n if (code === undefined || !isExitCode(code))\n problems.push(`the exit code of ${trigger} is ${String(code)}, not a whole number from 0 to 255`);\n }\n return problems;\n};\n\n/**\n * This function gives the options with one recorder for the recorder and the logger of the options.\n * Without a logger, it gives the same options.\n */\nconst withLogger = <O extends StartOptions>(options: O, description: ServiceDescription): O => {\n if (options.logger === undefined) return options;\n const given = options.record;\n const log = logEvents(options.logger, description);\n return {\n ...options,\n record: (event) => {\n given?.(event);\n log(event);\n },\n };\n};\n\n/** This function starts the composition of a service. */\nexport const service = (name: string): ServiceBuilder => {\n if (name.trim().length === 0) throw new Error(\"a service needs a name\");\n const transports: Transport[] = [];\n const dependencies: Dependency[] = [];\n const controllers: Array<{\n name: string;\n requires: string[];\n routes: Record<string, Operation>;\n patterns: RoutePattern[];\n }> = [];\n // the function of each route pattern, by controller and by pattern\n const choices = new Map<string, Map<string, OperationOf>>();\n const checks: Check[] = [];\n const runs = new Map<string, CheckFn>();\n const limiters: Limiter[] = [];\n const couplings: Coupling[] = [];\n const phases: Phase[] = [];\n let readiness: Timing | undefined;\n let liveness: Timing | undefined;\n let startup: Quantity | undefined;\n let cooperative: Extent | undefined;\n let floor: CooperativeFloor | undefined;\n let repeat: RepeatSignal | undefined;\n const triggers: ProcessTrigger[] = [];\n const messages: MessageTrigger[] = [];\n const exitCodes: Partial<Record<ExitTrigger, number>> = {};\n let started = false;\n let partial = false;\n let runtime: Promise<Health> | undefined;\n let live: Runtime | undefined;\n let running: Promise<Lifecycle> | undefined;\n let life: Lifecycle | undefined;\n const transportImpls = new Map<string, TransportImpl>();\n const handles = new Map<string, DependencyHandle>();\n const phaseWork = new Map<string, PhaseWork[]>();\n const watchdogs: WatchdogSpec[] = [];\n let probes: HealthServer | null = null;\n\n /** This function stops a change to the shape of the service after the start. */\n const composing = (what: string): void => {\n if (started) throw new Error(`${name} has started: ${what} is declared before svc.start()`);\n };\n const once = (list: ReadonlyArray<{ name: string }>, entry: string, what: string): void => {\n if (list.some((held) => held.name === entry))\n throw new Error(`${name} already has a ${what} named ${entry}`);\n };\n const transport =\n (kind: Transport[\"kind\"]) =>\n (entry: string, knobs: Readonly<Record<string, Extent>>, impl?: TransportImpl) => {\n composing(`a ${kind}`);\n once(transports, entry, \"transport\");\n transports.push({ name: entry, kind, knobs: { ...knobs } });\n if (impl !== undefined) transportImpls.set(entry, impl);\n return builder;\n };\n\n /** This function makes the runtime of the declaration: its checks, and a watchdog for each spec. */\n const makeRuntime = <O extends StartOptions>(\n given: O,\n ): { runtime: Runtime; description: ServiceDescription; stopPollers: () => void; options: O } => {\n const description = builder.describe();\n // the logger is one sink of the stream of the recorder: each machine writes to both\n const options = withLogger(given, description);\n const clock = options.clock ?? realClock;\n const dogs: Watchdog[] = [];\n const all = new Map(runs);\n for (const spec of watchdogs) {\n // the tick only watches the event loop: the work of the service keeps the process alive (SYS-126)\n const dog = watchdog(unrefClock(clock), spec, (from, to, on) =>\n options.record?.({ at: clock.now(), machine: \"watchdog\", instance: spec.name, from, to, on }),\n );\n dogs.push(dog);\n all.set(spec.name, () => dog.check());\n }\n const stopPollers = (): void => {\n for (const dog of dogs) dog.stop();\n };\n let made: Runtime;\n try {\n made = healthRuntime(description, all, options);\n } catch (error) {\n stopPollers();\n throw error;\n }\n // the stop of the health runtime also stops the watchdogs\n const runtime: Runtime = {\n ...made,\n stop: () => {\n made.stop();\n stopPollers();\n },\n };\n return { runtime, description, stopPollers, options };\n };\n\n const builder: ServiceBuilder = {\n name,\n get health() {\n return live ?? null;\n },\n get lifecycle() {\n return life ?? null;\n },\n dependency(entry, spec, handle) {\n once(dependencies, entry, \"dependency\");\n // a dependency that joins after the start has no connection that the lifecycle opens\n if (handle !== undefined && !started) handles.set(entry, handle);\n dependencies.push({\n name: entry,\n ...spec,\n knobs: { ...spec.knobs },\n operations: { ...spec.operations },\n });\n if (started) {\n partial = true;\n live?.addDependency(entry);\n }\n return builder;\n },\n server: transport(\"server\"),\n consumer: transport(\"consumer\"),\n worker: transport(\"worker\"),\n controller(entry) {\n composing(\"a controller\");\n once(controllers, entry, \"controller\");\n const held = {\n name: entry,\n requires: [] as string[],\n routes: {} as Record<string, Operation>,\n patterns: [] as RoutePattern[],\n };\n controllers.push(held);\n const handle: ControllerBuilder = {\n requires(...needed) {\n composing(`what ${entry} requires`);\n held.requires.push(...needed);\n return handle;\n },\n route(served, operation) {\n composing(`${entry}'s routes`);\n if (held.routes[served] !== undefined)\n throw new Error(`${entry} already serves ${served}`);\n held.routes[served] = { ...operation };\n return handle;\n },\n pattern(pattern, operations, operationOf) {\n composing(`${entry}'s route patterns`);\n if (held.patterns.some((each) => each.pattern === pattern))\n throw new Error(`${entry} already has the route pattern ${pattern}`);\n // the function is not data, thus the builder checks it here, and describe() checks the rest\n if (operationOf === undefined && Object.keys(operations).length > 1)\n throw new Error(`${entry}'s pattern ${pattern} has ${Object.keys(operations).length} operations, thus it needs the function that picks one`);\n held.patterns.push({\n pattern,\n operations: Object.fromEntries(Object.entries(operations).map(([name, operation]) => [name, { ...operation }])),\n });\n if (operationOf !== undefined) {\n const mine = choices.get(entry) ?? new Map<string, OperationOf>();\n mine.set(pattern, operationOf);\n choices.set(entry, mine);\n }\n return handle;\n },\n };\n return handle;\n },\n check(check, run) {\n once(checks, check.name, \"check\");\n if (started && run === undefined)\n throw new Error(`check ${check.name} joins after the start, thus it needs its function`);\n checks.push(copyCheck(check));\n if (run !== undefined) runs.set(check.name, run);\n if (started) {\n partial = true;\n live?.addCheck(copyCheck(check), run!);\n }\n return builder;\n },\n limiter(entry, spec) {\n composing(`the limiter ${entry}`);\n once(limiters, entry, \"limiter\");\n // the spec is data: the builder keeps a copy, and describe() checks each part\n const given = (spec ?? {}) as Partial<LimiterSpec>;\n limiters.push({\n name: entry,\n ...given,\n ...(given.policy === undefined ? {} : { policy: { ...given.policy } }),\n ...(given.store === undefined ? {} : { store: { ...given.store } }),\n ...(given.evict === undefined ? {} : { evict: { ...given.evict } }),\n } as Limiter);\n return builder;\n },\n healthServer(server) {\n composing(\"the health server\");\n if (probes !== null) throw new Error(`${name} already has a health server`);\n probes = server;\n return builder;\n },\n onPhase(phase, work) {\n composing(`work for the phase ${phase}`);\n phaseWork.set(phase, [...(phaseWork.get(phase) ?? []), work]);\n return builder;\n },\n watchdog(spec) {\n composing(`the watchdog ${spec.name}`);\n once(checks, spec.name, \"check\");\n // the watchdog is a check on the state of the process itself, on its own connection\n checks.push({\n name: spec.name,\n dependency: null,\n step: \"local-state\",\n ownConnection: true,\n gates: spec.gates,\n poll: { ...spec.poll },\n });\n watchdogs.push(spec);\n return builder;\n },\n readiness(timing) {\n composing(\"readiness\");\n readiness = timing;\n return builder;\n },\n liveness(timing) {\n composing(\"liveness\");\n liveness = timing;\n return builder;\n },\n startup(budget) {\n composing(\"the startup budget\");\n startup = budget;\n return builder;\n },\n couple(coupling) {\n composing(\"a coupling\");\n couplings.push({ ...coupling });\n return builder;\n },\n phase(entry, cap) {\n composing(\"a shutdown phase\");\n once(phases, entry, \"shutdown phase\");\n phases.push({ name: entry, cap });\n return builder;\n },\n cooperativeWindow(window) {\n composing(\"the cooperative window\");\n cooperative = window;\n return builder;\n },\n cooperativeFloor(given) {\n composing(\"the cooperative floor\");\n floor = given;\n return builder;\n },\n onRepeatSignal(policy) {\n composing(\"the policy of a repeat signal\");\n repeat = policy;\n return builder;\n },\n trigger(...given: ReadonlyArray<ProcessTrigger | MessageTrigger>) {\n composing(\"a trigger\");\n const [first, message] = given;\n if (first === \"ipc-message\" && typeof message === \"object\" && message !== null) {\n if (!triggers.includes(\"ipc-message\")) triggers.push(\"ipc-message\");\n messages.push({ ...message });\n return builder;\n }\n for (const each of given) if (typeof each === \"string\" && !triggers.includes(each)) triggers.push(each);\n return builder;\n },\n exitCode(trigger, code) {\n composing(`the exit code of ${trigger}`);\n exitCodes[trigger] = code;\n return builder;\n },\n profile(given) {\n composing(\"a profile\");\n if (given.readiness !== undefined) builder.readiness(given.readiness);\n if (given.liveness !== undefined) builder.liveness(given.liveness);\n if (given.startup !== undefined) builder.startup(given.startup);\n for (const coupling of given.couplings ?? []) builder.couple(coupling);\n for (const each of given.phases ?? []) builder.phase(each.name, each.cap);\n if (given.cooperativeWindow !== undefined) builder.cooperativeWindow(given.cooperativeWindow);\n if (given.cooperativeFloor !== undefined) builder.cooperativeFloor(given.cooperativeFloor);\n if (given.onRepeatSignal !== undefined) builder.onRepeatSignal(given.onRepeatSignal);\n if (given.triggers !== undefined) builder.trigger(...given.triggers);\n for (const message of given.messages ?? []) builder.trigger(\"ipc-message\", message);\n for (const [trigger, code] of Object.entries(given.exitCodes ?? {}))\n if (code !== undefined) builder.exitCode(trigger as ExitTrigger, code);\n return builder;\n },\n describe() {\n const missing: string[] = [];\n if (readiness === undefined) missing.push(\"readiness (svc.readiness)\");\n if (liveness === undefined) missing.push(\"liveness (svc.liveness)\");\n if (startup === undefined) missing.push(\"a startup budget (svc.startup)\");\n if (phases.length === 0) missing.push(\"its shutdown phases (svc.phase)\");\n if (cooperative === undefined)\n missing.push(\"a cooperative window, or no bound (svc.cooperativeWindow)\");\n if (repeat === undefined)\n missing.push(`what a repeat signal does, \"ignore\" or \"exit\" (svc.onRepeatSignal)`);\n if (missing.length > 0)\n throw new Error(\n `${name} does not declare ${missing.join(\"; \")}: the runtime has no defaults`,\n );\n const known = new Set(dependencies.map((entry) => entry.name));\n const problems: string[] = [];\n const policies: Record<Gate, Timing> = { readiness: readiness!, liveness: liveness! };\n for (const gate of [\"readiness\", \"liveness\"] as const)\n problems.push(...timingProblems(gate, policies[gate]));\n for (const check of checks) {\n if (check.dependency !== null && !known.has(check.dependency)) {\n problems.push(\n `check ${check.name} exercises ${check.dependency}, which is not a dependency`,\n );\n }\n if (!isTime(check.poll.interval) || !isTime(check.poll.timeout)) {\n problems.push(`check ${check.name} polls in a unit that is not a time`);\n } else if (!above(check.poll.interval) || !above(check.poll.timeout)) {\n problems.push(`check ${check.name} polls with an interval or a timeout that is not above zero`);\n }\n if (!(check.poll.jitter >= 0 && check.poll.jitter < 1))\n problems.push(`check ${check.name} has a jitter of ${check.poll.jitter}, not a fraction below 1`);\n problems.push(...marksProblems(check));\n // a debounce counts the polls of each check that it gates, thus they poll at its interval\n const timing = check.gates === null ? null : policies[check.gates];\n if (\n timing?.type === \"debounce\" &&\n isTime(check.poll.interval) &&\n above(timing.interval) &&\n valueIn(check.poll.interval, \"s\") !== valueIn(timing.interval, \"s\")\n )\n problems.push(\n `check ${check.name} polls every ${valueIn(check.poll.interval, \"s\")} s, but the ${check.gates} debounce counts polls every ${valueIn(timing.interval, \"s\")} s`,\n );\n }\n for (const controller of controllers) {\n for (const needed of controller.requires) {\n if (!known.has(needed))\n problems.push(\n `controller ${controller.name} requires ${needed}, which is not a dependency`,\n );\n }\n for (const [route, operation] of Object.entries(controller.routes))\n problems.push(...operationProblems(`controller ${controller.name}`, route, operation));\n for (const declared of controller.patterns)\n problems.push(...routePatternProblems(`controller ${controller.name}`, declared));\n }\n for (const limiter of limiters) {\n const { name: entry, ...spec } = limiter;\n problems.push(...limiterProblems(entry, spec));\n if (limiter.store?.kind === \"shared\" && typeof limiter.store.dependency === \"string\" && !known.has(limiter.store.dependency))\n problems.push(`limiter ${entry} keeps its counts in ${limiter.store.dependency}, which is not a dependency`);\n }\n for (const dependency of dependencies)\n for (const [name, operation] of Object.entries(dependency.operations))\n problems.push(...operationProblems(`dependency ${dependency.name}`, name, operation));\n for (const phase of phases)\n if (!isTime(phase.cap)) problems.push(`phase ${phase.name}'s cap is not a time`);\n problems.push(...shutdownProblems(floor, repeat, triggers, exitCodes, messages));\n // the stages of the shutdown keep their sequence: readiness fails first, the health server closes last\n const ranked = phases.map((phase) => phase.name).filter((each) => stageRank(each) >= 0);\n for (let at = 1; at < ranked.length; at += 1)\n if (stageRank(ranked[at]!) < stageRank(ranked[at - 1]!))\n problems.push(\n `the phase \"${ranked[at]!}\" comes after \"${ranked[at - 1]!}\", but the stages go ${STAGES.join(\", \")}`,\n );\n if (problems.length > 0) throw new Error(`${name}: ${problems.join(\"; \")}`);\n const controllersOut: Controller[] = controllers.map((entry) => ({\n name: entry.name,\n requires: [...entry.requires],\n routes: { ...entry.routes },\n ...(entry.patterns.length === 0\n ? {}\n : { patterns: entry.patterns.map((each) => ({ pattern: each.pattern, operations: { ...each.operations } })) }),\n }));\n return {\n format: FORMAT,\n name,\n partial,\n transports: transports.map((entry) => ({ ...entry, knobs: { ...entry.knobs } })),\n dependencies: dependencies.map((entry) => ({\n ...entry,\n knobs: { ...entry.knobs },\n operations: { ...entry.operations },\n })),\n controllers: controllersOut,\n checks: checks.map(copyCheck),\n ...(limiters.length === 0\n ? {}\n : {\n limiters: limiters.map((entry) => ({\n ...entry,\n policy: { ...entry.policy },\n store: { ...entry.store },\n evict: { maxKeys: { ...entry.evict.maxKeys } },\n })),\n }),\n policies: { readiness: readiness!, liveness: liveness!, startup: startup! },\n couplings: couplings.map((entry) => ({ ...entry })),\n shutdown: {\n phases: phases.map((entry) => ({ ...entry })),\n cooperativeWindow: cooperative!,\n ...(floor === undefined ? {} : { cooperativeFloor: floor }),\n onRepeatSignal: repeat!,\n ...(triggers.length === 0 ? {} : { triggers: [...triggers] }),\n ...(messages.length === 0 ? {} : { messages: messages.map((each) => ({ ...each })) }),\n ...(Object.keys(exitCodes).length === 0 ? {} : { exitCodes: { ...exitCodes } }),\n },\n };\n },\n start(options = {}) {\n // the start needs the whole graph: describe() is the check, and the runtime reads it\n if (runtime !== undefined) return runtime;\n if (running !== undefined) return Promise.reject(new Error(`${name} runs its lifecycle: use its health`));\n let made: Runtime;\n try {\n made = makeRuntime(options).runtime;\n } catch (error) {\n return Promise.reject(error);\n }\n started = true;\n live = made;\n runtime = made.warmUp().then(() => made);\n return runtime;\n },\n run(options = {}) {\n if (running !== undefined) return running;\n if (runtime !== undefined) return Promise.reject(new Error(`${name} started its health only: run() starts the whole lifecycle`));\n try {\n const description = builder.describe();\n const components: Components = {\n transports: transportImpls,\n dependencies: handles,\n healthServer: probes,\n phaseWork,\n choices,\n stopPollers: () => {},\n };\n const problems = [...lifecycleProblems(description, components), ...uncaughtProblems(options.uncaught)];\n if (problems.length > 0) throw new Error(`${name}: ${problems.join(\"; \")}`);\n const made = makeRuntime(options);\n started = true;\n live = made.runtime;\n // the builder holds the lifecycle before the first transport starts\n const ran = lifecycle(made.description, made.runtime, { ...components, stopPollers: made.stopPollers }, made.options, (given) => {\n life = given;\n });\n running = ran.started.then(() => ran);\n } catch (error) {\n return Promise.reject(error);\n }\n return running;\n },\n };\n return builder;\n};\n"],"mappings":";;;;;;;;;;;;AAuJA,MAAM,UAAU,WAA4B,YAAY,OAAO,MAAM,GAAG;AACxE,MAAM,SAAS,WACb,OAAO,UAAU,cAAe,OAAO,MAAM,KAAK,QAAQ,QAAoB,GAAG,IAAI;AACvF,MAAM,SAAS,UAA2B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K,IAAI,SAAS,KAAK,IAAI,GAAG;IAC1E,MAAM,OAAO,YAAY,OAAO;IAChC,UAAU;IACV,OAAO,KAAK;IAEZ,MAAM,MAAM,UAAU,KAAK,aAAa,KAAK,SAAS;KAAE,GAAG;KAAY,aAAa,KAAK;IAAY,GAAG,KAAK,UAAU,UAAU;KAC/H,OAAO;IACT,CAAC;IACD,UAAU,IAAI,QAAQ,WAAW,GAAG;GACtC,SAAS,OAAO;IACd,OAAO,QAAQ,OAAO,KAAK;GAC7B;GACA,OAAO;EACT;CACF;CACA,OAAO;AACT"}
|
package/build/channel.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel.js","names":[],"sources":["../src/channel.ts"],"sourcesContent":["// @mark1russell7/service/channel: channels in the style of Go, on the clock of the service. It\n// imports only ./clock.ts and @mark1russell7/collections: no `node:` module and no zod. Thus a\n// client in a browser can use it, as it uses ./clock.\n//\n// The code came from @mark1russell7/collections 0.7 (the review of its API, C12, S2). The changes:\n// `timeout` and `ticker` take a clock, `ticker` does not drift, the functions that start work give\n// each failure to `onError` and write nothing to the console, and `fanIn` and `merge` take an array.\n\nimport { asyncQueue, type AsyncQueue } from \"@mark1russell7/collections\";\nimport { realClock, type Cancel, type Clock } from \"./clock.ts\";\n\n/** This function gets a failure of the work that a function of this entry started. */\nexport type ErrorHandler = (error: unknown) => void;\n\n/** These options are for a function that starts work and gives an output channel. */\nexport interface FlowOptions {\n /** The size of the buffer of each output channel. The default is 0: a send waits for a receiver. */\n readonly bufferSize?: number | undefined;\n /**\n * This function gets each failure of the work. The output closes after a failure. Without it,\n * the failure is lost, but the output also closes.\n */\n readonly onError?: ErrorHandler | undefined;\n}\n\n/**\n * A channel carries values from senders to receivers, as a channel of Go does. A channel with a\n * buffer of 0 is a rendezvous: each send waits for a receiver.\n */\nexport class Channel<T> {\n private readonly queue: AsyncQueue<T>;\n private closed = false;\n\n /** This constructor makes a channel with a buffer of `bufferSize` values. The default is 0. */\n constructor(bufferSize = 0) {\n // A buffer of 0 makes a send wait for a receiver (before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17)\n this.queue = asyncQueue<T>({ capacity: bufferSize });\n }\n\n /**\n * This method sends a value. It waits while the buffer is full and no receiver waits.\n *\n * @throws Error when the channel is closed.\n */\n async send(value: T): Promise<void> {\n if (this.closed) throw new Error(\"Cannot send on closed channel\");\n await this.queue.put(value);\n }\n\n /**\n * This method receives a value. It waits while the channel has no value.\n *\n * @throws Error when the channel is closed and empty.\n */\n async receive(): Promise<T> {\n return await this.queue.take();\n }\n\n /**\n * This method waits for one value, as `receive` does, and gives it to `onValue`. When the\n * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in\n * the call that sends the value or closes the channel.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no value yet.\n */\n waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {\n return this.queue.waitTake(onValue, onClosed);\n }\n\n /** This method sends a value if a receiver or the buffer takes it at once. It gives false when not. */\n trySend(value: T): boolean {\n if (this.closed) return false;\n return this.queue.tryPut(value);\n }\n\n /** This method receives a value if the channel has one at once. It gives undefined when not. */\n tryReceive(): T | undefined {\n return this.queue.tryTake();\n }\n\n /** This method closes the channel. A send then fails, but a receiver can take the values that stay. */\n close(): void {\n this.closed = true;\n this.queue.close();\n }\n\n /** This value is true after `close`. */\n get isClosed(): boolean {\n return this.closed;\n }\n\n /** This value is the count of values in the buffer. */\n get size(): number {\n return this.queue.size;\n }\n\n /** This method makes a case of `select` for this channel. `handler` gets the value of the case. */\n case<R>(handler: (value: T) => R): SelectCase<R> {\n return {\n // The value of each call comes from this channel, so it has the type T\n handler: (value) => handler(value as T),\n wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),\n };\n }\n\n /** This iteration receives each value. It stops when the channel is closed and empty. */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n let value: T;\n try {\n value = await this.receive();\n } catch {\n // The channel is closed and empty\n return;\n }\n yield value;\n }\n }\n}\n\n/** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */\nexport type Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;\n\n/** A case of `select`: a wait for one value, and the function that gets the value. `Channel.case` makes one. */\nexport interface SelectCase<R> {\n /** This function gets the value of the case, when the case wins. */\n readonly handler: (value: unknown) => R;\n /** This function waits for one value of the case. `select` withdraws it when another case wins. */\n readonly wait: Wait;\n}\n\n/**\n * This function gives the first value of the waits, with the index of its wait. It rejects with\n * the error of the first wait whose channel is closed and empty. It withdraws each other wait in\n * the same call, so a later value stays in its channel (before, the receives of the cases that\n * lost stayed in their channels and dropped the next value of each: audit O56).\n */\nconst firstOf = (waits: readonly Wait[]): Promise<{ index: number; value: unknown }> =>\n new Promise((resolve, reject) => {\n const withdraws: Array<() => boolean> = [];\n let settled = false;\n const end = (): void => {\n settled = true;\n for (const withdraw of withdraws) withdraw();\n };\n // A wait can call back at once, in its own call, when its channel has a value or is closed\n try {\n for (let index = 0; index < waits.length && !settled; index++) {\n withdraws.push(\n waits[index]!(\n (value) => {\n if (settled) return;\n end();\n resolve({ index, value });\n },\n (error) => {\n if (settled) return;\n end();\n reject(error);\n },\n ),\n );\n }\n } catch (error) {\n // A wait that throws: the waits before it are withdrawn\n if (!settled) end();\n reject(error);\n }\n });\n\n/**\n * This function waits for the first case with a value, as the `select` of Go does, and gives the\n * result of its handler. A case that loses keeps no receive: a later value stays in its channel.\n * When the channel of a case is closed and empty, the promise rejects.\n *\n * @example\n * const result = await select(data.case((v) => `data ${v}`), timeout(1000).case(() => \"late\"));\n */\nexport const select = async <R>(...cases: readonly SelectCase<R>[]): Promise<R> => {\n const { index, value } = await firstOf(cases.map((c) => c.wait));\n // The handler runs after the race, not in the call of the sender\n return cases[index]!.handler(value);\n};\n\n/**\n * This function makes a channel that gets one value after `ms` milliseconds of `clock`, and then\n * closes. A case of it in `select` is a time limit.\n */\nexport const timeout = (ms: number, clock: Clock = realClock): Channel<void> => {\n const ch = new Channel<void>();\n clock.after(ms, () => {\n // The value waits for a receiver. The close lets the receivers after it fail at once.\n ch.send(undefined).catch(() => undefined);\n ch.close();\n });\n return ch;\n};\n\n/**\n * This error is the reason of the signal of a work that `within` stopped at its time limit. A\n * caller tells it from a failure of the work with `instanceof`.\n */\nexport class LateError extends Error {\n override readonly name = \"LateError\";\n}\n\n/**\n * The result of `within`: the value of the work, an end at the time limit, or the failure of the\n * work. The field `late` tells the two failures apart.\n */\nexport type Within<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly late: true }\n | { readonly ok: false; readonly late: false; readonly error: unknown };\n\n/** A work for `within`: a promise, or a function that gets the signal of the time limit. */\nexport type WithinWork<T> = PromiseLike<T> | ((signal: AbortSignal) => PromiseLike<T> | T);\n\n/**\n * This function gives the result of `work` when the work ends within `ms` milliseconds of `clock`.\n * Else it gives `{ ok: false, late: true }` at the time limit, and it aborts the signal of the work\n * with a `LateError`. The promise does not reject: a failure of the work is a result.\n *\n * The work starts before the timer. Thus a work whose own timer on `clock` ends at the time limit\n * is in time. The end of the work stops the timer, so a finished work keeps no timer. A function\n * that throws starts no timer. A failure of the work after the time limit is caught and dropped.\n * Give the work as a function to get the signal: a promise that started before the call cannot get it.\n *\n * @example\n * const result = await within((signal) => fetch(url, { signal }), 5000, clock);\n * if (result.ok) use(result.value);\n * else if (result.late) report(\"late\");\n * else report(result.error);\n */\nexport const within = <T>(work: WithinWork<T>, ms: number, clock: Clock = realClock): Promise<Within<T>> => {\n if (!(Number.isFinite(ms) && ms >= 0)) throw new RangeError(`The time limit of within is a finite number of 0 or more, not ${ms}`);\n const controller = new AbortController();\n let started: PromiseLike<T> | T;\n try {\n started = typeof work === \"function\" ? work(controller.signal) : work;\n } catch (error) {\n return Promise.resolve({ ok: false, late: false, error });\n }\n return new Promise<Within<T>>((resolve) => {\n let done = false;\n const cancel = clock.after(ms, () => {\n if (done) return;\n done = true;\n resolve({ ok: false, late: true });\n controller.abort(new LateError(`The work did not end within ${ms} ms`));\n });\n const end = (result: Within<T>): void => {\n if (done) return;\n done = true;\n cancel();\n resolve(result);\n };\n // The handlers also catch a failure after the time limit: it is not an unhandled rejection\n Promise.resolve(started).then(\n (value) => end({ ok: true, value }),\n (error: unknown) => end({ ok: false, late: false, error }),\n );\n });\n};\n\n/** A ticker is a channel of the numbers of its ticks. `stop` stops its timer and closes it. */\nexport type Ticker = Channel<number> & { readonly stop: () => void };\n\n/**\n * This function makes a channel that gets a tick each `ms` milliseconds of `clock`. Tick k (from 0)\n * comes due at start + (k + 1) * ms, so the ticks do not drift. A late timer gives the number of\n * the last tick that came due, and skips the ticks that it missed. The buffer has 1 value: a slow\n * receiver loses ticks, as with the ticker of Go.\n */\nexport const ticker = (ms: number, clock: Clock = realClock): Ticker => {\n if (!(Number.isFinite(ms) && ms > 0)) throw new RangeError(`The period of a ticker is a finite number above 0, not ${ms}`);\n const ch = new Channel<number>(1);\n const start = clock.now();\n let cancel: Cancel | undefined;\n const arm = (tick: number): void => {\n cancel = clock.after(Math.max(0, start + (tick + 1) * ms - clock.now()), () => {\n const due = Math.max(tick, Math.floor((clock.now() - start) / ms) - 1);\n ch.trySend(due);\n arm(due + 1);\n });\n };\n arm(0);\n return Object.assign(ch, {\n stop: () => {\n cancel?.();\n ch.close();\n },\n });\n};\n\n/** This function starts `work`. It gives a failure to `onError`, and it calls `end` after the work in each case. */\nconst run = (work: () => Promise<void>, end: () => void, onError: ErrorHandler | undefined): void => {\n void work()\n .catch((error: unknown) => onError?.(error))\n .finally(end);\n};\n\n/**\n * This function gives a channel of `transform` of each value of `input`. The output closes when\n * `input` is closed and empty, or after a failure of `transform`.\n */\nexport const pipeline = <T, U>(input: Channel<T>, transform: (value: T) => U | Promise<U>, options: FlowOptions = {}): Channel<U> => {\n const output = new Channel<U>(options.bufferSize);\n run(\n async () => {\n for await (const value of input) await output.send(await transform(value));\n },\n () => output.close(),\n options.onError,\n );\n return output;\n};\n\n/**\n * This function gives `count` channels. Each one gets each value of `input`. The outputs close when\n * `input` is closed and empty, or after a failed send.\n */\nexport const fanOut = <T>(input: Channel<T>, count: number, options: FlowOptions = {}): Channel<T>[] => {\n const outputs = Array.from({ length: count }, () => new Channel<T>(options.bufferSize));\n run(\n async () => {\n for await (const value of input) await Promise.all(outputs.map((ch) => ch.send(value)));\n },\n () => {\n for (const ch of outputs) ch.close();\n },\n options.onError,\n );\n return outputs;\n};\n\n/**\n * This function gives one channel with the values of all `inputs`. The output closes when each\n * input is closed and empty. A failed send of one input goes to `onError`.\n */\nexport const fanIn = <T>(inputs: readonly Channel<T>[], options: FlowOptions = {}): Channel<T> => {\n const output = new Channel<T>(options.bufferSize);\n const workers = inputs.map(async (input) => {\n for await (const value of input) await output.send(value);\n });\n // All the workers settle, then the output closes, also after a failed send\n void Promise.allSettled(workers).then((results) => {\n output.close();\n for (const result of results) if (result.status === \"rejected\") options.onError?.(result.reason);\n });\n return output;\n};\n\n/**\n * This function gives one channel with the values of `inputs`, as `fanIn` does, but it closes when\n * the first input is closed and empty. It takes one value at a time, from the inputs in turn, and\n * keeps no receive on an input while it waits for the reader. Thus each value reaches the output\n * one time, in the order of its input, or stays in its input. With no input, the output is closed.\n */\nexport const merge = <T>(inputs: readonly Channel<T>[]): Channel<T> => {\n const output = new Channel<T>();\n // With no input, no input can give a value, so the output is closed at once, as with fanIn\n if (inputs.length === 0) {\n output.close();\n return output;\n }\n void (async () => {\n // The input after the input of the last value comes first, so a busy input starves no other\n let start = 0;\n while (true) {\n const order = inputs.map((_, offset) => (start + offset) % inputs.length);\n let next: { index: number; value: unknown };\n try {\n next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));\n } catch {\n // An input is closed and empty\n break;\n }\n const index = order[next.index]!;\n start = (index + 1) % inputs.length;\n try {\n // The value came from inputs[index], so it has the type T\n await output.send(next.value as T);\n } catch {\n // The reader closed the output\n break;\n }\n }\n output.close();\n })();\n return output;\n};\n\n/** This function makes a channel with a buffer of `capacity` values. */\nexport const buffered = <T>(capacity: number): Channel<T> => new Channel<T>(capacity);\n\n/** This function makes a channel with no buffer: each send waits for a receiver. */\nexport const unbuffered = <T>(): Channel<T> => new Channel<T>(0);\n\n/** This function makes a channel with a buffer of `bufferSize` values. The default is 0. */\nexport const channel = <T>(bufferSize = 0): Channel<T> => new Channel<T>(bufferSize);\n\n/** These options are for `workerPool`. */\nexport interface WorkerPoolOptions<T> {\n /** The count of workers. The default is 1. */\n readonly workers?: number | undefined;\n /** The size of the buffer of the results. The default is 0. */\n readonly bufferSize?: number | undefined;\n /** This function gets each failure of a job, with the job. The other jobs continue. */\n readonly onError?: ((error: unknown, job: T) => void) | undefined;\n}\n\n/**\n * This function starts `workers` workers. Each one takes a job from `jobs`, gives the job to\n * `worker`, and sends the result. The results close when `jobs` is closed and empty and each\n * worker is done. A failed job goes to `onError`, and its worker takes the next job.\n */\nexport const workerPool = <T, R>(jobs: Channel<T>, worker: (job: T) => Promise<R>, options: WorkerPoolOptions<T> = {}): Channel<R> => {\n const results = new Channel<R>(options.bufferSize);\n const workers = Array.from({ length: options.workers ?? 1 }, async () => {\n for await (const job of jobs) {\n try {\n await results.send(await worker(job));\n } catch (error) {\n options.onError?.(error, job);\n }\n }\n });\n void Promise.all(workers).then(() => results.close());\n return results;\n};\n\n/**\n * This error is the reason of a task that a `preemptivePool` stopped: a newer task took its place,\n * or `stop` stopped it. A caller tells it from a failure of the task with `instanceof`.\n */\nexport class PreemptedError extends Error {\n override readonly name = \"PreemptedError\";\n}\n\n/** A pool that runs at most `max` tasks at a time, and stops the oldest task for a new task. */\nexport interface PreemptivePool {\n /**\n * This method starts `task` with a signal. When the pool is full, it first stops the oldest task.\n * The promise of a stopped task rejects at once with the reason of its signal, and the signal\n * tells the task to stop its work.\n */\n run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R>;\n /** This method stops each task that runs. The reason is `reason`, or a `PreemptedError`. */\n stop(reason?: unknown): void;\n /** This count is the number of tasks that run. */\n readonly size: number;\n}\n\n/**\n * This function makes a pool of at most `max` tasks. The newest task always operates: a new task in a\n * full pool stops the oldest task. This is the policy for work whose old results nobody reads, for\n * example the load of a page that the user left. `workerPool` keeps each job in a queue instead.\n *\n * @throws RangeError when `max` is not an integer of 1 or more.\n */\nexport const preemptivePool = (max: number): PreemptivePool => {\n if (!(Number.isInteger(max) && max >= 1)) throw new RangeError(`preemptivePool: max is an integer of 1 or more, not ${max}.`);\n // The controller of each task that runs, from the oldest. A Set keeps the order of the adds.\n const running = new Set<AbortController>();\n const preempt = (controller: AbortController, reason: unknown): void => {\n running.delete(controller);\n controller.abort(reason);\n };\n return {\n run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R> {\n for (const oldest of running) {\n if (running.size < max) break;\n preempt(oldest, new PreemptedError(\"A newer task took the place of this task.\"));\n }\n const controller = new AbortController();\n running.add(controller);\n const stopped = new Promise<never>((_resolve, reject) => {\n controller.signal.addEventListener(\"abort\", () => reject(controller.signal.reason), { once: true });\n });\n // A task that throws at once rejects as a task that fails later does\n const done = Promise.resolve().then(() => task(controller.signal));\n return Promise.race([done, stopped]).finally(() => running.delete(controller));\n },\n stop(reason?: unknown): void {\n for (const controller of [...running]) preempt(controller, reason ?? new PreemptedError(\"The pool stopped this task.\"));\n },\n get size(): number {\n return running.size;\n },\n };\n};\n"],"mappings":";;;;;;;AA6BA,IAAa,UAAb,MAAwB;CACtB;CACA,SAAiB;;CAGjB,YAAY,aAAa,GAAG;EAE1B,KAAK,QAAQ,WAAc,EAAE,UAAU,WAAW,CAAC;CACrD;;;;;;CAOA,MAAM,KAAK,OAAyB;EAClC,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,+BAA+B;EAChE,MAAM,KAAK,MAAM,IAAI,KAAK;CAC5B;;;;;;CAOA,MAAM,UAAsB;EAC1B,OAAO,MAAM,KAAK,MAAM,KAAK;CAC/B;;;;;;;;CASA,YAAY,SAA6B,UAAiD;EACxF,OAAO,KAAK,MAAM,SA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OAAe;GACjB,OAAO,QAAQ;EACjB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"channel.js","names":[],"sources":["../src/channel.ts"],"sourcesContent":["// @mark1russell7/service/channel: channels in the style of Go, on the clock of the service. It\n// imports only ./clock.ts and @mark1russell7/collections: no `node:` module and no zod. Thus a\n// client in a browser can use it, as it uses ./clock.\n//\n// The code came from @mark1russell7/collections 0.7 (the review of its API, C12, S2). The changes:\n// `timeout` and `ticker` take a clock, `ticker` does not drift, the functions that start work give\n// each failure to `onError` and write nothing to the console, and `fanIn` and `merge` take an array.\n\nimport { asyncQueue, type AsyncQueue } from \"@mark1russell7/collections\";\nimport { realClock, type Cancel, type Clock } from \"./clock.ts\";\n\n/** This function gets a failure of the work that a function of this entry started. */\nexport type ErrorHandler = (error: unknown) => void;\n\n/** These options are for a function that starts work and gives an output channel. */\nexport interface FlowOptions {\n /** The size of the buffer of each output channel. The default is 0: a send waits for a receiver. */\n readonly bufferSize?: number | undefined;\n /**\n * This function gets each failure of the work. The output closes after a failure. Without it,\n * the failure is lost, but the output also closes.\n */\n readonly onError?: ErrorHandler | undefined;\n}\n\n/**\n * A channel carries values from senders to receivers, as a channel of Go does. A channel with a\n * buffer of 0 is a rendezvous: each send waits for a receiver.\n */\nexport class Channel<T> {\n private readonly queue: AsyncQueue<T>;\n private closed = false;\n\n /** This constructor makes a channel with a buffer of `bufferSize` values. The default is 0. */\n constructor(bufferSize = 0) {\n // A buffer of 0 makes a send wait for a receiver (before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17)\n this.queue = asyncQueue<T>({ capacity: bufferSize });\n }\n\n /**\n * This method sends a value. It waits while the buffer is full and no receiver waits.\n *\n * @throws Error when the channel is closed.\n */\n async send(value: T): Promise<void> {\n if (this.closed) throw new Error(\"Cannot send on closed channel\");\n await this.queue.put(value);\n }\n\n /**\n * This method receives a value. It waits while the channel has no value.\n *\n * @throws Error when the channel is closed and empty.\n */\n async receive(): Promise<T> {\n return await this.queue.take();\n }\n\n /**\n * This method waits for one value, as `receive` does, and gives it to `onValue`. When the\n * channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in\n * the call that sends the value or closes the channel.\n *\n * @returns A function that withdraws the wait. It gives true when the wait had no value yet.\n */\n waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {\n return this.queue.waitTake(onValue, onClosed);\n }\n\n /** This method sends a value if a receiver or the buffer takes it at once. It gives false when not. */\n trySend(value: T): boolean {\n if (this.closed) return false;\n return this.queue.tryPut(value);\n }\n\n /** This method receives a value if the channel has one at once. It gives undefined when not. */\n tryReceive(): T | undefined {\n return this.queue.tryTake();\n }\n\n /** This method closes the channel. A send then fails, but a receiver can take the values that stay. */\n close(): void {\n this.closed = true;\n this.queue.close();\n }\n\n /** This value is true after `close`. */\n get isClosed(): boolean {\n return this.closed;\n }\n\n /** This value is the count of values in the buffer. */\n get size(): number {\n return this.queue.size;\n }\n\n /** This method makes a case of `select` for this channel. `handler` gets the value of the case. */\n case<R>(handler: (value: T) => R): SelectCase<R> {\n return {\n // The value of each call comes from this channel, so it has the type T\n handler: (value) => handler(value as T),\n wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),\n };\n }\n\n /** This iteration receives each value. It stops when the channel is closed and empty. */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n let value: T;\n try {\n value = await this.receive();\n } catch {\n // The channel is closed and empty\n return;\n }\n yield value;\n }\n }\n}\n\n/** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */\nexport type Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;\n\n/** A case of `select`: a wait for one value, and the function that gets the value. `Channel.case` makes one. */\nexport interface SelectCase<R> {\n /** This function gets the value of the case, when the case wins. */\n readonly handler: (value: unknown) => R;\n /** This function waits for one value of the case. `select` withdraws it when another case wins. */\n readonly wait: Wait;\n}\n\n/**\n * This function gives the first value of the waits, with the index of its wait. It rejects with\n * the error of the first wait whose channel is closed and empty. It withdraws each other wait in\n * the same call, so a later value stays in its channel (before, the receives of the cases that\n * lost stayed in their channels and dropped the next value of each: audit O56).\n */\nconst firstOf = (waits: readonly Wait[]): Promise<{ index: number; value: unknown }> =>\n new Promise((resolve, reject) => {\n const withdraws: Array<() => boolean> = [];\n let settled = false;\n const end = (): void => {\n settled = true;\n for (const withdraw of withdraws) withdraw();\n };\n // A wait can call back at once, in its own call, when its channel has a value or is closed\n try {\n for (let index = 0; index < waits.length && !settled; index++) {\n withdraws.push(\n waits[index]!(\n (value) => {\n if (settled) return;\n end();\n resolve({ index, value });\n },\n (error) => {\n if (settled) return;\n end();\n reject(error);\n },\n ),\n );\n }\n } catch (error) {\n // A wait that throws: the waits before it are withdrawn\n if (!settled) end();\n reject(error);\n }\n });\n\n/**\n * This function waits for the first case with a value, as the `select` of Go does, and gives the\n * result of its handler. A case that loses keeps no receive: a later value stays in its channel.\n * When the channel of a case is closed and empty, the promise rejects.\n *\n * @example\n * const result = await select(data.case((v) => `data ${v}`), timeout(1000).case(() => \"late\"));\n */\nexport const select = async <R>(...cases: readonly SelectCase<R>[]): Promise<R> => {\n const { index, value } = await firstOf(cases.map((c) => c.wait));\n // The handler runs after the race, not in the call of the sender\n return cases[index]!.handler(value);\n};\n\n/**\n * This function makes a channel that gets one value after `ms` milliseconds of `clock`, and then\n * closes. A case of it in `select` is a time limit.\n */\nexport const timeout = (ms: number, clock: Clock = realClock): Channel<void> => {\n const ch = new Channel<void>();\n // a receiver awaits this value, thus the timer keeps the process alive (SYS-126)\n clock.after(ms, () => {\n // The value waits for a receiver. The close lets the receivers after it fail at once.\n ch.send(undefined).catch(() => undefined);\n ch.close();\n });\n return ch;\n};\n\n/**\n * This error is the reason of the signal of a work that `within` stopped at its time limit. A\n * caller tells it from a failure of the work with `instanceof`.\n */\nexport class LateError extends Error {\n override readonly name = \"LateError\";\n}\n\n/**\n * The result of `within`: the value of the work, an end at the time limit, or the failure of the\n * work. The field `late` tells the two failures apart.\n */\nexport type Within<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly late: true }\n | { readonly ok: false; readonly late: false; readonly error: unknown };\n\n/** A work for `within`: a promise, or a function that gets the signal of the time limit. */\nexport type WithinWork<T> = PromiseLike<T> | ((signal: AbortSignal) => PromiseLike<T> | T);\n\n/**\n * This function gives the result of `work` when the work ends within `ms` milliseconds of `clock`.\n * Else it gives `{ ok: false, late: true }` at the time limit, and it aborts the signal of the work\n * with a `LateError`. The promise does not reject: a failure of the work is a result.\n *\n * The work starts before the timer. Thus a work whose own timer on `clock` ends at the time limit\n * is in time. The end of the work stops the timer, so a finished work keeps no timer. A function\n * that throws starts no timer. A failure of the work after the time limit is caught and dropped.\n * Give the work as a function to get the signal: a promise that started before the call cannot get it.\n *\n * @example\n * const result = await within((signal) => fetch(url, { signal }), 5000, clock);\n * if (result.ok) use(result.value);\n * else if (result.late) report(\"late\");\n * else report(result.error);\n */\nexport const within = <T>(work: WithinWork<T>, ms: number, clock: Clock = realClock): Promise<Within<T>> => {\n if (!(Number.isFinite(ms) && ms >= 0)) throw new RangeError(`The time limit of within is a finite number of 0 or more, not ${ms}`);\n const controller = new AbortController();\n let started: PromiseLike<T> | T;\n try {\n started = typeof work === \"function\" ? work(controller.signal) : work;\n } catch (error) {\n return Promise.resolve({ ok: false, late: false, error });\n }\n return new Promise<Within<T>>((resolve) => {\n let done = false;\n // the caller awaits the bound, thus the timer keeps the process alive (SYS-126)\n const cancel = clock.after(ms, () => {\n if (done) return;\n done = true;\n resolve({ ok: false, late: true });\n controller.abort(new LateError(`The work did not end within ${ms} ms`));\n });\n const end = (result: Within<T>): void => {\n if (done) return;\n done = true;\n cancel();\n resolve(result);\n };\n // The handlers also catch a failure after the time limit: it is not an unhandled rejection\n Promise.resolve(started).then(\n (value) => end({ ok: true, value }),\n (error: unknown) => end({ ok: false, late: false, error }),\n );\n });\n};\n\n/** A ticker is a channel of the numbers of its ticks. `stop` stops its timer and closes it. */\nexport type Ticker = Channel<number> & { readonly stop: () => void };\n\n/**\n * This function makes a channel that gets a tick each `ms` milliseconds of `clock`. Tick k (from 0)\n * comes due at start + (k + 1) * ms, so the ticks do not drift. A late timer gives the number of\n * the last tick that came due, and skips the ticks that it missed. The buffer has 1 value: a slow\n * receiver loses ticks, as with the ticker of Go.\n */\nexport const ticker = (ms: number, clock: Clock = realClock): Ticker => {\n if (!(Number.isFinite(ms) && ms > 0)) throw new RangeError(`The period of a ticker is a finite number above 0, not ${ms}`);\n const ch = new Channel<number>(1);\n const start = clock.now();\n let cancel: Cancel | undefined;\n const arm = (tick: number): void => {\n // a ticker keeps the process alive until its caller stops it, as with setInterval (SYS-126)\n cancel = clock.after(Math.max(0, start + (tick + 1) * ms - clock.now()), () => {\n const due = Math.max(tick, Math.floor((clock.now() - start) / ms) - 1);\n ch.trySend(due);\n arm(due + 1);\n });\n };\n arm(0);\n return Object.assign(ch, {\n stop: () => {\n cancel?.();\n ch.close();\n },\n });\n};\n\n/** This function starts `work`. It gives a failure to `onError`, and it calls `end` after the work in each case. */\nconst run = (work: () => Promise<void>, end: () => void, onError: ErrorHandler | undefined): void => {\n void work()\n .catch((error: unknown) => onError?.(error))\n .finally(end);\n};\n\n/**\n * This function gives a channel of `transform` of each value of `input`. The output closes when\n * `input` is closed and empty, or after a failure of `transform`.\n */\nexport const pipeline = <T, U>(input: Channel<T>, transform: (value: T) => U | Promise<U>, options: FlowOptions = {}): Channel<U> => {\n const output = new Channel<U>(options.bufferSize);\n run(\n async () => {\n for await (const value of input) await output.send(await transform(value));\n },\n () => output.close(),\n options.onError,\n );\n return output;\n};\n\n/**\n * This function gives `count` channels. Each one gets each value of `input`. The outputs close when\n * `input` is closed and empty, or after a failed send.\n */\nexport const fanOut = <T>(input: Channel<T>, count: number, options: FlowOptions = {}): Channel<T>[] => {\n const outputs = Array.from({ length: count }, () => new Channel<T>(options.bufferSize));\n run(\n async () => {\n for await (const value of input) await Promise.all(outputs.map((ch) => ch.send(value)));\n },\n () => {\n for (const ch of outputs) ch.close();\n },\n options.onError,\n );\n return outputs;\n};\n\n/**\n * This function gives one channel with the values of all `inputs`. The output closes when each\n * input is closed and empty. A failed send of one input goes to `onError`.\n */\nexport const fanIn = <T>(inputs: readonly Channel<T>[], options: FlowOptions = {}): Channel<T> => {\n const output = new Channel<T>(options.bufferSize);\n const workers = inputs.map(async (input) => {\n for await (const value of input) await output.send(value);\n });\n // All the workers settle, then the output closes, also after a failed send\n void Promise.allSettled(workers).then((results) => {\n output.close();\n for (const result of results) if (result.status === \"rejected\") options.onError?.(result.reason);\n });\n return output;\n};\n\n/**\n * This function gives one channel with the values of `inputs`, as `fanIn` does, but it closes when\n * the first input is closed and empty. It takes one value at a time, from the inputs in turn, and\n * keeps no receive on an input while it waits for the reader. Thus each value reaches the output\n * one time, in the order of its input, or stays in its input. With no input, the output is closed.\n */\nexport const merge = <T>(inputs: readonly Channel<T>[]): Channel<T> => {\n const output = new Channel<T>();\n // With no input, no input can give a value, so the output is closed at once, as with fanIn\n if (inputs.length === 0) {\n output.close();\n return output;\n }\n void (async () => {\n // The input after the input of the last value comes first, so a busy input starves no other\n let start = 0;\n while (true) {\n const order = inputs.map((_, offset) => (start + offset) % inputs.length);\n let next: { index: number; value: unknown };\n try {\n next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));\n } catch {\n // An input is closed and empty\n break;\n }\n const index = order[next.index]!;\n start = (index + 1) % inputs.length;\n try {\n // The value came from inputs[index], so it has the type T\n await output.send(next.value as T);\n } catch {\n // The reader closed the output\n break;\n }\n }\n output.close();\n })();\n return output;\n};\n\n/** This function makes a channel with a buffer of `capacity` values. */\nexport const buffered = <T>(capacity: number): Channel<T> => new Channel<T>(capacity);\n\n/** This function makes a channel with no buffer: each send waits for a receiver. */\nexport const unbuffered = <T>(): Channel<T> => new Channel<T>(0);\n\n/** This function makes a channel with a buffer of `bufferSize` values. The default is 0. */\nexport const channel = <T>(bufferSize = 0): Channel<T> => new Channel<T>(bufferSize);\n\n/** These options are for `workerPool`. */\nexport interface WorkerPoolOptions<T> {\n /** The count of workers. The default is 1. */\n readonly workers?: number | undefined;\n /** The size of the buffer of the results. The default is 0. */\n readonly bufferSize?: number | undefined;\n /** This function gets each failure of a job, with the job. The other jobs continue. */\n readonly onError?: ((error: unknown, job: T) => void) | undefined;\n}\n\n/**\n * This function starts `workers` workers. Each one takes a job from `jobs`, gives the job to\n * `worker`, and sends the result. The results close when `jobs` is closed and empty and each\n * worker is done. A failed job goes to `onError`, and its worker takes the next job.\n */\nexport const workerPool = <T, R>(jobs: Channel<T>, worker: (job: T) => Promise<R>, options: WorkerPoolOptions<T> = {}): Channel<R> => {\n const results = new Channel<R>(options.bufferSize);\n const workers = Array.from({ length: options.workers ?? 1 }, async () => {\n for await (const job of jobs) {\n try {\n await results.send(await worker(job));\n } catch (error) {\n options.onError?.(error, job);\n }\n }\n });\n void Promise.all(workers).then(() => results.close());\n return results;\n};\n\n/**\n * This error is the reason of a task that a `preemptivePool` stopped: a newer task took its place,\n * or `stop` stopped it. A caller tells it from a failure of the task with `instanceof`.\n */\nexport class PreemptedError extends Error {\n override readonly name = \"PreemptedError\";\n}\n\n/** A pool that runs at most `max` tasks at a time, and stops the oldest task for a new task. */\nexport interface PreemptivePool {\n /**\n * This method starts `task` with a signal. When the pool is full, it first stops the oldest task.\n * The promise of a stopped task rejects at once with the reason of its signal, and the signal\n * tells the task to stop its work.\n */\n run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R>;\n /** This method stops each task that runs. The reason is `reason`, or a `PreemptedError`. */\n stop(reason?: unknown): void;\n /** This count is the number of tasks that run. */\n readonly size: number;\n}\n\n/**\n * This function makes a pool of at most `max` tasks. The newest task always operates: a new task in a\n * full pool stops the oldest task. This is the policy for work whose old results nobody reads, for\n * example the load of a page that the user left. `workerPool` keeps each job in a queue instead.\n *\n * @throws RangeError when `max` is not an integer of 1 or more.\n */\nexport const preemptivePool = (max: number): PreemptivePool => {\n if (!(Number.isInteger(max) && max >= 1)) throw new RangeError(`preemptivePool: max is an integer of 1 or more, not ${max}.`);\n // The controller of each task that runs, from the oldest. A Set keeps the order of the adds.\n const running = new Set<AbortController>();\n const preempt = (controller: AbortController, reason: unknown): void => {\n running.delete(controller);\n controller.abort(reason);\n };\n return {\n run<R>(task: (signal: AbortSignal) => Promise<R>): Promise<R> {\n for (const oldest of running) {\n if (running.size < max) break;\n preempt(oldest, new PreemptedError(\"A newer task took the place of this task.\"));\n }\n const controller = new AbortController();\n running.add(controller);\n const stopped = new Promise<never>((_resolve, reject) => {\n controller.signal.addEventListener(\"abort\", () => reject(controller.signal.reason), { once: true });\n });\n // A task that throws at once rejects as a task that fails later does\n const done = Promise.resolve().then(() => task(controller.signal));\n return Promise.race([done, stopped]).finally(() => running.delete(controller));\n },\n stop(reason?: unknown): void {\n for (const controller of [...running]) preempt(controller, reason ?? new PreemptedError(\"The pool stopped this task.\"));\n },\n get size(): number {\n return running.size;\n },\n };\n};\n"],"mappings":";;;;;;;AA6BA,IAAa,UAAb,MAAwB;CACtB;CACA,SAAiB;;CAGjB,YAAY,aAAa,GAAG;EAE1B,KAAK,QAAQ,WAAc,EAAE,UAAU,WAAW,CAAC;CACrD;;;;;;CAOA,MAAM,KAAK,OAAyB;EAClC,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,+BAA+B;EAChE,MAAM,KAAK,MAAM,IAAI,KAAK;CAC5B;;;;;;CAOA,MAAM,UAAsB;EAC1B,OAAO,MAAM,KAAK,MAAM,KAAK;CAC/B;;;;;;;;CASA,YAAY,SAA6B,UAAiD;EACxF,OAAO,KAAK,MAAM,SAAS,SAAS,QAAQ;CAC9C;;CAGA,QAAQ,OAAmB;EACzB,IAAI,KAAK,QAAQ,OAAO;EACxB,OAAO,KAAK,MAAM,OAAO,KAAK;CAChC;;CAGA,aAA4B;EAC1B,OAAO,KAAK,MAAM,QAAQ;CAC5B;;CAGA,QAAc;EACZ,KAAK,SAAS;EACd,KAAK,MAAM,MAAM;CACnB;;C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