@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.
@@ -1 +1 @@
1
- {"version":3,"file":"core.js","names":[],"sources":["../../src/client/core.ts"],"sourcesContent":["// The parts of a client wrapper that do not change from one client to the next. Each client entry\n// (`./redis`, `./pg`, `./http-client`, `./websocket`, and each later client of S1) fills them in with its driver. The core gives\n// the shapes of a client, the outcome of a call in three values, the rule that sends a call again,\n// the record of the calls in flight, the bounded close, the checks of the steps of a connection,\n// and the problems of a spec and of a client in a description. It loads only quantity.\n// The section \"Unified or separate\" of docs/S6.md gives each part, and the reason for each part that stays in a driver.\n\nimport type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { quantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { Backoff } from \"../backoff.ts\";\nimport { retrierOn } from \"../retrier.ts\";\nimport type { ServiceBuilder } from \"../builder.ts\";\nimport type { Cancel, Clock } from \"../clock.ts\";\nimport type { Check, Dependency, Gate, ServiceDescription, Step } from \"../description.ts\";\nimport type { Recorder } from \"../events.ts\";\nimport type { Outcome } from \"../latch.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport { mayReissue } from \"../operation.ts\";\nimport type { CheckFn } from \"../poller.ts\";\nimport type { Poll } from \"../timing.ts\";\nimport type { Meeting } from \"./meets.ts\";\n\n/**\n * A sent result is the outcome of a call, in three values (C8):\n * - `ok`: the server answered.\n * - `error`: the call did not apply. The server answered with an error (`reply`), or the call did\n * not leave the client.\n * - `indeterminate`: the call can have reached the server, and nothing tells if it applied.\n */\nexport type Sent<T> =\n | { readonly outcome: \"ok\"; readonly value: T; readonly attempts: number }\n | { readonly outcome: \"error\"; readonly error: string; readonly reply: boolean; readonly attempts: number }\n | { readonly outcome: \"indeterminate\"; readonly error: string; readonly attempts: number };\n\n/** This type is the outcome of one try of a call, before the core counts the tries. */\nexport type Attempt<T = unknown> =\n | { readonly outcome: \"ok\"; readonly value: T }\n | { readonly outcome: \"error\"; readonly error: string; readonly reply: boolean }\n | { readonly outcome: \"indeterminate\"; readonly error: string };\n\n/** Send options tell how the client sends one call. */\nexport interface SendOptions {\n /** This signal abandons the call. A call that left the client is then indeterminate. */\n readonly signal?: AbortSignal | undefined;\n /** False stops the client: it does not send the call again. A check that must fail at once uses it. */\n readonly reissue?: boolean | undefined;\n}\n\n/** A dial function opens a new connection to the server, and reads one reply of the protocol. The `dial` check uses it. */\nexport type DialFn = (host: string, port: number, signal: AbortSignal) => Promise<void>;\n\n/** The steps of a connection that each client gives a check for (B14). A client can add more steps. */\nexport type ClientStep = Extract<Step, \"dial\" | \"round-trip\" | \"local-state\">;\n\n/** Check options tell which checks the client gives the health runtime, and which policy each one controls. */\nexport interface CheckOptions<S extends Step = ClientStep> {\n readonly poll: Poll;\n /** For each step, the policy that its check controls, or null for a check that only reports. A step that is absent has no check. */\n readonly steps: Partial<Record<S, Gate | null>>;\n /**\n * With a catalog, the client gives a check for each step that it has (B19). The steps of `steps` are\n * the nominated checks. Each other step reports only, and polls at the catalog poll. `true` is a poll\n * of 30 s with the jitter and the timeout of `poll`. A nominated step that the client has no check\n * for then fails the attach. Without a catalog, the client gives only the steps of `steps`.\n */\n readonly catalog?: true | Poll | undefined;\n}\n\n/** This interval is the poll of a catalog check that gates nothing (B19). */\nexport const CATALOG_INTERVAL: Quantity = quantity(30, \"s\");\n\n/** A step check is the function of one step, and if it uses the connection of the application. */\nexport interface StepCheck {\n readonly ownConnection: boolean;\n readonly run: CheckFn;\n}\n\n/** This function gives an amount in milliseconds. \"infinite\" is `Infinity`. */\nexport const ms = (amount: Extent): number =>\n amount.value === \"infinite\" ? Number.POSITIVE_INFINITY : valueIn(amount as Quantity, \"ms\");\n\n/** This function gives an amount in milliseconds, or undefined for \"infinite\". Each driver then writes its own form of \"no timer\". */\nexport const finiteMs = (amount: Extent): number | undefined => {\n const value = ms(amount);\n return Number.isFinite(value) ? value : undefined;\n};\n\n/** This function gives the text of an error. */\nexport const message = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * These are the knobs that each client has, by the names of the ordering law. Each driver adds its\n * own knobs. The comments of each driver tell which option of the driver a knob sets.\n */\nexport interface ClientKnobs {\n /** This time bounds a new connection. */\n readonly connect_bound: Quantity;\n /** This time bounds each call on the connection of the application. */\n readonly request_timeout: Quantity;\n /** This time is the idle time of TCP keepalive. Node then sends 10 probes 1 s apart. */\n readonly keepalive_idle: Extent;\n /** This time is the age at which the client replaces a connection. */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the client at the shutdown. */\n readonly close_bound: Quantity;\n /**\n * This time is when the kernel gives up a segment that it retransmits. Node cannot set it, thus\n * the declaration states it for the ordering law (O17), from the platform.\n */\n readonly retrans_giveup_time: Extent;\n}\n\n/** A client spec is the declaration of one client: where it connects, and its knobs. Each driver adds its own fields. */\nexport interface ClientSpec<K extends ClientKnobs = ClientKnobs> {\n readonly host: string;\n readonly port: number;\n readonly password?: string | undefined;\n /** This identifier is the component in the corpus, for example `systems.component.redis`, or null. */\n readonly system: string | null;\n readonly knobs: K;\n /** These operations add to the table of the client, or change it. */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** A factory makes the connection or the pool of a client from the options of its driver. */\nexport type Factory<O, C> = (options: O) => C | Promise<C>;\n\n/** These options make a client. Without them, a client uses its driver, the real clock, and the dial of its protocol. */\nexport interface ClientOptions<F> {\n readonly create?: F | undefined;\n readonly clock?: Clock | undefined;\n /** This function receives each transition of the client, for the prober (D3). */\n readonly record?: Recorder | undefined;\n readonly dial?: DialFn | undefined;\n}\n\n/** A client socket is the part of the socket of a connection that the join of the prober and the bounded close read. */\nexport interface ClientSocket {\n readonly localAddress?: string | undefined;\n readonly localPort?: number | undefined;\n readonly remoteAddress?: string | undefined;\n readonly remotePort?: number | undefined;\n /** This method closes the socket at once. A close of the driver only half-closes it, and a silent peer does not answer that. */\n destroy?(): void;\n}\n\n/**\n * A client join is one connection, at the time when it can serve (D1, D2). The prober joins its\n * kernel records to the server's view of the connection through it. Each driver adds the server's id of the connection.\n */\nexport interface ClientJoin {\n readonly generation: number;\n /** This time is when the connection became ready, in milliseconds on the monotonic clock. */\n readonly at: number;\n readonly localAddress: string | null;\n readonly localPort: number | null;\n readonly remoteAddress: string | null;\n readonly remotePort: number | null;\n}\n\n/** This function gives the addresses and the ports of a socket for a join. Each one is null when the socket does not give it. */\nexport const socketEnds = (\n socket: ClientSocket | undefined,\n): Pick<ClientJoin, \"localAddress\" | \"localPort\" | \"remoteAddress\" | \"remotePort\"> => ({\n localAddress: socket?.localAddress ?? null,\n localPort: socket?.localPort ?? null,\n remoteAddress: socket?.remoteAddress ?? null,\n remotePort: socket?.remotePort ?? null,\n});\n\n/** A client is a dependency of a service: its declaration, its handle and its checks. Each driver adds the method that sends a call. */\nexport interface Client<S extends Step = ClientStep, J extends ClientJoin = ClientJoin> {\n readonly name: string;\n /** This declaration goes to `svc.dependency(name, declaration, handle)`. */\n readonly declaration: Omit<Dependency, \"name\">;\n readonly handle: DependencyHandle;\n /** These are the manifestations that the client can meet, and the detectors of each (E9). */\n readonly meets: readonly Meeting[];\n /** This text is the state of the client, as the machine document of the client names it. */\n readonly status: string;\n /** These are the connections of the client, the latest last. */\n readonly joins: readonly J[];\n /** This method gives the checks of the client and their functions, for `svc.check(check, run)`. */\n checks(options: CheckOptions<S>): ReadonlyArray<readonly [Check, CheckFn]>;\n /** This method declares the client in a service: its dependency, its handle and its checks. */\n attach(svc: ServiceBuilder, options: CheckOptions<S>): ServiceBuilder;\n /** This method gives the problems of the client in a description: a close that does not fit in its phase, for example. */\n problems(description: ServiceDescription): string[];\n}\n\n/** This function declares a client in a service: its dependency, its handle, and each of its checks. */\nexport const attachClient = (\n svc: ServiceBuilder,\n name: string,\n declaration: Omit<Dependency, \"name\">,\n handle: DependencyHandle,\n checks: ReadonlyArray<readonly [Check, CheckFn]>,\n): ServiceBuilder => {\n svc.dependency(name, declaration, handle);\n for (const [check, run] of checks) svc.check(check, run);\n return svc;\n};\n\n/** This function gives the table of operations of a client: the defaults of its driver, then the operations of its spec. */\nexport const operationTable = (\n defaults: Readonly<Record<string, Operation>>,\n more: Readonly<Record<string, Operation>> | undefined,\n): Readonly<Record<string, Operation>> => ({ ...defaults, ...more });\n\n/** A client recorder gives one transition of a client to the recorder of the options, for the prober (D3). */\nexport type ClientRecorder = (from: string, to: string, on: string, detail?: string) => void;\n\n/** This function makes the recorder of a client. Each event has the machine \"client\", and the name of the client as its instance. */\nexport const clientRecorder =\n (record: Recorder | undefined, clock: Clock, name: string): ClientRecorder =>\n (from, to, on, detail) =>\n record?.({ at: clock.now(), machine: \"client\", instance: name, from, to, on, ...(detail === undefined ? {} : { detail }) });\n\n/** This function gives the outcome of a call that did not leave the client. It is certain: the call did not apply. */\nexport const notSent = (error: string): Attempt<never> => ({ outcome: \"error\", error, reply: false });\n\n/** A settle function gives the outcome of a call in flight. A driver can give a cause, for example the error that ends a client of a pool. */\nexport type Settle<T = unknown> = (value: Attempt<T>, cause?: Error) => void;\n\n/**\n * This record holds the calls in flight of a client. Each call settles one time. A call that the\n * caller abandons after it left the client is indeterminate, because a sent call cannot be\n * cancelled (principle 9). The close and a closed connection settle each call that stays (C10).\n */\nexport interface InFlight {\n /** This number is the count of the calls in flight. */\n readonly size: number;\n /**\n * This method sends one call, and records it until it settles. `start` sends the call, and gives\n * its outcome to `settle`. `after` operates one time, after the call settles and before its promise resolves.\n */\n track<T>(\n signal: AbortSignal | undefined,\n abandoned: string,\n start: (settle: Settle<T>) => void,\n after?: (value: Attempt<T>, cause: Error | undefined) => void,\n ): Promise<Attempt<T>>;\n /** This method settles each call in flight as indeterminate, with this error. */\n settleAll(error: string): void;\n /** This method resolves when no call is in flight. A close that waits for its calls uses it in its bound. */\n idle(): Promise<void>;\n}\n\n/** This function makes the record of the calls in flight of a client. */\nexport const inFlight = (): InFlight => {\n const closes = new Set<(error: string) => void>();\n const waiters = new Set<() => void>();\n const wake = (): void => {\n if (closes.size > 0) return;\n for (const waiter of [...waiters]) waiter();\n waiters.clear();\n };\n return {\n get size() {\n return closes.size;\n },\n idle: () =>\n new Promise<void>((resolve) => {\n if (closes.size === 0) resolve();\n else waiters.add(resolve);\n }),\n track<T>(\n signal: AbortSignal | undefined,\n abandoned: string,\n start: (settle: Settle<T>) => void,\n after?: (value: Attempt<T>, cause: Error | undefined) => void,\n ): Promise<Attempt<T>> {\n return new Promise<Attempt<T>>((resolve) => {\n let settled = false;\n const settle: Settle<T> = (value, cause) => {\n if (settled) return;\n settled = true;\n closes.delete(close);\n signal?.removeEventListener(\"abort\", aborted);\n after?.(value, cause);\n resolve(value);\n wake();\n };\n const close = (error: string): void => settle({ outcome: \"indeterminate\", error }, new Error(error));\n const aborted = (): void => close(abandoned);\n closes.add(close);\n signal?.addEventListener(\"abort\", aborted, { once: true });\n start(settle);\n });\n },\n settleAll(error) {\n for (const close of [...closes]) close(error);\n },\n };\n};\n\n/**\n * This function sends one call through the record of the calls in flight, with a timer of the\n * wrapper. A driver with no timer for its call uses it: amqplib, and the agent of Node. At `bound`\n * milliseconds the call is indeterminate with the error `timedOut`, because it left the client.\n * The timer stops when the call settles, before `after` operates.\n */\nexport const trackWithTimer = <T>(\n flight: InFlight,\n clock: Clock,\n bound: number,\n signal: AbortSignal | undefined,\n abandoned: string,\n timedOut: string,\n start: (settle: Settle<T>) => void,\n after?: (value: Attempt<T>, cause: Error | undefined) => void,\n): Promise<Attempt<T>> => {\n let stop: Cancel = () => {};\n return flight.track<T>(\n signal,\n abandoned,\n (settle) => {\n stop = clock.after(bound, () => settle({ outcome: \"indeterminate\", error: timedOut }));\n start(settle);\n },\n (value, cause) => {\n stop();\n after?.(value, cause);\n },\n );\n};\n\n/**\n * This function waits for the work of a close, for `bound` milliseconds at most. It gives true when\n * the work ended in its bound, with a success or a failure. It gives false at the bound. The driver\n * then destroys each socket that stays, because a silent server does not close its half.\n */\nexport const withinBound = (clock: Clock, bound: number, work: Promise<unknown>): Promise<boolean> => {\n const done = work.then(\n () => true,\n () => true,\n );\n let cancel: Cancel = () => {};\n const timer = new Promise<boolean>((resolve) => {\n cancel = clock.after(bound, () => resolve(false));\n });\n return Promise.race([done, timer]).then((ended) => {\n cancel();\n return ended;\n });\n};\n\n/**\n * A ready wait holds the calls that wait for a ready connection before their second try. A client\n * that connects again by itself uses it: Redis and RabbitMQ.\n */\nexport interface ReadyWait {\n /** This method waits until the client is ready, for `within` milliseconds at most. It gives true when the client is ready. */\n wait(within: number, signal?: AbortSignal): Promise<boolean>;\n /** This method ends each wait with true. The client uses it when its connection is ready. */\n wake(): void;\n}\n\n/** This function makes the ready wait of a client. The function `ready` tells if the client is ready. */\nexport const readyWait = (clock: Clock, ready: () => boolean): ReadyWait => {\n const waiters = new Set<() => void>();\n return {\n wait: (within, signal) =>\n new Promise((resolve) => {\n if (ready()) {\n resolve(true);\n return;\n }\n let cancel: Cancel = () => {};\n const done = (value: boolean): void => {\n waiters.delete(wake);\n cancel();\n signal?.removeEventListener(\"abort\", aborted);\n resolve(value);\n };\n const wake = (): void => done(true);\n const aborted = (): void => done(false);\n waiters.add(wake);\n cancel = clock.after(within, () => done(ready()));\n signal?.addEventListener(\"abort\", aborted, { once: true });\n }),\n wake() {\n for (const wake of [...waiters]) wake();\n },\n };\n};\n\n/** These are the knobs of a client that connects again by itself, after a delay that doubles. */\nexport interface RetryKnobs {\n /** This time is the first delay before a new try to connect. The delay doubles after each try. */\n readonly retry_base: Quantity;\n /** This time is the most that one delay can be, before its jitter. */\n readonly retry_cap: Quantity;\n}\n\n/**\n * This function gives the backoff of the tries to connect: from `retry_base`, doubling to\n * `retry_cap`, each with a jitter up to the base. The client rounds each delay to a whole millisecond.\n */\nexport const retryBackoff = (knobs: RetryKnobs): Backoff => ({\n base: ms(knobs.retry_base),\n factor: 2,\n cap: ms(knobs.retry_cap),\n jitter: { kind: \"add\", amount: ms(knobs.retry_base) },\n});\n\n/**\n * A retry schedule holds the next try to connect, for a client that connects again by itself. It\n * counts the tries since the last join. Each delay comes from the backoff, rounded to a whole millisecond.\n */\nexport interface RetrySchedule {\n /** This count is the number of tries since the last reset. */\n readonly tries: number;\n /** This method counts one more try, and starts `due` after the delay of that try. It stops a try that waits. */\n schedule(due: () => void): void;\n /** This method stops the try that waits. The close uses it. */\n cancel(): void;\n /** This method sets the count of tries to zero. The client uses it at each join. */\n reset(): void;\n}\n\n/** This function makes the retry schedule of a client, from its backoff and its random numbers. RabbitMQ and WebSocket use it. */\nexport const retrySchedule = (clock: Clock, backoff: Backoff, random: () => number): RetrySchedule => {\n // the public retrier does the same work: the schedule only names its count `tries`\n const retry = retrierOn(clock, backoff, random);\n return {\n get tries() {\n return retry.attempts;\n },\n schedule(due) {\n retry.schedule(due);\n },\n cancel: () => retry.cancel(),\n reset: () => retry.reset(),\n };\n};\n\n/** This function gives the problems of the retry knobs: the cap must not be below the base. */\nexport const retryProblems = (name: string, knobs: RetryKnobs): string[] =>\n ms(knobs.retry_cap) < ms(knobs.retry_base) ? [`${name}'s retry_cap is below its retry_base`] : [];\n\n/**\n * This function gives the problem of a count of misses that is not a whole number above zero. A\n * client that closes its connection after a count of heartbeat misses uses it. `mechanism` names the heartbeat, for example \"watchdog\".\n */\nexport const missesProblems = (name: string, misses: number, mechanism: string): string[] =>\n Number.isInteger(misses) && misses >= 1 ? [] : [`${name}'s ${mechanism} closes the connection after ${misses} misses, not a whole number above zero`];\n\n/** This function gives the problems of the knobs of a spec that each client has: each knob must be a time of zero or more. */\nexport const timeProblems = (name: string, knobs: object): string[] => {\n const problems: string[] = [];\n for (const [knob, amount] of Object.entries(knobs) as Array<[string, Extent]>) {\n if (amount.value !== \"infinite\" && !(ms(amount) >= 0)) problems.push(`${name}'s ${knob} is not a time of zero or more`);\n }\n return problems;\n};\n\n/** This function writes a bound for a driver that reads 0 as no timer: \"infinite\" is 0. */\nexport const orZero = (amount: Extent): number => finiteMs(amount) ?? 0;\n\n/** This function tells if an amount is a whole number of milliseconds. \"infinite\" is whole. */\nexport const wholeMs = (amount: Extent): boolean => amount.value === \"infinite\" || Number.isInteger(ms(amount));\n\n/** This function tells if an amount is a whole number of seconds. \"infinite\" is whole. */\nexport const wholeSeconds = (amount: Extent): boolean =>\n amount.value === \"infinite\" || Number.isInteger(valueIn(amount as Quantity, \"s\"));\n\n/** These are the knobs of a spec that `zeroProblems` and `wholeProblems` examine, by their kind. */\nexport interface KnobKinds {\n /** These knobs must be a finite time above zero, because the driver reads 0 as no bound. */\n readonly bounded?: readonly string[] | undefined;\n /** These knobs can be \"infinite\", which the driver writes as 0. Thus 0 itself is not a bound. */\n readonly open?: readonly string[] | undefined;\n /** These knobs go to the driver in whole milliseconds. */\n readonly millis?: readonly string[] | undefined;\n /** These knobs go to the driver or to Node in whole seconds. */\n readonly seconds?: readonly string[] | undefined;\n}\n\nconst knobOf = (knobs: object, knob: string): Extent => (knobs as Record<string, Extent>)[knob]!;\n\n/**\n * This function gives the problems of the knobs of a driver that reads 0 as no timer. pg and the\n * MongoDB driver read 0 so. A bounded knob must be a finite time above zero. An open knob can be\n * \"infinite\", and 0 is then a mistake.\n */\nexport const zeroProblems = (name: string, driver: string, knobs: object, kinds: KnobKinds): string[] => {\n const problems: string[] = [];\n for (const knob of kinds.bounded ?? []) {\n const value = ms(knobOf(knobs, knob));\n if (!(value > 0) || !Number.isFinite(value)) problems.push(`${name}'s ${knob} is not a finite time above zero: ${driver} reads 0 as no bound`);\n }\n for (const knob of kinds.open ?? []) {\n const amount = knobOf(knobs, knob);\n if (amount.value !== \"infinite\" && !(ms(amount) > 0)) problems.push(`${name}'s ${knob} is zero: give \"infinite\" for no bound`);\n }\n return problems;\n};\n\n/** This function gives the problems of the knobs that a driver takes in whole milliseconds or in whole seconds. */\nexport const wholeProblems = (name: string, knobs: object, kinds: KnobKinds): string[] => [\n ...(kinds.millis ?? []).filter((knob) => !wholeMs(knobOf(knobs, knob))).map((knob) => `${name}'s ${knob} is not a whole number of milliseconds`),\n ...(kinds.seconds ?? []).filter((knob) => !wholeSeconds(knobOf(knobs, knob))).map((knob) => `${name}'s ${knob} is not a whole number of seconds`),\n];\n\n/** This function gives the problems of the sizes of a pool: at most `max` connections, and `min` from 0 to `max`. */\nexport const poolProblems = (name: string, pool: { readonly max: number; readonly min: number }): string[] => {\n const problems: string[] = [];\n if (!Number.isInteger(pool.max) || pool.max < 1) problems.push(`${name}'s pool has a max of ${pool.max}, not a whole number above zero`);\n if (!Number.isInteger(pool.min) || pool.min < 0 || pool.min > pool.max)\n problems.push(`${name}'s pool has a min of ${pool.min}, not a whole number from 0 to its max`);\n return problems;\n};\n\n/**\n * This function gives the problem O07 of a client whose server has a deadline, or null. The client\n * must wait longer than the deadline of the server. Then the server ends a slow call with an error\n * first. Otherwise the client gives up first, and the server goes on with the call. `call` names\n * the call of the server, for example a statement.\n */\nexport const deadlineProblem = (name: string, request: Quantity, deadline: Extent, call: string): string | null =>\n deadline.value !== \"infinite\" && ms(request) <= ms(deadline)\n ? `${name}'s request_timeout is not above its statement_timeout: the server goes on with a ${call} that the client gave up (O07)`\n : null;\n\n/**\n * This function gives the problem O01 of a client pool, or null. The pool must close an idle\n * connection before its server does. Otherwise a request can go on a connection that the server\n * closed. A server that keeps an idle connection with no bound gives no problem. `knob` names the\n * idle time of the client: `pool_idle_expiry` of a pool, or `client_idle_timeout` of a gRPC channel.\n */\nexport const idleCloseProblem = (name: string, expiry: Extent, close: Extent, knob = \"pool_idle_expiry\"): string | null =>\n close.value !== \"infinite\" && !(ms(expiry) < ms(close))\n ? `${name}'s ${knob} is not below the idle close of its server: a request can go on a connection that the server closed (O01)`\n : null;\n\n/**\n * This function gives the problems of the timers that the wrapper has, because its driver has none.\n * Each one must be a finite time above zero. `bounds` gives what each knob bounds, for example \"a call\".\n */\nexport const wrapperTimerProblems = (name: string, knobs: object, bounds: Readonly<Record<string, string>>): string[] =>\n Object.entries(bounds)\n .filter(([knob]) => {\n const value = ms(knobOf(knobs, knob));\n return !(value > 0) || !Number.isFinite(value);\n })\n .map(([knob, what]) => `${name}'s ${knob} is not a finite time above zero: the timer of the wrapper is the only bound of ${what}`);\n\n/** This function gives the problem of a finite connection age, for a client that does not replace a connection at an age. `reason` tells why. */\nexport const ageProblems = (name: string, knobs: Pick<ClientKnobs, \"max_connection_age\">, reason: string): string[] =>\n knobs.max_connection_age.value === \"infinite\" ? [] : [`${name}'s max_connection_age is not \"infinite\": ${reason}`];\n\n/** This function gives the problem of a keepalive that is not a finite time above zero, for a driver that always turns keepalive on. */\nexport const keepaliveOnProblems = (name: string, knobs: Pick<ClientKnobs, \"keepalive_idle\">, driver: string): string[] => {\n const value = ms(knobs.keepalive_idle);\n return value > 0 && Number.isFinite(value) ? [] : [`${name}'s keepalive_idle is not a finite time above zero: ${driver} always turns keepalive on`];\n};\n\n/** These are the parts of one call that the core uses to send it, and to send it again. */\nexport interface Reissue<T> {\n readonly clock: Clock;\n /** This time bounds the call and its second try, in milliseconds from its start. */\n readonly bound: number;\n /** This operation is the declaration of the call, or undefined when the table does not name it. */\n readonly operation: Operation | undefined;\n readonly options: SendOptions;\n /** This function makes one try. Its signal ends the try. */\n readonly attempt: (signal: AbortSignal | undefined) => Promise<Attempt<T>>;\n /** This function operates before the second try, with the time that is left. False stops the second try. */\n readonly beforeAgain?: ((left: number, signal: AbortSignal | undefined) => Promise<boolean>) | undefined;\n /** This function receives the start of a second try, for the record of the client. */\n readonly onReissue: () => void;\n}\n\n/**\n * This function sends a call, and gives its outcome in three values. It sends again only an\n * idempotent operation, one time at most, after an outcome that is not certain. A reply of the\n * server is certain. The second try ends at the bound of the call, not one bound after its own start.\n */\nexport const sendWithReissue = async <T>(call: Reissue<T>): Promise<Sent<T>> => {\n const { clock, bound } = call;\n const { signal } = call.options;\n const operation = call.options.reissue === false ? undefined : call.operation;\n const started = clock.now();\n const first = await call.attempt(signal);\n if (first.outcome === \"ok\") return { outcome: \"ok\", value: first.value, attempts: 1 };\n const again =\n !(first.outcome === \"error\" && first.reply) &&\n operation !== undefined &&\n signal?.aborted !== true &&\n mayReissue(operation, quantity((clock.now() - started) / 1000, \"s\"));\n const left = bound - (clock.now() - started);\n if (!again || left <= 0) return { ...first, attempts: 1 };\n if (call.beforeAgain !== undefined && !(await call.beforeAgain(left, signal))) return { ...first, attempts: 1 };\n call.onReissue();\n const end = new AbortController();\n const stop = clock.after(Math.max(0, bound - (clock.now() - started)), () => end.abort());\n const forward = (): void => end.abort();\n signal?.addEventListener(\"abort\", forward, { once: true });\n const second = await call.attempt(end.signal);\n stop();\n signal?.removeEventListener(\"abort\", forward);\n return second.outcome === \"ok\" ? { outcome: \"ok\", value: second.value, attempts: 2 } : { ...second, attempts: 2 };\n};\n\n/**\n * This function gives the checks of a client, for `svc.check(check, run)`. Without a catalog, it gives\n * a check for each step that the options name, when the client has a function for that step. With a\n * catalog, it gives a check for each step of the client. It then throws for a nominated step that the\n * client does not have (B19). The name of each check is the pair of the component and the step, a\n * public contract.\n */\nexport const stepChecks = <S extends Step>(\n name: string,\n options: CheckOptions<S>,\n runs: Readonly<Partial<Record<S, StepCheck>>>,\n): ReadonlyArray<readonly [Check, CheckFn]> => {\n const has = (Object.entries(runs) as Array<[S, StepCheck | undefined]>).filter(([, run]) => run !== undefined).map(([step]) => step);\n const catalog = options.catalog === true ? { ...options.poll, interval: CATALOG_INTERVAL } : options.catalog;\n if (catalog !== undefined) {\n const missing = Object.keys(options.steps).filter((step) => !has.includes(step as S));\n if (missing.length > 0) {\n throw new Error(`${name}: the nominated checks ${missing.join(\", \")} are not in the catalog of the client (${has.join(\", \")})`);\n }\n }\n const made: Array<readonly [Check, CheckFn]> = [];\n for (const step of has) {\n const run = runs[step] as StepCheck;\n const nominated = step in options.steps;\n if (!nominated && catalog === undefined) continue;\n made.push([\n {\n name: `${name}.${step}`,\n dependency: name,\n step,\n ownConnection: run.ownConnection,\n gates: nominated ? (options.steps[step] ?? null) : null,\n poll: nominated || catalog === undefined ? options.poll : catalog,\n },\n run.run,\n ]);\n }\n return made;\n};\n\n/** This function makes a check outcome from a sent result: only `ok` passes. */\nexport const passes = (sent: Sent<unknown>): Outcome => (sent.outcome === \"ok\" ? \"ok\" : \"error\");\n\n/** This check gives the state of the client, without a round trip. */\nexport const localStateCheck = (ready: () => boolean): StepCheck => ({ ownConnection: true, run: () => (ready() ? \"ok\" : \"error\") });\n\n/**\n * This check sends one call on the connection of the application. A check measures the step at this time.\n * Thus it does not send the call again, and only `ok` passes.\n */\nexport const roundTripCheck = (send: (options: SendOptions) => Promise<Sent<unknown>>): StepCheck => ({\n ownConnection: true,\n run: async (signal) => passes(await send({ signal, reissue: false })),\n});\n\n/**\n * This check opens a new connection each time. It finds a server that refuses connections, but not\n * a stalled connection of the application. A failed dial throws, and the poller counts the throw as an error.\n */\nexport const dialCheck = (dial: DialFn, host: string, port: number): StepCheck => ({\n ownConnection: false,\n run: async (signal) => {\n await dial(host, port, signal);\n return \"ok\" as const;\n },\n});\n\n/** These are the bounds of a client that the core examines in a description. */\nexport interface ClientBounds {\n /** This time bounds the close of the client, in milliseconds. */\n readonly close: number;\n /** This time bounds a call on the connection of the application, in milliseconds. */\n readonly request: number;\n}\n\n/** This function gives the bounds of a client that `clientProblems` examines, from its knobs. */\nexport const clientBounds = (knobs: ClientKnobs): ClientBounds => ({ close: ms(knobs.close_bound), request: ms(knobs.request_timeout) });\n\n/**\n * This function gives the problems of a client in a description:\n * - The client needs the phase \"tear down dependencies\", and its close must fit in the cap of that phase.\n * - A round-trip check must end in one jittered poll (B7, O13).\n */\nexport const clientProblems = (name: string, description: ServiceDescription, bounds: ClientBounds): string[] => {\n const found: string[] = [];\n const teardown = description.shutdown.phases.find((phase) => phase.name === \"tear down dependencies\");\n if (teardown === undefined) found.push(`${name} needs the phase \"tear down dependencies\" to close`);\n else if (bounds.close >= valueIn(teardown.cap, \"ms\"))\n found.push(`${name}'s close_bound of ${bounds.close} ms does not fit in the cap of \"tear down dependencies\"`);\n for (const check of description.checks) {\n if (check.dependency !== name || check.step !== \"round-trip\") continue;\n const slowest = valueIn(check.poll.timeout, \"ms\") + valueIn(check.poll.interval, \"ms\") * (1 + check.poll.jitter);\n if (bounds.request > slowest) found.push(`${name}'s request_timeout outlives one jittered poll of ${check.name} (B7, O13)`);\n }\n return found;\n};\n\n/**\n * This poll is a poll of the checks to start from: each 5 s with a jitter of 20 %, and a timeout of\n * 4 s (B6, O12). Its slowest poll is 4 s + 5 s × 1.2 = 10 s, the slowest poll of the cells of O13.\n * It does not depend on a driver. The starting knobs of each driver fit it.\n */\nexport const STARTING_POLL: Poll = { interval: { value: 5, unit: \"s\" }, jitter: 0.2, timeout: { value: 4, unit: \"s\" } };\n"],"mappings":";;;;;AAsEA,MAAa,mBAA6B,SAAS,IAAI,GAAG;;AAS1D,MAAa,MAAM,WACjB,OAAO,UAAU,aAAa,OAAO,oBAAoB,QAAQ,QAAoB,IAAI;;AAG3F,MAAa,YAAY,WAAuC;CAC9D,MAAM,QAAQ,GAAG,MAAM;CACvB,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AAC1C;;AAGA,MAAa,WAAW,UAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;AAyEzG,MAAa,cACX,YACqF;CACrF,cAAc,QAAQ,gBAAgB;CACtC,WAAW,QAAQ,aAAa;CAChC,eAAe,QAAQ,iBAAiB;CACxC,YAAY,QAAQ,cAAc;AACpC;;AAuBA,MAAa,gBACX,KACA,MACA,aACA,QACA,WACmB;CACnB,IAAI,WAAW,MAAM,aAAa,MAAM;CACxC,KAAK,MAAM,CAAC,OAAO,QAAQ,QAAQ,IAAI,MAAM,OAAO,GAAG;CACvD,OAAO;AACT;;AAGA,MAAa,kBACX,UACA,UACyC;CAAE,GAAG;CAAU,GAAG;AAAK;;AAMlE,MAAa,kBACV,QAA8B,OAAc,UAC5C,MAAM,IAAI,IAAI,WACb,SAAS;CAAE,IAAI,MAAM,IAAI;CAAG,SAAS;CAAU,UAAU;CAAM;CAAM;CAAI;CAAI,G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,QAAQ,MAAM,KAAK,UAAU,IAAI,KAAK,IAAI,MAAM,KAAK;EACzG,IAAI,OAAO,UAAU,SAAS,MAAM,KAAK,GAAG,KAAK,mDAAmD,MAAM,KAAK,WAAW;CAC5H;CACA,OAAO;AACT;;;;;;AAOA,MAAa,gBAAsB;CAAE,UAAU;EAAE,OAAO;EAAG,MAAM;CAAI;CAAG,QAAQ;CAAK,SAAS;EAAE,OAAO;EAAG,MAAM;CAAI;AAAE"}
1
+ {"version":3,"file":"core.js","names":[],"sources":["../../src/client/core.ts"],"sourcesContent":["// The parts of a client wrapper that do not change from one client to the next. Each client entry\n// (`./redis`, `./pg`, `./http-client`, `./websocket`, and each later client of S1) fills them in with its driver. The core gives\n// the shapes of a client, the outcome of a call in three values, the rule that sends a call again,\n// the record of the calls in flight, the bounded close, the checks of the steps of a connection,\n// and the problems of a spec and of a client in a description. It loads only quantity.\n// The section \"Unified or separate\" of docs/S6.md gives each part, and the reason for each part that stays in a driver.\n\nimport type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { quantity, valueIn } from \"@mark1russell7/quantity\";\nimport type { Backoff } from \"../backoff.ts\";\nimport { retrierOn } from \"../retrier.ts\";\nimport type { ServiceBuilder } from \"../builder.ts\";\nimport type { Cancel, Clock } from \"../clock.ts\";\nimport type { Check, Dependency, Gate, ServiceDescription, Step } from \"../description.ts\";\nimport type { Recorder } from \"../events.ts\";\nimport type { Outcome } from \"../latch.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport { mayReissue } from \"../operation.ts\";\nimport type { CheckFn } from \"../poller.ts\";\nimport type { Poll } from \"../timing.ts\";\nimport type { Meeting } from \"./meets.ts\";\n\n/**\n * A sent result is the outcome of a call, in three values (C8):\n * - `ok`: the server answered.\n * - `error`: the call did not apply. The server answered with an error (`reply`), or the call did\n * not leave the client.\n * - `indeterminate`: the call can have reached the server, and nothing tells if it applied.\n */\nexport type Sent<T> =\n | { readonly outcome: \"ok\"; readonly value: T; readonly attempts: number }\n | { readonly outcome: \"error\"; readonly error: string; readonly reply: boolean; readonly attempts: number }\n | { readonly outcome: \"indeterminate\"; readonly error: string; readonly attempts: number };\n\n/** This type is the outcome of one try of a call, before the core counts the tries. */\nexport type Attempt<T = unknown> =\n | { readonly outcome: \"ok\"; readonly value: T }\n | { readonly outcome: \"error\"; readonly error: string; readonly reply: boolean }\n | { readonly outcome: \"indeterminate\"; readonly error: string };\n\n/** Send options tell how the client sends one call. */\nexport interface SendOptions {\n /** This signal abandons the call. A call that left the client is then indeterminate. */\n readonly signal?: AbortSignal | undefined;\n /** False stops the client: it does not send the call again. A check that must fail at once uses it. */\n readonly reissue?: boolean | undefined;\n}\n\n/** A dial function opens a new connection to the server, and reads one reply of the protocol. The `dial` check uses it. */\nexport type DialFn = (host: string, port: number, signal: AbortSignal) => Promise<void>;\n\n/** The steps of a connection that each client gives a check for (B14). A client can add more steps. */\nexport type ClientStep = Extract<Step, \"dial\" | \"round-trip\" | \"local-state\">;\n\n/** Check options tell which checks the client gives the health runtime, and which policy each one controls. */\nexport interface CheckOptions<S extends Step = ClientStep> {\n readonly poll: Poll;\n /** For each step, the policy that its check controls, or null for a check that only reports. A step that is absent has no check. */\n readonly steps: Partial<Record<S, Gate | null>>;\n /**\n * With a catalog, the client gives a check for each step that it has (B19). The steps of `steps` are\n * the nominated checks. Each other step reports only, and polls at the catalog poll. `true` is a poll\n * of 30 s with the jitter and the timeout of `poll`. A nominated step that the client has no check\n * for then fails the attach. Without a catalog, the client gives only the steps of `steps`.\n */\n readonly catalog?: true | Poll | undefined;\n}\n\n/** This interval is the poll of a catalog check that gates nothing (B19). */\nexport const CATALOG_INTERVAL: Quantity = quantity(30, \"s\");\n\n/** A step check is the function of one step, and if it uses the connection of the application. */\nexport interface StepCheck {\n readonly ownConnection: boolean;\n readonly run: CheckFn;\n}\n\n/** This function gives an amount in milliseconds. \"infinite\" is `Infinity`. */\nexport const ms = (amount: Extent): number =>\n amount.value === \"infinite\" ? Number.POSITIVE_INFINITY : valueIn(amount as Quantity, \"ms\");\n\n/** This function gives an amount in milliseconds, or undefined for \"infinite\". Each driver then writes its own form of \"no timer\". */\nexport const finiteMs = (amount: Extent): number | undefined => {\n const value = ms(amount);\n return Number.isFinite(value) ? value : undefined;\n};\n\n/** This function gives the text of an error. */\nexport const message = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * These are the knobs that each client has, by the names of the ordering law. Each driver adds its\n * own knobs. The comments of each driver tell which option of the driver a knob sets.\n */\nexport interface ClientKnobs {\n /** This time bounds a new connection. */\n readonly connect_bound: Quantity;\n /** This time bounds each call on the connection of the application. */\n readonly request_timeout: Quantity;\n /** This time is the idle time of TCP keepalive. Node then sends 10 probes 1 s apart. */\n readonly keepalive_idle: Extent;\n /** This time is the age at which the client replaces a connection. */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the client at the shutdown. */\n readonly close_bound: Quantity;\n /**\n * This time is when the kernel gives up a segment that it retransmits. Node cannot set it, thus\n * the declaration states it for the ordering law (O17), from the platform.\n */\n readonly retrans_giveup_time: Extent;\n}\n\n/** A client spec is the declaration of one client: where it connects, and its knobs. Each driver adds its own fields. */\nexport interface ClientSpec<K extends ClientKnobs = ClientKnobs> {\n readonly host: string;\n readonly port: number;\n readonly password?: string | undefined;\n /** This identifier is the component in the corpus, for example `systems.component.redis`, or null. */\n readonly system: string | null;\n readonly knobs: K;\n /** These operations add to the table of the client, or change it. */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** A factory makes the connection or the pool of a client from the options of its driver. */\nexport type Factory<O, C> = (options: O) => C | Promise<C>;\n\n/** These options make a client. Without them, a client uses its driver, the real clock, and the dial of its protocol. */\nexport interface ClientOptions<F> {\n readonly create?: F | undefined;\n readonly clock?: Clock | undefined;\n /** This function receives each transition of the client, for the prober (D3). */\n readonly record?: Recorder | undefined;\n readonly dial?: DialFn | undefined;\n}\n\n/** A client socket is the part of the socket of a connection that the join of the prober and the bounded close read. */\nexport interface ClientSocket {\n readonly localAddress?: string | undefined;\n readonly localPort?: number | undefined;\n readonly remoteAddress?: string | undefined;\n readonly remotePort?: number | undefined;\n /** This method closes the socket at once. A close of the driver only half-closes it, and a silent peer does not answer that. */\n destroy?(): void;\n}\n\n/**\n * A client join is one connection, at the time when it can serve (D1, D2). The prober joins its\n * kernel records to the server's view of the connection through it. Each driver adds the server's id of the connection.\n */\nexport interface ClientJoin {\n readonly generation: number;\n /** This time is when the connection became ready, in milliseconds on the monotonic clock. */\n readonly at: number;\n readonly localAddress: string | null;\n readonly localPort: number | null;\n readonly remoteAddress: string | null;\n readonly remotePort: number | null;\n}\n\n/** This function gives the addresses and the ports of a socket for a join. Each one is null when the socket does not give it. */\nexport const socketEnds = (\n socket: ClientSocket | undefined,\n): Pick<ClientJoin, \"localAddress\" | \"localPort\" | \"remoteAddress\" | \"remotePort\"> => ({\n localAddress: socket?.localAddress ?? null,\n localPort: socket?.localPort ?? null,\n remoteAddress: socket?.remoteAddress ?? null,\n remotePort: socket?.remotePort ?? null,\n});\n\n/** A client is a dependency of a service: its declaration, its handle and its checks. Each driver adds the method that sends a call. */\nexport interface Client<S extends Step = ClientStep, J extends ClientJoin = ClientJoin> {\n readonly name: string;\n /** This declaration goes to `svc.dependency(name, declaration, handle)`. */\n readonly declaration: Omit<Dependency, \"name\">;\n readonly handle: DependencyHandle;\n /** These are the manifestations that the client can meet, and the detectors of each (E9). */\n readonly meets: readonly Meeting[];\n /** This text is the state of the client, as the machine document of the client names it. */\n readonly status: string;\n /** These are the connections of the client, the latest last. */\n readonly joins: readonly J[];\n /** This method gives the checks of the client and their functions, for `svc.check(check, run)`. */\n checks(options: CheckOptions<S>): ReadonlyArray<readonly [Check, CheckFn]>;\n /** This method declares the client in a service: its dependency, its handle and its checks. */\n attach(svc: ServiceBuilder, options: CheckOptions<S>): ServiceBuilder;\n /** This method gives the problems of the client in a description: a close that does not fit in its phase, for example. */\n problems(description: ServiceDescription): string[];\n}\n\n/** This function declares a client in a service: its dependency, its handle, and each of its checks. */\nexport const attachClient = (\n svc: ServiceBuilder,\n name: string,\n declaration: Omit<Dependency, \"name\">,\n handle: DependencyHandle,\n checks: ReadonlyArray<readonly [Check, CheckFn]>,\n): ServiceBuilder => {\n svc.dependency(name, declaration, handle);\n for (const [check, run] of checks) svc.check(check, run);\n return svc;\n};\n\n/** This function gives the table of operations of a client: the defaults of its driver, then the operations of its spec. */\nexport const operationTable = (\n defaults: Readonly<Record<string, Operation>>,\n more: Readonly<Record<string, Operation>> | undefined,\n): Readonly<Record<string, Operation>> => ({ ...defaults, ...more });\n\n/** A client recorder gives one transition of a client to the recorder of the options, for the prober (D3). */\nexport type ClientRecorder = (from: string, to: string, on: string, detail?: string) => void;\n\n/** This function makes the recorder of a client. Each event has the machine \"client\", and the name of the client as its instance. */\nexport const clientRecorder =\n (record: Recorder | undefined, clock: Clock, name: string): ClientRecorder =>\n (from, to, on, detail) =>\n record?.({ at: clock.now(), machine: \"client\", instance: name, from, to, on, ...(detail === undefined ? {} : { detail }) });\n\n/** This function gives the outcome of a call that did not leave the client. It is certain: the call did not apply. */\nexport const notSent = (error: string): Attempt<never> => ({ outcome: \"error\", error, reply: false });\n\n/** A settle function gives the outcome of a call in flight. A driver can give a cause, for example the error that ends a client of a pool. */\nexport type Settle<T = unknown> = (value: Attempt<T>, cause?: Error) => void;\n\n/**\n * This record holds the calls in flight of a client. Each call settles one time. A call that the\n * caller abandons after it left the client is indeterminate, because a sent call cannot be\n * cancelled (principle 9). The close and a closed connection settle each call that stays (C10).\n */\nexport interface InFlight {\n /** This number is the count of the calls in flight. */\n readonly size: number;\n /**\n * This method sends one call, and records it until it settles. `start` sends the call, and gives\n * its outcome to `settle`. `after` operates one time, after the call settles and before its promise resolves.\n */\n track<T>(\n signal: AbortSignal | undefined,\n abandoned: string,\n start: (settle: Settle<T>) => void,\n after?: (value: Attempt<T>, cause: Error | undefined) => void,\n ): Promise<Attempt<T>>;\n /** This method settles each call in flight as indeterminate, with this error. */\n settleAll(error: string): void;\n /** This method resolves when no call is in flight. A close that waits for its calls uses it in its bound. */\n idle(): Promise<void>;\n}\n\n/** This function makes the record of the calls in flight of a client. */\nexport const inFlight = (): InFlight => {\n const closes = new Set<(error: string) => void>();\n const waiters = new Set<() => void>();\n const wake = (): void => {\n if (closes.size > 0) return;\n for (const waiter of [...waiters]) waiter();\n waiters.clear();\n };\n return {\n get size() {\n return closes.size;\n },\n idle: () =>\n new Promise<void>((resolve) => {\n if (closes.size === 0) resolve();\n else waiters.add(resolve);\n }),\n track<T>(\n signal: AbortSignal | undefined,\n abandoned: string,\n start: (settle: Settle<T>) => void,\n after?: (value: Attempt<T>, cause: Error | undefined) => void,\n ): Promise<Attempt<T>> {\n return new Promise<Attempt<T>>((resolve) => {\n let settled = false;\n const settle: Settle<T> = (value, cause) => {\n if (settled) return;\n settled = true;\n closes.delete(close);\n signal?.removeEventListener(\"abort\", aborted);\n after?.(value, cause);\n resolve(value);\n wake();\n };\n const close = (error: string): void => settle({ outcome: \"indeterminate\", error }, new Error(error));\n const aborted = (): void => close(abandoned);\n closes.add(close);\n signal?.addEventListener(\"abort\", aborted, { once: true });\n start(settle);\n });\n },\n settleAll(error) {\n for (const close of [...closes]) close(error);\n },\n };\n};\n\n/**\n * This function sends one call through the record of the calls in flight, with a timer of the\n * wrapper. A driver with no timer for its call uses it: amqplib, and the agent of Node. At `bound`\n * milliseconds the call is indeterminate with the error `timedOut`, because it left the client.\n * The timer stops when the call settles, before `after` operates.\n */\nexport const trackWithTimer = <T>(\n flight: InFlight,\n clock: Clock,\n bound: number,\n signal: AbortSignal | undefined,\n abandoned: string,\n timedOut: string,\n start: (settle: Settle<T>) => void,\n after?: (value: Attempt<T>, cause: Error | undefined) => void,\n): Promise<Attempt<T>> => {\n let stop: Cancel = () => {};\n return flight.track<T>(\n signal,\n abandoned,\n (settle) => {\n // the caller awaits the attempt, thus its bound keeps the process alive (SYS-126)\n stop = clock.after(bound, () => settle({ outcome: \"indeterminate\", error: timedOut }));\n start(settle);\n },\n (value, cause) => {\n stop();\n after?.(value, cause);\n },\n );\n};\n\n/**\n * This function waits for the work of a close, for `bound` milliseconds at most. It gives true when\n * the work ended in its bound, with a success or a failure. It gives false at the bound. The driver\n * then destroys each socket that stays, because a silent server does not close its half.\n */\nexport const withinBound = (clock: Clock, bound: number, work: Promise<unknown>): Promise<boolean> => {\n const done = work.then(\n () => true,\n () => true,\n );\n let cancel: Cancel = () => {};\n const timer = new Promise<boolean>((resolve) => {\n // the caller awaits this bound, thus it keeps the process alive (SYS-126)\n cancel = clock.after(bound, () => resolve(false));\n });\n return Promise.race([done, timer]).then((ended) => {\n cancel();\n return ended;\n });\n};\n\n/**\n * A ready wait holds the calls that wait for a ready connection before their second try. A client\n * that connects again by itself uses it: Redis and RabbitMQ.\n */\nexport interface ReadyWait {\n /** This method waits until the client is ready, for `within` milliseconds at most. It gives true when the client is ready. */\n wait(within: number, signal?: AbortSignal): Promise<boolean>;\n /** This method ends each wait with true. The client uses it when its connection is ready. */\n wake(): void;\n}\n\n/** This function makes the ready wait of a client. The function `ready` tells if the client is ready. */\nexport const readyWait = (clock: Clock, ready: () => boolean): ReadyWait => {\n const waiters = new Set<() => void>();\n return {\n wait: (within, signal) =>\n new Promise((resolve) => {\n if (ready()) {\n resolve(true);\n return;\n }\n let cancel: Cancel = () => {};\n const done = (value: boolean): void => {\n waiters.delete(wake);\n cancel();\n signal?.removeEventListener(\"abort\", aborted);\n resolve(value);\n };\n const wake = (): void => done(true);\n const aborted = (): void => done(false);\n waiters.add(wake);\n // the caller awaits the readiness, thus this bound keeps the process alive (SYS-126)\n cancel = clock.after(within, () => done(ready()));\n signal?.addEventListener(\"abort\", aborted, { once: true });\n }),\n wake() {\n for (const wake of [...waiters]) wake();\n },\n };\n};\n\n/** These are the knobs of a client that connects again by itself, after a delay that doubles. */\nexport interface RetryKnobs {\n /** This time is the first delay before a new try to connect. The delay doubles after each try. */\n readonly retry_base: Quantity;\n /** This time is the most that one delay can be, before its jitter. */\n readonly retry_cap: Quantity;\n}\n\n/**\n * This function gives the backoff of the tries to connect: from `retry_base`, doubling to\n * `retry_cap`, each with a jitter up to the base. The client rounds each delay to a whole millisecond.\n */\nexport const retryBackoff = (knobs: RetryKnobs): Backoff => ({\n base: ms(knobs.retry_base),\n factor: 2,\n cap: ms(knobs.retry_cap),\n jitter: { kind: \"add\", amount: ms(knobs.retry_base) },\n});\n\n/**\n * A retry schedule holds the next try to connect, for a client that connects again by itself. It\n * counts the tries since the last join. Each delay comes from the backoff, rounded to a whole millisecond.\n */\nexport interface RetrySchedule {\n /** This count is the number of tries since the last reset. */\n readonly tries: number;\n /** This method counts one more try, and starts `due` after the delay of that try. It stops a try that waits. */\n schedule(due: () => void): void;\n /** This method stops the try that waits. The close uses it. */\n cancel(): void;\n /** This method sets the count of tries to zero. The client uses it at each join. */\n reset(): void;\n}\n\n/** This function makes the retry schedule of a client, from its backoff and its random numbers. RabbitMQ and WebSocket use it. */\nexport const retrySchedule = (clock: Clock, backoff: Backoff, random: () => number): RetrySchedule => {\n // the public retrier does the same work: the schedule only names its count `tries`\n const retry = retrierOn(clock, backoff, random);\n return {\n get tries() {\n return retry.attempts;\n },\n schedule(due) {\n retry.schedule(due);\n },\n cancel: () => retry.cancel(),\n reset: () => retry.reset(),\n };\n};\n\n/** This function gives the problems of the retry knobs: the cap must not be below the base. */\nexport const retryProblems = (name: string, knobs: RetryKnobs): string[] =>\n ms(knobs.retry_cap) < ms(knobs.retry_base) ? [`${name}'s retry_cap is below its retry_base`] : [];\n\n/**\n * This function gives the problem of a count of misses that is not a whole number above zero. A\n * client that closes its connection after a count of heartbeat misses uses it. `mechanism` names the heartbeat, for example \"watchdog\".\n */\nexport const missesProblems = (name: string, misses: number, mechanism: string): string[] =>\n Number.isInteger(misses) && misses >= 1 ? [] : [`${name}'s ${mechanism} closes the connection after ${misses} misses, not a whole number above zero`];\n\n/** This function gives the problems of the knobs of a spec that each client has: each knob must be a time of zero or more. */\nexport const timeProblems = (name: string, knobs: object): string[] => {\n const problems: string[] = [];\n for (const [knob, amount] of Object.entries(knobs) as Array<[string, Extent]>) {\n if (amount.value !== \"infinite\" && !(ms(amount) >= 0)) problems.push(`${name}'s ${knob} is not a time of zero or more`);\n }\n return problems;\n};\n\n/** This function writes a bound for a driver that reads 0 as no timer: \"infinite\" is 0. */\nexport const orZero = (amount: Extent): number => finiteMs(amount) ?? 0;\n\n/** This function tells if an amount is a whole number of milliseconds. \"infinite\" is whole. */\nexport const wholeMs = (amount: Extent): boolean => amount.value === \"infinite\" || Number.isInteger(ms(amount));\n\n/** This function tells if an amount is a whole number of seconds. \"infinite\" is whole. */\nexport const wholeSeconds = (amount: Extent): boolean =>\n amount.value === \"infinite\" || Number.isInteger(valueIn(amount as Quantity, \"s\"));\n\n/** These are the knobs of a spec that `zeroProblems` and `wholeProblems` examine, by their kind. */\nexport interface KnobKinds {\n /** These knobs must be a finite time above zero, because the driver reads 0 as no bound. */\n readonly bounded?: readonly string[] | undefined;\n /** These knobs can be \"infinite\", which the driver writes as 0. Thus 0 itself is not a bound. */\n readonly open?: readonly string[] | undefined;\n /** These knobs go to the driver in whole milliseconds. */\n readonly millis?: readonly string[] | undefined;\n /** These knobs go to the driver or to Node in whole seconds. */\n readonly seconds?: readonly string[] | undefined;\n}\n\nconst knobOf = (knobs: object, knob: string): Extent => (knobs as Record<string, Extent>)[knob]!;\n\n/**\n * This function gives the problems of the knobs of a driver that reads 0 as no timer. pg and the\n * MongoDB driver read 0 so. A bounded knob must be a finite time above zero. An open knob can be\n * \"infinite\", and 0 is then a mistake.\n */\nexport const zeroProblems = (name: string, driver: string, knobs: object, kinds: KnobKinds): string[] => {\n const problems: string[] = [];\n for (const knob of kinds.bounded ?? []) {\n const value = ms(knobOf(knobs, knob));\n if (!(value > 0) || !Number.isFinite(value)) problems.push(`${name}'s ${knob} is not a finite time above zero: ${driver} reads 0 as no bound`);\n }\n for (const knob of kinds.open ?? []) {\n const amount = knobOf(knobs, knob);\n if (amount.value !== \"infinite\" && !(ms(amount) > 0)) problems.push(`${name}'s ${knob} is zero: give \"infinite\" for no bound`);\n }\n return problems;\n};\n\n/** This function gives the problems of the knobs that a driver takes in whole milliseconds or in whole seconds. */\nexport const wholeProblems = (name: string, knobs: object, kinds: KnobKinds): string[] => [\n ...(kinds.millis ?? []).filter((knob) => !wholeMs(knobOf(knobs, knob))).map((knob) => `${name}'s ${knob} is not a whole number of milliseconds`),\n ...(kinds.seconds ?? []).filter((knob) => !wholeSeconds(knobOf(knobs, knob))).map((knob) => `${name}'s ${knob} is not a whole number of seconds`),\n];\n\n/** This function gives the problems of the sizes of a pool: at most `max` connections, and `min` from 0 to `max`. */\nexport const poolProblems = (name: string, pool: { readonly max: number; readonly min: number }): string[] => {\n const problems: string[] = [];\n if (!Number.isInteger(pool.max) || pool.max < 1) problems.push(`${name}'s pool has a max of ${pool.max}, not a whole number above zero`);\n if (!Number.isInteger(pool.min) || pool.min < 0 || pool.min > pool.max)\n problems.push(`${name}'s pool has a min of ${pool.min}, not a whole number from 0 to its max`);\n return problems;\n};\n\n/**\n * This function gives the problem O07 of a client whose server has a deadline, or null. The client\n * must wait longer than the deadline of the server. Then the server ends a slow call with an error\n * first. Otherwise the client gives up first, and the server goes on with the call. `call` names\n * the call of the server, for example a statement.\n */\nexport const deadlineProblem = (name: string, request: Quantity, deadline: Extent, call: string): string | null =>\n deadline.value !== \"infinite\" && ms(request) <= ms(deadline)\n ? `${name}'s request_timeout is not above its statement_timeout: the server goes on with a ${call} that the client gave up (O07)`\n : null;\n\n/**\n * This function gives the problem O01 of a client pool, or null. The pool must close an idle\n * connection before its server does. Otherwise a request can go on a connection that the server\n * closed. A server that keeps an idle connection with no bound gives no problem. `knob` names the\n * idle time of the client: `pool_idle_expiry` of a pool, or `client_idle_timeout` of a gRPC channel.\n */\nexport const idleCloseProblem = (name: string, expiry: Extent, close: Extent, knob = \"pool_idle_expiry\"): string | null =>\n close.value !== \"infinite\" && !(ms(expiry) < ms(close))\n ? `${name}'s ${knob} is not below the idle close of its server: a request can go on a connection that the server closed (O01)`\n : null;\n\n/**\n * This function gives the problems of the timers that the wrapper has, because its driver has none.\n * Each one must be a finite time above zero. `bounds` gives what each knob bounds, for example \"a call\".\n */\nexport const wrapperTimerProblems = (name: string, knobs: object, bounds: Readonly<Record<string, string>>): string[] =>\n Object.entries(bounds)\n .filter(([knob]) => {\n const value = ms(knobOf(knobs, knob));\n return !(value > 0) || !Number.isFinite(value);\n })\n .map(([knob, what]) => `${name}'s ${knob} is not a finite time above zero: the timer of the wrapper is the only bound of ${what}`);\n\n/** This function gives the problem of a finite connection age, for a client that does not replace a connection at an age. `reason` tells why. */\nexport const ageProblems = (name: string, knobs: Pick<ClientKnobs, \"max_connection_age\">, reason: string): string[] =>\n knobs.max_connection_age.value === \"infinite\" ? [] : [`${name}'s max_connection_age is not \"infinite\": ${reason}`];\n\n/** This function gives the problem of a keepalive that is not a finite time above zero, for a driver that always turns keepalive on. */\nexport const keepaliveOnProblems = (name: string, knobs: Pick<ClientKnobs, \"keepalive_idle\">, driver: string): string[] => {\n const value = ms(knobs.keepalive_idle);\n return value > 0 && Number.isFinite(value) ? [] : [`${name}'s keepalive_idle is not a finite time above zero: ${driver} always turns keepalive on`];\n};\n\n/** These are the parts of one call that the core uses to send it, and to send it again. */\nexport interface Reissue<T> {\n readonly clock: Clock;\n /** This time bounds the call and its second try, in milliseconds from its start. */\n readonly bound: number;\n /** This operation is the declaration of the call, or undefined when the table does not name it. */\n readonly operation: Operation | undefined;\n readonly options: SendOptions;\n /** This function makes one try. Its signal ends the try. */\n readonly attempt: (signal: AbortSignal | undefined) => Promise<Attempt<T>>;\n /** This function operates before the second try, with the time that is left. False stops the second try. */\n readonly beforeAgain?: ((left: number, signal: AbortSignal | undefined) => Promise<boolean>) | undefined;\n /** This function receives the start of a second try, for the record of the client. */\n readonly onReissue: () => void;\n}\n\n/**\n * This function sends a call, and gives its outcome in three values. It sends again only an\n * idempotent operation, one time at most, after an outcome that is not certain. A reply of the\n * server is certain. The second try ends at the bound of the call, not one bound after its own start.\n */\nexport const sendWithReissue = async <T>(call: Reissue<T>): Promise<Sent<T>> => {\n const { clock, bound } = call;\n const { signal } = call.options;\n const operation = call.options.reissue === false ? undefined : call.operation;\n const started = clock.now();\n const first = await call.attempt(signal);\n if (first.outcome === \"ok\") return { outcome: \"ok\", value: first.value, attempts: 1 };\n const again =\n !(first.outcome === \"error\" && first.reply) &&\n operation !== undefined &&\n signal?.aborted !== true &&\n mayReissue(operation, quantity((clock.now() - started) / 1000, \"s\"));\n const left = bound - (clock.now() - started);\n if (!again || left <= 0) return { ...first, attempts: 1 };\n if (call.beforeAgain !== undefined && !(await call.beforeAgain(left, signal))) return { ...first, attempts: 1 };\n call.onReissue();\n const end = new AbortController();\n // the caller awaits the second try, thus its bound keeps the process alive (SYS-126)\n const stop = clock.after(Math.max(0, bound - (clock.now() - started)), () => end.abort());\n const forward = (): void => end.abort();\n signal?.addEventListener(\"abort\", forward, { once: true });\n const second = await call.attempt(end.signal);\n stop();\n signal?.removeEventListener(\"abort\", forward);\n return second.outcome === \"ok\" ? { outcome: \"ok\", value: second.value, attempts: 2 } : { ...second, attempts: 2 };\n};\n\n/**\n * This function gives the checks of a client, for `svc.check(check, run)`. Without a catalog, it gives\n * a check for each step that the options name, when the client has a function for that step. With a\n * catalog, it gives a check for each step of the client. It then throws for a nominated step that the\n * client does not have (B19). The name of each check is the pair of the component and the step, a\n * public contract.\n */\nexport const stepChecks = <S extends Step>(\n name: string,\n options: CheckOptions<S>,\n runs: Readonly<Partial<Record<S, StepCheck>>>,\n): ReadonlyArray<readonly [Check, CheckFn]> => {\n const has = (Object.entries(runs) as Array<[S, StepCheck | undefined]>).filter(([, run]) => run !== undefined).map(([step]) => step);\n const catalog = options.catalog === true ? { ...options.poll, interval: CATALOG_INTERVAL } : options.catalog;\n if (catalog !== undefined) {\n const missing = Object.keys(options.steps).filter((step) => !has.includes(step as S));\n if (missing.length > 0) {\n throw new Error(`${name}: the nominated checks ${missing.join(\", \")} are not in the catalog of the client (${has.join(\", \")})`);\n }\n }\n const made: Array<readonly [Check, CheckFn]> = [];\n for (const step of has) {\n const run = runs[step] as StepCheck;\n const nominated = step in options.steps;\n if (!nominated && catalog === undefined) continue;\n made.push([\n {\n name: `${name}.${step}`,\n dependency: name,\n step,\n ownConnection: run.ownConnection,\n gates: nominated ? (options.steps[step] ?? null) : null,\n poll: nominated || catalog === undefined ? options.poll : catalog,\n },\n run.run,\n ]);\n }\n return made;\n};\n\n/** This function makes a check outcome from a sent result: only `ok` passes. */\nexport const passes = (sent: Sent<unknown>): Outcome => (sent.outcome === \"ok\" ? \"ok\" : \"error\");\n\n/** This check gives the state of the client, without a round trip. */\nexport const localStateCheck = (ready: () => boolean): StepCheck => ({ ownConnection: true, run: () => (ready() ? \"ok\" : \"error\") });\n\n/**\n * This check sends one call on the connection of the application. A check measures the step at this time.\n * Thus it does not send the call again, and only `ok` passes.\n */\nexport const roundTripCheck = (send: (options: SendOptions) => Promise<Sent<unknown>>): StepCheck => ({\n ownConnection: true,\n run: async (signal) => passes(await send({ signal, reissue: false })),\n});\n\n/**\n * This check opens a new connection each time. It finds a server that refuses connections, but not\n * a stalled connection of the application. A failed dial throws, and the poller counts the throw as an error.\n */\nexport const dialCheck = (dial: DialFn, host: string, port: number): StepCheck => ({\n ownConnection: false,\n run: async (signal) => {\n await dial(host, port, signal);\n return \"ok\" as const;\n },\n});\n\n/** These are the bounds of a client that the core examines in a description. */\nexport interface ClientBounds {\n /** This time bounds the close of the client, in milliseconds. */\n readonly close: number;\n /** This time bounds a call on the connection of the application, in milliseconds. */\n readonly request: number;\n}\n\n/** This function gives the bounds of a client that `clientProblems` examines, from its knobs. */\nexport const clientBounds = (knobs: ClientKnobs): ClientBounds => ({ close: ms(knobs.close_bound), request: ms(knobs.request_timeout) });\n\n/**\n * This function gives the problems of a client in a description:\n * - The client needs the phase \"tear down dependencies\", and its close must fit in the cap of that phase.\n * - A round-trip check must end in one jittered poll (B7, O13).\n */\nexport const clientProblems = (name: string, description: ServiceDescription, bounds: ClientBounds): string[] => {\n const found: string[] = [];\n const teardown = description.shutdown.phases.find((phase) => phase.name === \"tear down dependencies\");\n if (teardown === undefined) found.push(`${name} needs the phase \"tear down dependencies\" to close`);\n else if (bounds.close >= valueIn(teardown.cap, \"ms\"))\n found.push(`${name}'s close_bound of ${bounds.close} ms does not fit in the cap of \"tear down dependencies\"`);\n for (const check of description.checks) {\n if (check.dependency !== name || check.step !== \"round-trip\") continue;\n const slowest = valueIn(check.poll.timeout, \"ms\") + valueIn(check.poll.interval, \"ms\") * (1 + check.poll.jitter);\n if (bounds.request > slowest) found.push(`${name}'s request_timeout outlives one jittered poll of ${check.name} (B7, O13)`);\n }\n return found;\n};\n\n/**\n * This poll is a poll of the checks to start from: each 5 s with a jitter of 20 %, and a timeout of\n * 4 s (B6, O12). Its slowest poll is 4 s + 5 s × 1.2 = 10 s, the slowest poll of the cells of O13.\n * It does not depend on a driver. The starting knobs of each driver fit it.\n */\nexport const STARTING_POLL: Poll = { interval: { value: 5, unit: \"s\" }, jitter: 0.2, timeout: { value: 4, unit: \"s\" } };\n"],"mappings":";;;;;AAsEA,MAAa,mBAA6B,SAAS,IAAI,GAAG;;AAS1D,MAAa,MAAM,WACjB,OAAO,UAAU,aAAa,OAAO,oBAAoB,QAAQ,QAAoB,IAAI;;AAG3F,MAAa,YAAY,WAAuC;CAC9D,MAAM,QAAQ,GAAG,MAAM;CACvB,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AAC1C;;AAGA,MAAa,WAAW,UAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;AAyEzG,MAAa,cACX,YACqF;CACrF,cAAc,QAAQ,gBAAgB;CACtC,WAAW,QAAQ,aAAa;CAChC,eAAe,QAAQ,iBAAiB;CACxC,YAAY,QAAQ,cAAc;AACpC;;AAuBA,MAAa,gBACX,KACA,MACA,aACA,QACA,WACmB;CACn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,wBAAwB;CACpG,IAAI,aAAa,KAAA,GAAW,MAAM,KAAK,GAAG,KAAK,mDAAmD;MAC7F,IAAI,OAAO,SAAS,QAAQ,SAAS,KAAK,IAAI,GACjD,MAAM,KAAK,GAAG,KAAK,oBAAoB,OAAO,MAAM,wDAAwD;CAC9G,KAAK,MAAM,SAAS,YAAY,QAAQ;EACtC,IAAI,MAAM,eAAe,QAAQ,MAAM,SAAS,cAAc;EAC9D,MAAM,UAAU,QAAQ,MAAM,KAAK,SAAS,IAAI,IAAI,QAAQ,MAAM,KAAK,UAAU,IAAI,KAAK,IAAI,MAAM,KAAK;EACzG,IAAI,OAAO,UAAU,SAAS,MAAM,KAAK,GAAG,KAAK,mDAAmD,MAAM,KAAK,WAAW;CAC5H;CACA,OAAO;AACT;;;;;;AAOA,MAAa,gBAAsB;CAAE,UAAU;EAAE,OAAO;EAAG,MAAM;CAAI;CAAG,QAAQ;CAAK,SAAS;EAAE,OAAO;EAAG,MAAM;CAAI;AAAE"}
package/build/clock.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Cancel, Clock, PlatformClockOptions, platformClock, realClock } from "@mark1russell7/algebra/clock";
2
- export { type Cancel, type Clock, type PlatformClockOptions, platformClock, realClock };
1
+ import { Cancel, Clock, PlatformClockOptions, platformClock, realClock, unrefClock } from "@mark1russell7/algebra/clock";
2
+ export { type Cancel, type Clock, type PlatformClockOptions, platformClock, realClock, unrefClock };
package/build/clock.js CHANGED
@@ -1 +1 @@
1
- export { platformClock, realClock } from "@mark1russell7/algebra/clock";
1
+ export { platformClock, realClock, unrefClock } from "@mark1russell7/algebra/clock";
@@ -1,4 +1,4 @@
1
- import { platformClock, realClock } from "./clock.js";
1
+ import { realClock } from "./clock.js";
2
2
  import { ownStream } from "./drains.js";
3
3
  import { fakeClock } from "./fakes.js";
4
4
  import { pushedSource } from "./http/fake-server.js";
@@ -63,8 +63,7 @@ const trackedLifecycle = (clock) => {
63
63
  };
64
64
  };
65
65
  const realNow = () => performance.now();
66
- const alive = platformClock();
67
- const turn = () => delay(alive, 0);
66
+ const turn = () => delay(realClock, 0);
68
67
  /** This function waits on the real clock, until the test is true or the bound ends. It gives the test at the end. */
69
68
  const within = async (bound, test) => {
70
69
  const end = realNow() + bound;
@@ -133,7 +132,7 @@ const transportConformance = (make, options = {}) => {
133
132
  const timeOf = () => {
134
133
  if (!fake) return {
135
134
  clock: realClock,
136
- pass: (ms) => delay(alive, ms)
135
+ pass: (ms) => delay(realClock, ms)
137
136
  };
138
137
  const clock = fakeClock();
139
138
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"conformance.js","names":[],"sources":["../src/conformance.ts"],"sourcesContent":["import { delay } from \"@mark1russell7/algebra/clock\";\nimport type { Clock } from \"./clock.ts\";\nimport { platformClock, realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { ownStream } from \"./drains.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport { pushedSource } from \"./http/fake-server.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.ts\";\nimport type { RequestEnd, RequestFn, Tracker } from \"./requests.ts\";\nimport { tracker } from \"./requests.ts\";\n\n/** A held work is one unit of work that stays in flight until the test releases it. */\nexport interface HeldWork {\n /** This method lets the work end. Its promise ends when the caller of the work has its answer, or its error. */\n release(): Promise<void>;\n /** This flag tells if the work got the cooperative abort of the drain. */\n readonly aborted: boolean;\n}\n\n/**\n * A transport subject is a transport and the client side of its work. The kit offers work through\n * it, holds work in flight through it, and reads the count of the transport.\n */\nexport interface TransportSubject {\n readonly impl: TransportImpl;\n /** This lifecycle goes to `start()`. Without it, the kit gives a detached lifecycle. */\n readonly life?: Lifecycle | undefined;\n /** This method offers one unit of new work. It gives true when the transport took it, and false when it refused it. */\n offer(): Promise<boolean>;\n /** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */\n hold(): Promise<HeldWork>;\n /**\n * This method sends one call through the transport, for the stream cases (option `streams`). The\n * handler of the call gives `call.work` to `life.request(call.controller, call.route, ...)` of the\n * lifecycle of the start, and writes its stream to the caller. It gives what the caller sees.\n */\n call?(call: StreamCall): CallerView | Promise<CallerView>;\n /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\n}\n\n/** A stream call is one request of the stream cases. The kit gives its work, and the subject sends it. */\nexport interface StreamCall {\n /** This name is the controller of the request in the lifecycle of the kit. */\n readonly controller: string;\n /** This name is the route of the request in the lifecycle of the kit. */\n readonly route: string;\n /** This function is the work of the request: one value, or a stream of values. */\n readonly work: RequestFn<unknown>;\n /** True tells that the answer is a stream of items. False tells that the answer is unary: one status and one value. */\n readonly stream: boolean;\n}\n\n/** A seen end is the end of a call, as its caller read it. */\nexport interface SeenEnd {\n readonly kind: RequestEnd[\"kind\"];\n /**\n * True tells that the end came in the body of the answer, after its status, for example as the\n * last line of a stream. False tells that the end came as the status of the answer.\n */\n readonly inBand: boolean;\n}\n\n/** A caller view is what the caller of a call has read so far. The kit reads it again until it changes. */\nexport interface CallerView {\n /** These values are the items that the caller read, in their sequence. */\n readonly items: readonly unknown[];\n /** This end is the end that the caller read, or null while the call is open. */\n readonly end: SeenEnd | null;\n}\n\n/**\n * This function gives a detached lifecycle: a lifecycle with no service, for the start of a\n * transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request\n * and each use of its health throws, because no service declares a route.\n */\nexport const detachedLifecycle = (): Lifecycle => {\n const none = (): never => {\n throw new Error(\"a detached lifecycle has no service: give the transport the lifecycle of a service\");\n };\n const health = { verdict: none, probe: none, metrics: none, subscribe: none, forceFail: none, drain: none, stop: none } as Health;\n return {\n health,\n state: \"running\",\n exitCode: null,\n errors: [],\n started: Promise.resolve(),\n done: new Promise<number>(() => {}),\n signal: new AbortController().signal,\n shutdown: none,\n request: none,\n inFlight: () => 0,\n keepAlive: () => true,\n };\n};\n\n/** These names are the controller and the route of each call of the stream cases. */\nconst CALLS = { controller: \"conformance\", route: \"call\" } as const;\n\n/**\n * This function gives a lifecycle with request tracking for the stream cases, and its tracker. The\n * kit uses the tracker for the stages of the shutdown, as the lifecycle of a service does. Its\n * requests are not idempotent, and it admits each request until the stop of its intake.\n */\nconst trackedLifecycle = (clock: Clock): { readonly life: Lifecycle; readonly requests: Tracker } => {\n const requests = tracker([{ name: CALLS.controller, requires: [], routes: { [CALLS.route]: { idempotent: false } } }], clock, () => null);\n const life: Lifecycle = {\n ...detachedLifecycle(),\n // the lifecycle owns each stream that it makes, thus the drain of the transport waits for the end of its cut\n request: (controller, route, work, options) => ownStream(requests.request(controller, route, work, options), life),\n inFlight: (controller) => requests.inFlight(controller),\n };\n return { life, requests };\n};\n\n/** A subject factory makes a new subject for each case, on the clock of the case. */\nexport type SubjectFactory = (clock: Clock) => TransportSubject | Promise<TransportSubject>;\n\n/** A conformance record is one measurement of a case, for the raw records of a run in CI. */\nexport interface ConformanceRecord {\n readonly case: string;\n readonly what: string;\n /** This time is the limit of the contract, in milliseconds. */\n readonly expected: number;\n /** This time is what the case measured, in milliseconds of the real clock. */\n readonly measured: number;\n}\n\n/** These options tune the conformance kit. */\nexport interface ConformanceOptions {\n /** This name goes before the name of each case. */\n readonly name?: string | undefined;\n /** This clock moves the cases: `fake` gives exact and fast cases, and `real` measures the timing. The default is `fake`. */\n readonly clock?: \"fake\" | \"real\" | undefined;\n /** This time is the cap of each drain of the cases, in milliseconds. The default is 1000. */\n readonly cap?: number | undefined;\n /** This time is the most that a close can take, in milliseconds of the real clock. The default is 1000. */\n readonly closeBound?: number | undefined;\n /** This time is the most that an event can take to reach the transport, in real milliseconds. The default is 100. */\n readonly slack?: number | undefined;\n /** False tells that the work of the transport cannot see the cooperative abort. The default is true. */\n readonly cooperative?: boolean | undefined;\n /** This count is the number of works that the count case holds. The default is 3. */\n readonly holds?: number | undefined;\n /**\n * True adds the stream cases (S6 D4). Then the subject gives `call`, and the kit gives the\n * transport a lifecycle with request tracking. The default is false.\n */\n readonly streams?: boolean | undefined;\n /** This function receives each measurement, for the raw records of a run. */\n readonly record?: ((record: ConformanceRecord) => void) | undefined;\n}\n\ninterface Time {\n readonly clock: Clock;\n pass(ms: number): Promise<void>;\n}\n\ninterface Tracked {\n readonly settled: boolean;\n readonly error: unknown;\n readonly failed: boolean;\n}\n\nconst realNow = (): number => performance.now();\n// The waits of the case keep the process alive, as a plain setTimeout does. A timer of realClock does not.\nconst alive = platformClock();\nconst turn = (): Promise<void> => delay(alive, 0);\n\n/** This function waits on the real clock, until the test is true or the bound ends. It gives the test at the end. */\nconst within = async (bound: number, test: () => boolean): Promise<boolean> => {\n const end = realNow() + bound;\n for (;;) {\n if (test()) return true;\n if (realNow() > end) return test();\n await turn();\n }\n};\n\n/** This function lets the events that are ready reach the transport, with no move of the clock of the case. */\nconst quiet = async (): Promise<void> => {\n for (let at = 0; at < 8; at += 1) await turn();\n};\n\n/** This function uses a method of the transport, and gives a throw of the method as a rejection. */\nconst attempt = (call: () => Promise<void> | void): Promise<void> => {\n try {\n return Promise.resolve(call());\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nconst track = (promise: Promise<unknown>): Tracked => {\n const state = { settled: false, error: undefined as unknown, failed: false };\n promise.then(\n () => {\n state.settled = true;\n },\n (error: unknown) => {\n state.settled = true;\n state.failed = true;\n state.error = error;\n },\n );\n return state;\n};\n\n/**\n * This function generates the conformance cases of a transport (S6 A9). `make` gives a new subject\n * for each case. Each case throws on a failure, and its message names the part of the contract.\n * - The start: nothing is in flight, and the transport takes work.\n * - The count: it follows each work from its events, with no move of the clock.\n * - `stopIntake` refuses new work, keeps the work in flight, and a second stop has no effect.\n * - `drain` ends at once with no work, ends with the last work, and holds to its deadline and not\n * past it. It gives the cooperative abort to the work, and it does not throw.\n * - `close` ends the work in flight in its bound, and a second close has no effect.\n * - The stages in their sequence, as the lifecycle does them.\n *\n * The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a\n * unary call is a stream of one item. The kit gives the transport a lifecycle with request\n * tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.\n * - A unary call gives one value, and its end comes as the status of the answer.\n * - A stream stays in flight until its end, not until its first item.\n * - A failure after the first item ends the stream with an error line in the body, not a status.\n * A failure before the first item gets a status.\n * - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.\n * - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.\n */\nexport const transportConformance = (make: SubjectFactory, options: ConformanceOptions = {}): ContractCase[] => {\n const name = options.name ?? \"transport\";\n const fake = (options.clock ?? \"fake\") === \"fake\";\n const cap = options.cap ?? 1000;\n const closeBound = options.closeBound ?? 1000;\n const slack = options.slack ?? 100;\n const cooperative = options.cooperative ?? true;\n const holds = options.holds ?? 3;\n\n const timeOf = (): Time => {\n if (!fake) return { clock: realClock, pass: (ms: number) => delay(alive, ms) };\n const clock = fakeClock();\n return { clock, pass: (ms) => clock.advance(ms) };\n };\n\n const check = (ok: boolean, what: string): void => {\n if (!ok) throw new Error(`${name}: ${what}`);\n };\n\n const each = (title: string, body: (subject: TransportSubject, time: Time, title: string) => Promise<void>): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, subject.life ?? detachedLifecycle());\n await body(subject, time, title);\n } finally {\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const count = (subject: TransportSubject, expected: number, what: string): Promise<void> =>\n within(slack, () => subject.impl.inFlight() === expected).then((ok) =>\n check(ok, `${what}: inFlight() gives ${subject.impl.inFlight()}, not ${expected}`),\n );\n\n const closes = async (subject: TransportSubject, title: string): Promise<void> => {\n const began = realNow();\n const closed = track(attempt(() => subject.impl.close()));\n const inBound = await within(closeBound, () => closed.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"close\", expected: closeBound, measured: took });\n check(inBound, `close did not end in its bound of ${closeBound} ms`);\n check(!closed.failed, `close threw: ${String(closed.error)}`);\n };\n\n const cases: ContractCase[] = [\n each(\"nothing is in flight after the start, and it takes new work\", async (subject) => {\n check(subject.impl.inFlight() === 0, `inFlight() gives ${subject.impl.inFlight()} after the start, not 0`);\n check(await subject.offer(), \"the transport refused new work after its start\");\n await count(subject, 0, \"the work ended\");\n }),\n\n each(\"the count follows each work in flight from its events, with no move of the clock\", async (subject) => {\n const held: HeldWork[] = [];\n for (let at = 1; at <= holds; at += 1) {\n held.push(await subject.hold());\n await count(subject, at, `${at} works are in flight`);\n }\n for (let at = holds - 1; at >= 0; at -= 1) {\n await held[at]!.release();\n await count(subject, at, `${at} works are in flight after a release`);\n }\n }),\n\n each(\"stopIntake refuses new work, keeps the work in flight, and a second stop has no effect\", async (subject) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n await count(subject, 1, \"stopIntake cut the work in flight\");\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after a second stopIntake\");\n await work.release();\n await count(subject, 0, \"the work in flight ended after stopIntake\");\n }),\n\n each(\"drain ends at once when nothing is in flight\", async (subject, time) => {\n await subject.impl.stopIntake();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, new AbortController().signal)));\n check(await within(slack, () => drained.settled), \"drain did not end with nothing in flight\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n }),\n\n each(\"drain ends when the last work ends, before its deadline\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while work was in flight, before its deadline\");\n await work.release();\n check(await within(slack, () => drained.settled), \"drain did not end when the last work ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the last work ended\");\n }),\n\n each(\"drain holds to its deadline and not past it, and does not throw\", async (subject, time, title) => {\n await subject.hold();\n await subject.impl.stopIntake();\n const began = realNow();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n if (fake) {\n await time.pass(cap - 1);\n await quiet();\n check(!drained.settled, \"drain ended before its deadline, with work in flight\");\n await time.pass(1);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n } else {\n const ended = await within(cap + slack, () => drained.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"drain to its deadline\", expected: cap, measured: took });\n check(ended, `drain did not end in ${cap + slack} ms, with a deadline at ${cap} ms`);\n check(took >= cap - slack, `drain ended after ${Math.round(took)} ms, before its deadline at ${cap} ms`);\n }\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n }),\n\n ...(cooperative\n ? [\n each(\"drain gives the cooperative abort to the work in flight\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await time.pass(cap / 2);\n await quiet();\n check(!work.aborted, \"the work got an abort before the signal of the drain aborted\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => work.aborted), \"the work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline after the cooperative abort\");\n check(!drained.failed, `drain threw after the cooperative abort: ${String(drained.error)}`);\n }),\n ]\n : []),\n\n each(\"drain with an aborted signal and a deadline in the past ends at once\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() - 1, abort.signal)));\n check(await within(slack, () => drained.settled), \"drain did not end at once with its deadline in the past\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n if (cooperative) check(await within(slack, () => work.aborted), \"the work did not get an abort that came before the drain\");\n }),\n\n each(\"close ends the work in flight, in its bound\", async (subject, _time, title) => {\n for (let at = 0; at < holds; at += 1) await subject.hold();\n await count(subject, holds, \"the works are in flight before the close\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n\n each(\"close is idempotent: a second close has no effect\", async (subject, _time, title) => {\n await subject.hold();\n const first = track(attempt(() => subject.impl.close()));\n const second = track(attempt(() => subject.impl.close()));\n check(await within(closeBound, () => first.settled && second.settled), \"two closes did not end in the bound\");\n check(!first.failed && !second.failed, `a close threw: ${String(first.error ?? second.error)}`);\n await closes(subject, title);\n await count(subject, 0, \"the closes left work in flight\");\n }),\n\n each(\"close right after the start ends in its bound\", async (subject, _time, title) => {\n await closes(subject, title);\n check(subject.impl.inFlight() === 0, \"inFlight() is not 0 after a close with no work\");\n }),\n\n each(\"the stages in their sequence: stop intake, drain with its cooperative abort, close\", async (subject, time, title) => {\n const short = await subject.hold();\n const long = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await short.release();\n await count(subject, 1, \"one work ended in the drain\");\n await time.pass(cap / 2);\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n if (cooperative) check(await within(slack, () => long.aborted), \"the long work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n ];\n if (!(options.streams ?? false)) return cases;\n\n /** A fed stream is a stream call whose items, end and failure the case gives. */\n interface Fed {\n readonly view: CallerView;\n push(value: unknown): void;\n finish(): void;\n fail(error: Error): void;\n /** This flag tells if the work got the abort of its signal. */\n readonly aborted: boolean;\n }\n\n const eachStream = (\n title: string,\n body: (subject: TransportSubject, time: Time, requests: Tracker) => Promise<void>,\n ): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n const { life, requests } = trackedLifecycle(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, life);\n check(subject.call !== undefined, \"the option streams needs a subject that gives call()\");\n await body(subject, time, requests);\n } finally {\n // each work of the case ends, thus no stream stays open after the case\n requests.stopIntake();\n requests.cooperativeAbort();\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const call = (subject: TransportSubject, given: StreamCall): Promise<CallerView> => Promise.resolve(subject.call!(given));\n\n const openStream = async (subject: TransportSubject): Promise<Fed> => {\n const source = pushedSource<unknown>();\n let started = false;\n let signal: AbortSignal | null = null;\n const view = await call(subject, {\n ...CALLS,\n stream: true,\n work: (given) => {\n started = true;\n signal = given;\n return source.iterable;\n },\n });\n check(await within(slack, () => started), \"the work of a stream call did not start\");\n return {\n view,\n push: (value) => source.push(value),\n finish: () => source.finish(),\n fail: (error) => source.fail(error),\n get aborted() {\n return (signal as AbortSignal | null)?.aborted === true;\n },\n };\n };\n\n const pushes = async (fed: Fed, value: number, what: string): Promise<void> => {\n const before = fed.view.items.length;\n fed.push(value);\n check(await within(slack, () => fed.view.items.length > before), `${what}: the caller did not get the item ${value}`);\n };\n\n const ends = async (view: CallerView, kind: RequestEnd[\"kind\"], inBand: boolean, what: string): Promise<void> => {\n check(await within(slack, () => view.end !== null), `${what}: the caller got no end`);\n const end = view.end!;\n const where = (body: boolean): string => (body ? \"in the body\" : \"as a status\");\n check(\n end.kind === kind && end.inBand === inBand,\n `${what}: the caller got the end ${end.kind} ${where(end.inBand)}, not ${kind} ${where(inBand)}`,\n );\n };\n\n /** This function stops the intake of the tracker and of the transport, as the stage `stop intake` does. */\n const stopBoth = async (subject: TransportSubject, requests: Tracker): Promise<void> => {\n requests.stopIntake();\n await subject.impl.stopIntake();\n };\n\n /**\n * This function starts the drain of the transport and of the tracker, as the stage `drain` does.\n * The abort of `signal` is also the cooperative abort of the tracker. It tracks the drain of the transport.\n */\n const drainBoth = (subject: TransportSubject, requests: Tracker, deadline: number, signal: AbortSignal): Tracked => {\n if (signal.aborted) requests.cooperativeAbort();\n else signal.addEventListener(\"abort\", () => requests.cooperativeAbort(), { once: true });\n void requests.drain(deadline);\n return track(attempt(() => subject.impl.drain(deadline, signal)));\n };\n\n const failure = (): Error => new Error(\"the failure of the conformance kit\");\n\n const streamCases: ContractCase[] = [\n eachStream(\"a unary call is a stream of one item: one value, and its end as the status\", async (subject) => {\n let started = false;\n let give: (value: unknown) => void = () => {};\n const view = await call(subject, {\n ...CALLS,\n stream: false,\n work: () => {\n started = true;\n return new Promise<unknown>((resolve) => {\n give = resolve;\n });\n },\n });\n check(await within(slack, () => started), \"the work of a unary call did not start\");\n await count(subject, 1, \"a unary call is in flight\");\n give(7);\n await ends(view, \"done\", false, \"a unary call\");\n check(view.items.length === 1 && view.items[0] === 7, `a unary call gave the items ${JSON.stringify(view.items)}, not [7]`);\n await count(subject, 0, \"a unary call ended\");\n }),\n\n eachStream(\"a stream stays in flight until its end, not until its first item\", async (subject) => {\n const fed = await openStream(subject);\n await count(subject, 1, \"a stream is open\");\n for (const value of [1, 2]) {\n await pushes(fed, value, \"an open stream\");\n await count(subject, 1, `a stream is open after its item ${value}`);\n }\n check(fed.view.end === null, \"the caller got an end before the end of the stream\");\n fed.finish();\n await ends(fed.view, \"done\", true, \"a stream that ended\");\n check(JSON.stringify(fed.view.items) === \"[1,2]\", `a stream gave the items ${JSON.stringify(fed.view.items)}, not [1,2]`);\n await count(subject, 0, \"a stream ended\");\n }),\n\n eachStream(\"a failure after the first item ends the stream with an error line, not a status\", async (subject) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before its failure\");\n fed.fail(failure());\n await ends(fed.view, \"failed\", true, \"a stream that failed after its first item\");\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"a failure before the first item gets a status, not an error line\", async (subject) => {\n const fed = await openStream(subject);\n fed.fail(failure());\n await ends(fed.view, \"failed\", false, \"a stream that failed before its first item\");\n check(fed.view.items.length === 0, `a stream that failed before its first item gave ${fed.view.items.length} items`);\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"drain waits for an open stream, and the cooperative abort ends the stream with its end\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const abort = new AbortController();\n const deadline = time.clock.now() + cap;\n const drained = drainBoth(subject, requests, deadline, abort.signal);\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while a stream was open, before its deadline\");\n check(fed.view.end === null, \"the caller got an end before the cooperative abort\");\n await count(subject, 1, \"a stream is open in the drain\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => fed.aborted), \"the work of the stream did not get the cooperative abort\");\n await ends(fed.view, \"cut\", true, \"a stream after the cooperative abort\");\n check(await within(slack, () => drained.settled), \"drain did not end when the stream ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the stream ended\");\n await count(subject, 0, \"the cooperative abort left a stream in flight\");\n }),\n\n eachStream(\"drain cuts an open stream at its deadline, and the caller gets the end of the cut\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const drained = drainBoth(subject, requests, time.clock.now() + cap, new AbortController().signal);\n await time.pass(cap);\n await ends(fed.view, \"cut\", true, \"a stream at the deadline of the drain\");\n check(await within(slack, () => drained.settled), \"drain did not end after the cut of the stream\");\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n await count(subject, 0, \"the cut left a stream in flight\");\n }),\n ];\n return [...cases, ...streamCases];\n};\n"],"mappings":";;;;;;;;;;;;AA6EA,MAAa,0BAAqC;CAChD,MAAM,aAAoB;EACxB,MAAM,IAAI,MAAM,oFAAoF;CACtG;CAEA,OAAO;EACL,QAAA;GAFe,SAAS;GAAM,OAAO;GAAM,SAAS;GAAM,WAAW;GAAM,WAAW;GAAM,OAAO;GAAM,MAAM;EAE1G;EACL,OAAO;EACP,UAAU;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M;GACnE,MAAM,KAAK,KAAK,MAAM,CAAC;GACvB,MAAM,MAAM;GACZ,MAAM,CAAC,QAAQ,SAAS,0DAA0D;GAClF,MAAM,IAAI,KAAK,QAAQ,MAAM,oDAAoD;GACjF,MAAM,MAAM,SAAS,GAAG,+BAA+B;GACvD,MAAM,sBAAM,IAAI,MAAM,8CAA8C,CAAC;GACrE,MAAM,MAAM,OAAO,aAAa,IAAI,OAAO,GAAG,0DAA0D;GACxG,MAAM,KAAK,IAAI,MAAM,OAAO,MAAM,sCAAsC;GACxE,MAAM,MAAM,OAAO,aAAa,QAAQ,OAAO,GAAG,yCAAyC;GAC3F,MAAM,CAAC,QAAQ,QAAQ,gBAAgB,OAAO,QAAQ,KAAK,GAAG;GAC9D,MAAM,KAAK,MAAM,IAAI,IAAI,UAAU,wDAAwD;GAC3F,MAAM,MAAM,SAAS,GAAG,+CAA+C;EACzE,CAAC;EAED,WAAW,qFAAqF,OAAO,SAAS,MAAM,aAAa;GACjI,MAAM,MAAM,MAAM,WAAW,OAAO;GACpC,MAAM,OAAO,KAAK,GAAG,2BAA2B;GAChD,MAAM,SAAS,SAAS,QAAQ;GAChC,MAAM,UAAU,UAAU,SAAS,UAAU,KAAK,MAAM,IAAI,IAAI,KAAK,IAAI,gBAAgB,CAAC,CAAC,MAAM;GACjG,MAAM,KAAK,KAAK,GAAG;GACnB,MAAM,KAAK,IAAI,MAAM,OAAO,MAAM,uCAAuC;GACzE,MAAM,MAAM,OAAO,aAAa,QAAQ,OAAO,GAAG,+CAA+C;GACjG,MAAM,CAAC,QAAQ,QAAQ,gCAAgC,OAAO,QAAQ,KAAK,GAAG;GAC9E,MAAM,MAAM,SAAS,GAAG,iCAAiC;EAC3D,CAAC;CACH;CACA,OAAO,CAAC,GAAG,OAAO,GAAG,WAAW;AAClC"}
1
+ {"version":3,"file":"conformance.js","names":[],"sources":["../src/conformance.ts"],"sourcesContent":["import { delay } from \"@mark1russell7/algebra/clock\";\nimport type { Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { ownStream } from \"./drains.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport { pushedSource } from \"./http/fake-server.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.ts\";\nimport type { RequestEnd, RequestFn, Tracker } from \"./requests.ts\";\nimport { tracker } from \"./requests.ts\";\n\n/** A held work is one unit of work that stays in flight until the test releases it. */\nexport interface HeldWork {\n /** This method lets the work end. Its promise ends when the caller of the work has its answer, or its error. */\n release(): Promise<void>;\n /** This flag tells if the work got the cooperative abort of the drain. */\n readonly aborted: boolean;\n}\n\n/**\n * A transport subject is a transport and the client side of its work. The kit offers work through\n * it, holds work in flight through it, and reads the count of the transport.\n */\nexport interface TransportSubject {\n readonly impl: TransportImpl;\n /** This lifecycle goes to `start()`. Without it, the kit gives a detached lifecycle. */\n readonly life?: Lifecycle | undefined;\n /** This method offers one unit of new work. It gives true when the transport took it, and false when it refused it. */\n offer(): Promise<boolean>;\n /** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */\n hold(): Promise<HeldWork>;\n /**\n * This method sends one call through the transport, for the stream cases (option `streams`). The\n * handler of the call gives `call.work` to `life.request(call.controller, call.route, ...)` of the\n * lifecycle of the start, and writes its stream to the caller. It gives what the caller sees.\n */\n call?(call: StreamCall): CallerView | Promise<CallerView>;\n /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\n}\n\n/** A stream call is one request of the stream cases. The kit gives its work, and the subject sends it. */\nexport interface StreamCall {\n /** This name is the controller of the request in the lifecycle of the kit. */\n readonly controller: string;\n /** This name is the route of the request in the lifecycle of the kit. */\n readonly route: string;\n /** This function is the work of the request: one value, or a stream of values. */\n readonly work: RequestFn<unknown>;\n /** True tells that the answer is a stream of items. False tells that the answer is unary: one status and one value. */\n readonly stream: boolean;\n}\n\n/** A seen end is the end of a call, as its caller read it. */\nexport interface SeenEnd {\n readonly kind: RequestEnd[\"kind\"];\n /**\n * True tells that the end came in the body of the answer, after its status, for example as the\n * last line of a stream. False tells that the end came as the status of the answer.\n */\n readonly inBand: boolean;\n}\n\n/** A caller view is what the caller of a call has read so far. The kit reads it again until it changes. */\nexport interface CallerView {\n /** These values are the items that the caller read, in their sequence. */\n readonly items: readonly unknown[];\n /** This end is the end that the caller read, or null while the call is open. */\n readonly end: SeenEnd | null;\n}\n\n/**\n * This function gives a detached lifecycle: a lifecycle with no service, for the start of a\n * transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request\n * and each use of its health throws, because no service declares a route.\n */\nexport const detachedLifecycle = (): Lifecycle => {\n const none = (): never => {\n throw new Error(\"a detached lifecycle has no service: give the transport the lifecycle of a service\");\n };\n const health = { verdict: none, probe: none, metrics: none, subscribe: none, forceFail: none, drain: none, stop: none } as Health;\n return {\n health,\n state: \"running\",\n exitCode: null,\n errors: [],\n started: Promise.resolve(),\n done: new Promise<number>(() => {}),\n signal: new AbortController().signal,\n shutdown: none,\n request: none,\n inFlight: () => 0,\n keepAlive: () => true,\n };\n};\n\n/** These names are the controller and the route of each call of the stream cases. */\nconst CALLS = { controller: \"conformance\", route: \"call\" } as const;\n\n/**\n * This function gives a lifecycle with request tracking for the stream cases, and its tracker. The\n * kit uses the tracker for the stages of the shutdown, as the lifecycle of a service does. Its\n * requests are not idempotent, and it admits each request until the stop of its intake.\n */\nconst trackedLifecycle = (clock: Clock): { readonly life: Lifecycle; readonly requests: Tracker } => {\n const requests = tracker([{ name: CALLS.controller, requires: [], routes: { [CALLS.route]: { idempotent: false } } }], clock, () => null);\n const life: Lifecycle = {\n ...detachedLifecycle(),\n // the lifecycle owns each stream that it makes, thus the drain of the transport waits for the end of its cut\n request: (controller, route, work, options) => ownStream(requests.request(controller, route, work, options), life),\n inFlight: (controller) => requests.inFlight(controller),\n };\n return { life, requests };\n};\n\n/** A subject factory makes a new subject for each case, on the clock of the case. */\nexport type SubjectFactory = (clock: Clock) => TransportSubject | Promise<TransportSubject>;\n\n/** A conformance record is one measurement of a case, for the raw records of a run in CI. */\nexport interface ConformanceRecord {\n readonly case: string;\n readonly what: string;\n /** This time is the limit of the contract, in milliseconds. */\n readonly expected: number;\n /** This time is what the case measured, in milliseconds of the real clock. */\n readonly measured: number;\n}\n\n/** These options tune the conformance kit. */\nexport interface ConformanceOptions {\n /** This name goes before the name of each case. */\n readonly name?: string | undefined;\n /** This clock moves the cases: `fake` gives exact and fast cases, and `real` measures the timing. The default is `fake`. */\n readonly clock?: \"fake\" | \"real\" | undefined;\n /** This time is the cap of each drain of the cases, in milliseconds. The default is 1000. */\n readonly cap?: number | undefined;\n /** This time is the most that a close can take, in milliseconds of the real clock. The default is 1000. */\n readonly closeBound?: number | undefined;\n /** This time is the most that an event can take to reach the transport, in real milliseconds. The default is 100. */\n readonly slack?: number | undefined;\n /** False tells that the work of the transport cannot see the cooperative abort. The default is true. */\n readonly cooperative?: boolean | undefined;\n /** This count is the number of works that the count case holds. The default is 3. */\n readonly holds?: number | undefined;\n /**\n * True adds the stream cases (S6 D4). Then the subject gives `call`, and the kit gives the\n * transport a lifecycle with request tracking. The default is false.\n */\n readonly streams?: boolean | undefined;\n /** This function receives each measurement, for the raw records of a run. */\n readonly record?: ((record: ConformanceRecord) => void) | undefined;\n}\n\ninterface Time {\n readonly clock: Clock;\n pass(ms: number): Promise<void>;\n}\n\ninterface Tracked {\n readonly settled: boolean;\n readonly error: unknown;\n readonly failed: boolean;\n}\n\nconst realNow = (): number => performance.now();\n// The waits of the case keep the process alive: each timer of realClock does (SYS-126).\nconst turn = (): Promise<void> => delay(realClock, 0);\n\n/** This function waits on the real clock, until the test is true or the bound ends. It gives the test at the end. */\nconst within = async (bound: number, test: () => boolean): Promise<boolean> => {\n const end = realNow() + bound;\n for (;;) {\n if (test()) return true;\n if (realNow() > end) return test();\n await turn();\n }\n};\n\n/** This function lets the events that are ready reach the transport, with no move of the clock of the case. */\nconst quiet = async (): Promise<void> => {\n for (let at = 0; at < 8; at += 1) await turn();\n};\n\n/** This function uses a method of the transport, and gives a throw of the method as a rejection. */\nconst attempt = (call: () => Promise<void> | void): Promise<void> => {\n try {\n return Promise.resolve(call());\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nconst track = (promise: Promise<unknown>): Tracked => {\n const state = { settled: false, error: undefined as unknown, failed: false };\n promise.then(\n () => {\n state.settled = true;\n },\n (error: unknown) => {\n state.settled = true;\n state.failed = true;\n state.error = error;\n },\n );\n return state;\n};\n\n/**\n * This function generates the conformance cases of a transport (S6 A9). `make` gives a new subject\n * for each case. Each case throws on a failure, and its message names the part of the contract.\n * - The start: nothing is in flight, and the transport takes work.\n * - The count: it follows each work from its events, with no move of the clock.\n * - `stopIntake` refuses new work, keeps the work in flight, and a second stop has no effect.\n * - `drain` ends at once with no work, ends with the last work, and holds to its deadline and not\n * past it. It gives the cooperative abort to the work, and it does not throw.\n * - `close` ends the work in flight in its bound, and a second close has no effect.\n * - The stages in their sequence, as the lifecycle does them.\n *\n * The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a\n * unary call is a stream of one item. The kit gives the transport a lifecycle with request\n * tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.\n * - A unary call gives one value, and its end comes as the status of the answer.\n * - A stream stays in flight until its end, not until its first item.\n * - A failure after the first item ends the stream with an error line in the body, not a status.\n * A failure before the first item gets a status.\n * - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.\n * - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.\n */\nexport const transportConformance = (make: SubjectFactory, options: ConformanceOptions = {}): ContractCase[] => {\n const name = options.name ?? \"transport\";\n const fake = (options.clock ?? \"fake\") === \"fake\";\n const cap = options.cap ?? 1000;\n const closeBound = options.closeBound ?? 1000;\n const slack = options.slack ?? 100;\n const cooperative = options.cooperative ?? true;\n const holds = options.holds ?? 3;\n\n const timeOf = (): Time => {\n if (!fake) return { clock: realClock, pass: (ms: number) => delay(realClock, ms) };\n const clock = fakeClock();\n return { clock, pass: (ms) => clock.advance(ms) };\n };\n\n const check = (ok: boolean, what: string): void => {\n if (!ok) throw new Error(`${name}: ${what}`);\n };\n\n const each = (title: string, body: (subject: TransportSubject, time: Time, title: string) => Promise<void>): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, subject.life ?? detachedLifecycle());\n await body(subject, time, title);\n } finally {\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const count = (subject: TransportSubject, expected: number, what: string): Promise<void> =>\n within(slack, () => subject.impl.inFlight() === expected).then((ok) =>\n check(ok, `${what}: inFlight() gives ${subject.impl.inFlight()}, not ${expected}`),\n );\n\n const closes = async (subject: TransportSubject, title: string): Promise<void> => {\n const began = realNow();\n const closed = track(attempt(() => subject.impl.close()));\n const inBound = await within(closeBound, () => closed.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"close\", expected: closeBound, measured: took });\n check(inBound, `close did not end in its bound of ${closeBound} ms`);\n check(!closed.failed, `close threw: ${String(closed.error)}`);\n };\n\n const cases: ContractCase[] = [\n each(\"nothing is in flight after the start, and it takes new work\", async (subject) => {\n check(subject.impl.inFlight() === 0, `inFlight() gives ${subject.impl.inFlight()} after the start, not 0`);\n check(await subject.offer(), \"the transport refused new work after its start\");\n await count(subject, 0, \"the work ended\");\n }),\n\n each(\"the count follows each work in flight from its events, with no move of the clock\", async (subject) => {\n const held: HeldWork[] = [];\n for (let at = 1; at <= holds; at += 1) {\n held.push(await subject.hold());\n await count(subject, at, `${at} works are in flight`);\n }\n for (let at = holds - 1; at >= 0; at -= 1) {\n await held[at]!.release();\n await count(subject, at, `${at} works are in flight after a release`);\n }\n }),\n\n each(\"stopIntake refuses new work, keeps the work in flight, and a second stop has no effect\", async (subject) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n await count(subject, 1, \"stopIntake cut the work in flight\");\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after a second stopIntake\");\n await work.release();\n await count(subject, 0, \"the work in flight ended after stopIntake\");\n }),\n\n each(\"drain ends at once when nothing is in flight\", async (subject, time) => {\n await subject.impl.stopIntake();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, new AbortController().signal)));\n check(await within(slack, () => drained.settled), \"drain did not end with nothing in flight\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n }),\n\n each(\"drain ends when the last work ends, before its deadline\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while work was in flight, before its deadline\");\n await work.release();\n check(await within(slack, () => drained.settled), \"drain did not end when the last work ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the last work ended\");\n }),\n\n each(\"drain holds to its deadline and not past it, and does not throw\", async (subject, time, title) => {\n await subject.hold();\n await subject.impl.stopIntake();\n const began = realNow();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n if (fake) {\n await time.pass(cap - 1);\n await quiet();\n check(!drained.settled, \"drain ended before its deadline, with work in flight\");\n await time.pass(1);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n } else {\n const ended = await within(cap + slack, () => drained.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"drain to its deadline\", expected: cap, measured: took });\n check(ended, `drain did not end in ${cap + slack} ms, with a deadline at ${cap} ms`);\n check(took >= cap - slack, `drain ended after ${Math.round(took)} ms, before its deadline at ${cap} ms`);\n }\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n }),\n\n ...(cooperative\n ? [\n each(\"drain gives the cooperative abort to the work in flight\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await time.pass(cap / 2);\n await quiet();\n check(!work.aborted, \"the work got an abort before the signal of the drain aborted\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => work.aborted), \"the work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline after the cooperative abort\");\n check(!drained.failed, `drain threw after the cooperative abort: ${String(drained.error)}`);\n }),\n ]\n : []),\n\n each(\"drain with an aborted signal and a deadline in the past ends at once\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() - 1, abort.signal)));\n check(await within(slack, () => drained.settled), \"drain did not end at once with its deadline in the past\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n if (cooperative) check(await within(slack, () => work.aborted), \"the work did not get an abort that came before the drain\");\n }),\n\n each(\"close ends the work in flight, in its bound\", async (subject, _time, title) => {\n for (let at = 0; at < holds; at += 1) await subject.hold();\n await count(subject, holds, \"the works are in flight before the close\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n\n each(\"close is idempotent: a second close has no effect\", async (subject, _time, title) => {\n await subject.hold();\n const first = track(attempt(() => subject.impl.close()));\n const second = track(attempt(() => subject.impl.close()));\n check(await within(closeBound, () => first.settled && second.settled), \"two closes did not end in the bound\");\n check(!first.failed && !second.failed, `a close threw: ${String(first.error ?? second.error)}`);\n await closes(subject, title);\n await count(subject, 0, \"the closes left work in flight\");\n }),\n\n each(\"close right after the start ends in its bound\", async (subject, _time, title) => {\n await closes(subject, title);\n check(subject.impl.inFlight() === 0, \"inFlight() is not 0 after a close with no work\");\n }),\n\n each(\"the stages in their sequence: stop intake, drain with its cooperative abort, close\", async (subject, time, title) => {\n const short = await subject.hold();\n const long = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await short.release();\n await count(subject, 1, \"one work ended in the drain\");\n await time.pass(cap / 2);\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n if (cooperative) check(await within(slack, () => long.aborted), \"the long work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n ];\n if (!(options.streams ?? false)) return cases;\n\n /** A fed stream is a stream call whose items, end and failure the case gives. */\n interface Fed {\n readonly view: CallerView;\n push(value: unknown): void;\n finish(): void;\n fail(error: Error): void;\n /** This flag tells if the work got the abort of its signal. */\n readonly aborted: boolean;\n }\n\n const eachStream = (\n title: string,\n body: (subject: TransportSubject, time: Time, requests: Tracker) => Promise<void>,\n ): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n const { life, requests } = trackedLifecycle(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, life);\n check(subject.call !== undefined, \"the option streams needs a subject that gives call()\");\n await body(subject, time, requests);\n } finally {\n // each work of the case ends, thus no stream stays open after the case\n requests.stopIntake();\n requests.cooperativeAbort();\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const call = (subject: TransportSubject, given: StreamCall): Promise<CallerView> => Promise.resolve(subject.call!(given));\n\n const openStream = async (subject: TransportSubject): Promise<Fed> => {\n const source = pushedSource<unknown>();\n let started = false;\n let signal: AbortSignal | null = null;\n const view = await call(subject, {\n ...CALLS,\n stream: true,\n work: (given) => {\n started = true;\n signal = given;\n return source.iterable;\n },\n });\n check(await within(slack, () => started), \"the work of a stream call did not start\");\n return {\n view,\n push: (value) => source.push(value),\n finish: () => source.finish(),\n fail: (error) => source.fail(error),\n get aborted() {\n return (signal as AbortSignal | null)?.aborted === true;\n },\n };\n };\n\n const pushes = async (fed: Fed, value: number, what: string): Promise<void> => {\n const before = fed.view.items.length;\n fed.push(value);\n check(await within(slack, () => fed.view.items.length > before), `${what}: the caller did not get the item ${value}`);\n };\n\n const ends = async (view: CallerView, kind: RequestEnd[\"kind\"], inBand: boolean, what: string): Promise<void> => {\n check(await within(slack, () => view.end !== null), `${what}: the caller got no end`);\n const end = view.end!;\n const where = (body: boolean): string => (body ? \"in the body\" : \"as a status\");\n check(\n end.kind === kind && end.inBand === inBand,\n `${what}: the caller got the end ${end.kind} ${where(end.inBand)}, not ${kind} ${where(inBand)}`,\n );\n };\n\n /** This function stops the intake of the tracker and of the transport, as the stage `stop intake` does. */\n const stopBoth = async (subject: TransportSubject, requests: Tracker): Promise<void> => {\n requests.stopIntake();\n await subject.impl.stopIntake();\n };\n\n /**\n * This function starts the drain of the transport and of the tracker, as the stage `drain` does.\n * The abort of `signal` is also the cooperative abort of the tracker. It tracks the drain of the transport.\n */\n const drainBoth = (subject: TransportSubject, requests: Tracker, deadline: number, signal: AbortSignal): Tracked => {\n if (signal.aborted) requests.cooperativeAbort();\n else signal.addEventListener(\"abort\", () => requests.cooperativeAbort(), { once: true });\n void requests.drain(deadline);\n return track(attempt(() => subject.impl.drain(deadline, signal)));\n };\n\n const failure = (): Error => new Error(\"the failure of the conformance kit\");\n\n const streamCases: ContractCase[] = [\n eachStream(\"a unary call is a stream of one item: one value, and its end as the status\", async (subject) => {\n let started = false;\n let give: (value: unknown) => void = () => {};\n const view = await call(subject, {\n ...CALLS,\n stream: false,\n work: () => {\n started = true;\n return new Promise<unknown>((resolve) => {\n give = resolve;\n });\n },\n });\n check(await within(slack, () => started), \"the work of a unary call did not start\");\n await count(subject, 1, \"a unary call is in flight\");\n give(7);\n await ends(view, \"done\", false, \"a unary call\");\n check(view.items.length === 1 && view.items[0] === 7, `a unary call gave the items ${JSON.stringify(view.items)}, not [7]`);\n await count(subject, 0, \"a unary call ended\");\n }),\n\n eachStream(\"a stream stays in flight until its end, not until its first item\", async (subject) => {\n const fed = await openStream(subject);\n await count(subject, 1, \"a stream is open\");\n for (const value of [1, 2]) {\n await pushes(fed, value, \"an open stream\");\n await count(subject, 1, `a stream is open after its item ${value}`);\n }\n check(fed.view.end === null, \"the caller got an end before the end of the stream\");\n fed.finish();\n await ends(fed.view, \"done\", true, \"a stream that ended\");\n check(JSON.stringify(fed.view.items) === \"[1,2]\", `a stream gave the items ${JSON.stringify(fed.view.items)}, not [1,2]`);\n await count(subject, 0, \"a stream ended\");\n }),\n\n eachStream(\"a failure after the first item ends the stream with an error line, not a status\", async (subject) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before its failure\");\n fed.fail(failure());\n await ends(fed.view, \"failed\", true, \"a stream that failed after its first item\");\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"a failure before the first item gets a status, not an error line\", async (subject) => {\n const fed = await openStream(subject);\n fed.fail(failure());\n await ends(fed.view, \"failed\", false, \"a stream that failed before its first item\");\n check(fed.view.items.length === 0, `a stream that failed before its first item gave ${fed.view.items.length} items`);\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"drain waits for an open stream, and the cooperative abort ends the stream with its end\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const abort = new AbortController();\n const deadline = time.clock.now() + cap;\n const drained = drainBoth(subject, requests, deadline, abort.signal);\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while a stream was open, before its deadline\");\n check(fed.view.end === null, \"the caller got an end before the cooperative abort\");\n await count(subject, 1, \"a stream is open in the drain\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => fed.aborted), \"the work of the stream did not get the cooperative abort\");\n await ends(fed.view, \"cut\", true, \"a stream after the cooperative abort\");\n check(await within(slack, () => drained.settled), \"drain did not end when the stream ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the stream ended\");\n await count(subject, 0, \"the cooperative abort left a stream in flight\");\n }),\n\n eachStream(\"drain cuts an open stream at its deadline, and the caller gets the end of the cut\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const drained = drainBoth(subject, requests, time.clock.now() + cap, new AbortController().signal);\n await time.pass(cap);\n await ends(fed.view, \"cut\", true, \"a stream at the deadline of the drain\");\n check(await within(slack, () => drained.settled), \"drain did not end after the cut of the stream\");\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n await count(subject, 0, \"the cut left a stream in flight\");\n }),\n ];\n return [...cases, ...streamCases];\n};\n"],"mappings":";;;;;;;;;;;;AA6EA,MAAa,0BAAqC;CAChD,MAAM,aAAoB;EACxB,MAAM,IAAI,MAAM,oFAAoF;CACtG;CAEA,OAAO;EACL,QAAA;GAFe,SAAS;GAAM,OAAO;GAAM,SAAS;GAAM,WAAW;GAAM,WAAW;GAAM,OAAO;GAAM,MAAM;EAE1G;EACL,OAAO;EACP,UAAU;EACV,QAAQ,CAAC;EACT,SAAS,QAAQ,QAAQ;EACzB,MAAM,IAAI,cAAsB,CAAC,CAAC;EAClC,QAAQ,IAAI,gBAAgB,CAAC,CAAC;EAC9B,UAAU;EACV,SAAS;EACT,gBAAgB;EAChB,iBAAiB;CACnB;AACF;;AAGA,MAAM,QAAQ;CAAE,YAAY;CAAe,OAAO;AAAO;;;;;;AAOzD,MAAM,oBAAoB,UAA2E;CACnG,MAAM,WAAW,QAAQ,CAAC;EAAE,MAAM,MAAM;EAAY,UAAU,CAAC;EAAG,QAAQ,GAAG,MAAM,QAAQ,EAAE,YAAY,MAAM,EAAE;CAAE,CAAC,GAAG,aAAa,IAAI;CACxI,MAAM,OAAkB;EACtB,GAAG,kBAAkB;EAErB,UAAU,YAAY,OAAO,M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F,MAAM,MAAM,SAAS,GAAG,+CAA+C;EACzE,CAAC;EAED,WAAW,qFAAqF,OAAO,SAAS,MAAM,aAAa;GACjI,MAAM,MAAM,MAAM,WAAW,OAAO;GACpC,MAAM,OAAO,KAAK,GAAG,2BAA2B;GAChD,MAAM,SAAS,SAAS,QAAQ;GAChC,MAAM,UAAU,UAAU,SAAS,UAAU,KAAK,MAAM,IAAI,IAAI,KAAK,IAAI,gBAAgB,CAAC,CAAC,MAAM;GACjG,MAAM,KAAK,KAAK,GAAG;GACnB,MAAM,KAAK,IAAI,MAAM,OAAO,MAAM,uCAAuC;GACzE,MAAM,MAAM,OAAO,aAAa,QAAQ,OAAO,GAAG,+CAA+C;GACjG,MAAM,CAAC,QAAQ,QAAQ,gCAAgC,OAAO,QAAQ,KAAK,GAAG;GAC9E,MAAM,MAAM,SAAS,GAAG,iCAAiC;EAC3D,CAAC;CACH;CACA,OAAO,CAAC,GAAG,OAAO,GAAG,WAAW;AAClC"}
package/build/health.js CHANGED
@@ -1,4 +1,4 @@
1
- import { realClock } from "./clock.js";
1
+ import { realClock, unrefClock } from "./clock.js";
2
2
  import { latch } from "./latch.js";
3
3
  import { meter } from "./metrics.js";
4
4
  import { poller } from "./poller.js";
@@ -53,6 +53,7 @@ const healthRuntime = (description, runs, options = {}) => {
53
53
  budgetTimer = null;
54
54
  if (gate !== "open" && gate !== "failed") gateTrace(gate, gate, "startup.over-budget");
55
55
  });
56
+ budgetTimer.unref?.();
56
57
  const changed = () => {
57
58
  if (listeners.size === 0) return;
58
59
  const now = verdict();
@@ -61,7 +62,7 @@ const healthRuntime = (description, runs, options = {}) => {
61
62
  const add = (check, given, late) => {
62
63
  const run = options.wrapCheck?.(check, given) ?? given;
63
64
  const timing = check.gates === null ? null : description.policies[check.gates];
64
- const made = timing === null ? null : latch(timing, clock, check.gates === "readiness", changed, tracer(timing.type === "window" ? "window" : "latch", check.name));
65
+ const made = timing === null ? null : latch(timing, unrefClock(clock), check.gates === "readiness", changed, tracer(timing.type === "window" ? "window" : "latch", check.name));
65
66
  const entry = {
66
67
  check,
67
68
  latch: made,
@@ -71,6 +72,7 @@ const healthRuntime = (description, runs, options = {}) => {
71
72
  run,
72
73
  clock,
73
74
  random,
75
+ unrefLoop: true,
74
76
  forced: () => forced.has(check.name) || check.dependency !== null && forced.has(check.dependency),
75
77
  record: (result) => {
76
78
  counts.poll(check, result);
@@ -1 +1 @@
1
- {"version":3,"file":"health.js","names":[],"sources":["../src/health.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { Check, Gate, ServiceDescription } from \"./description.ts\";\nimport type { MachineName, Recorder } from \"./events.ts\";\nimport type { Latch, Result, Trace } from \"./latch.ts\";\nimport type { Logger } from \"./logger.ts\";\nimport { latch } from \"./latch.ts\";\nimport type { HealthMetrics } from \"./metrics.ts\";\nimport { meter } from \"./metrics.ts\";\nimport type { CheckFn, Poller } from \"./poller.ts\";\nimport { poller } from \"./poller.ts\";\n\n/** These options start the runtime. Without them, it uses the real clock and `Math.random`. */\nexport interface StartOptions {\n readonly clock?: Clock | undefined;\n /** This function gives a number in [0, 1) for the jitter of each poll. */\n readonly random?: (() => number) | undefined;\n /** This list names the checks or dependencies whose polls fail at once (a seam for tests). */\n readonly forceFail?: readonly string[] | undefined;\n /** This function receives each transition of each machine of the runtime. */\n readonly record?: Recorder | undefined;\n /**\n * This logger receives each transition too, as a log entry with a level and fields (`logEvents`).\n * Without it, the runtime writes no log, as before. For the console, give `consoleLogger()`.\n */\n readonly logger?: Logger | undefined;\n /**\n * This function can replace the function of a check, for example to add a delay to each call\n * (a seam for tests: a degraded dependency). It gives the function to use.\n */\n readonly wrapCheck?: ((check: Check, run: CheckFn) => CheckFn) | undefined;\n}\n\n/** A check verdict is the cached state of one check, for the probes and the report. */\nexport interface CheckVerdict {\n readonly gates: Gate | null;\n readonly dependency: string | null;\n /** This flag tells if the latch of the check is tripped, or it is null for a check that only reports. */\n readonly tripped: boolean | null;\n readonly streak: number;\n /** This time is when the latch last changed, in milliseconds on the monotonic clock. */\n readonly since: number | null;\n readonly last: Result | null;\n}\n\n/** A verdict is the state of the service, from its cache. Nothing in it starts a check. */\nexport interface HealthVerdict {\n /** This flag becomes true one time, after the warm-up sweep. */\n readonly started: boolean;\n readonly draining: boolean;\n /** This flag tells if the service can take new work: started, not draining, and each readiness latch released. */\n readonly ready: boolean;\n /** This flag tells if each liveness latch is released. */\n readonly alive: boolean;\n /** These flags tell if each controller can take new work, from the dependencies that it needs. */\n readonly controllers: Readonly<Record<string, boolean>>;\n readonly dependencies: Readonly<Record<string, boolean>>;\n readonly checks: Readonly<Record<string, CheckVerdict>>;\n readonly startup: { readonly budget: number; readonly elapsed: number; readonly overBudget: boolean };\n}\n\n/** A probe kind is the question that a probe asks: the startup, the readiness, the liveness, or the whole report. */\nexport type ProbeKind = \"startup\" | \"readiness\" | \"liveness\" | \"report\";\n\n/** A probe answer is a status and a body, for any HTTP framework or none. */\nexport interface ProbeAnswer {\n readonly status: 200 | 503;\n readonly contentType: \"application/health+json\";\n readonly body: {\n readonly status: \"pass\" | \"fail\";\n readonly service: string;\n readonly probe: ProbeKind;\n readonly controller?: string | undefined;\n readonly verdict?: HealthVerdict | undefined;\n };\n}\n\n/** The health runtime of a started service. It reads its timing and its checks from the declaration. */\nexport interface Health {\n verdict(): HealthVerdict;\n /**\n * This method answers a probe from the cache, in constant time, and it starts no check. A\n * readiness probe with a controller asks about that controller. The report always answers 200.\n */\n probe(kind: ProbeKind, controller?: string): ProbeAnswer;\n /**\n * This method gives the counts of the runtime (B18). They are the outcomes, the durations and the\n * episodes of failure of each check, and the transitions of its machines. It starts no check.\n */\n metrics(): HealthMetrics;\n /** This method gives each change of the verdict to `listener`, and gives the function that stops it. */\n subscribe(listener: (verdict: HealthVerdict) => void): () => void;\n /** This method adds a name to the force-fail list, or removes it. */\n forceFail(name: string, on: boolean): void;\n /** This method fails readiness for good. The drain of the lifecycle starts with it. */\n drain(): void;\n /** This method stops each poller and each timer of the runtime. */\n stop(): void;\n}\n\n/** The runtime parts that the builder and the lifecycle use. */\nexport interface Runtime extends Health {\n /**\n * This method opens the startup gate: one bounded warm-up sweep of each check, then the loops of\n * the pollers. It is idempotent, and it does nothing after `failStartup()` or `stop()`.\n */\n warmUp(): Promise<void>;\n /** This method moves the gate from `closed` to `starting`: the lifecycle starts its components. */\n beginStartup(): void;\n /** This method moves the gate to `failed` for good: a component did not start. */\n failStartup(cause: string): void;\n addCheck(check: Check, run: CheckFn): void;\n addDependency(name: string): void;\n}\n\ninterface Entry {\n readonly check: Check;\n readonly poller: Poller;\n readonly latch: Latch | null;\n}\n\n/**\n * This function makes the runtime of a declaration. The service has no defaults of its own: each\n * timing, poll and coupling comes from the description.\n */\nexport const healthRuntime = (\n description: ServiceDescription,\n runs: ReadonlyMap<string, CheckFn>,\n options: StartOptions = {},\n): Runtime => {\n const clock = options.clock ?? realClock;\n const random = options.random ?? Math.random;\n const forced = new Set(options.forceFail ?? []);\n const startedAt = clock.now();\n const budget = valueIn(description.policies.startup, \"ms\");\n const entries = new Map<string, Entry>();\n const dependencies = new Set(description.dependencies.map((dependency) => dependency.name));\n // a dependency that joined after the start is tripped until a check on it passes one time\n const lateDependencies = new Set<string>();\n const listeners = new Set<(verdict: HealthVerdict) => void>();\n let started = false;\n let draining = false;\n let stopped = false;\n // the startup gate: closed, starting (components start), sweeping (the warm-up), open or failed\n let gate = \"closed\";\n\n const counts = meter();\n // each transition goes to the meter, and then to the recorder of the options\n const record: Recorder = (event) => {\n counts.event(event);\n options.record?.(event);\n };\n const tracer =\n (machine: MachineName, instance: string): Trace =>\n (from, to, on) =>\n record({ at: clock.now(), machine, instance, from, to, on });\n const gateTrace = tracer(\"gate\", description.name);\n const moveGate = (to: string, on: string, detail?: string): void => {\n const from = gate;\n gate = to;\n record({\n at: clock.now(),\n machine: \"gate\",\n instance: description.name,\n from,\n to,\n on,\n ...(detail === undefined ? {} : { detail }),\n });\n };\n // the startup budget: a gate that is not open at its end says so. The platform's startup probe\n // acts on it, and the runtime does not stop itself\n let budgetTimer: Cancel | null = clock.after(budget, () => {\n budgetTimer = null;\n if (gate !== \"open\" && gate !== \"failed\") gateTrace(gate, gate, \"startup.over-budget\");\n });\n\n const changed = (): void => {\n if (listeners.size === 0) return;\n const now = verdict();\n for (const listener of listeners) listener(now);\n };\n\n const add = (check: Check, given: CheckFn, late: boolean): void => {\n const run = options.wrapCheck?.(check, given) ?? given;\n const timing = check.gates === null ? null : description.policies[check.gates];\n // readiness is earned: its latch starts tripped. Liveness passes from the start (and a late\n // liveness check starts released too, or one late registration could restart the process)\n const made =\n timing === null\n ? null\n : latch(\n timing,\n clock,\n check.gates === \"readiness\",\n changed,\n tracer(timing.type === \"window\" ? \"window\" : \"latch\", check.name),\n );\n const entry: Entry = {\n check,\n latch: made,\n poller: poller({\n name: check.name,\n poll: check.poll,\n run,\n clock,\n random,\n forced: () =>\n forced.has(check.name) || (check.dependency !== null && forced.has(check.dependency)),\n record: (result) => {\n counts.poll(check, result);\n made?.record(result);\n // a late dependency is released by the first pass of a check on it\n if (result.outcome === \"ok\" && check.dependency !== null)\n if (lateDependencies.delete(check.dependency)) changed();\n },\n trace: tracer(\"poller\", check.name),\n }),\n };\n entries.set(check.name, entry);\n counts.add(check);\n if (late && !stopped) {\n // a late registration pulls readiness until its first pass: it polls at once, then on its loop\n void entry.poller.pollNow();\n entry.poller.start(entry.poller.jittered());\n }\n };\n\n for (const check of description.checks) {\n const run = runs.get(check.name);\n if (run === undefined) throw new Error(`check ${check.name} has no function: the runtime has no defaults`);\n add(check, run, false);\n }\n\n const latchesOf = (gateOf: Gate, keep: (check: Check) => boolean = () => true): Latch[] =>\n [...entries.values()].flatMap((entry) =>\n entry.check.gates === gateOf && entry.latch !== null && keep(entry.check) ? [entry.latch] : [],\n );\n const released = (latches: readonly Latch[]): boolean => latches.every((each) => !each.tripped);\n /** This function tells if a policy fails through a declared coupling from another policy. */\n const coupledOff = (to: Gate, base: Record<Gate, boolean>): boolean =>\n description.couplings.some((coupling) => coupling.to === to && !base[coupling.from]);\n\n const verdict = (): HealthVerdict => {\n const base: Record<Gate, boolean> = {\n readiness: released(latchesOf(\"readiness\")) && lateDependencies.size === 0,\n liveness: released(latchesOf(\"liveness\")),\n };\n const alive = base.liveness && !coupledOff(\"liveness\", base);\n const open = started && !draining && !coupledOff(\"readiness\", base);\n const ready = open && base.readiness;\n const dependencyReady = (name: string): boolean =>\n !lateDependencies.has(name) &&\n released(latchesOf(\"readiness\", (check) => check.dependency === name));\n const own = released(latchesOf(\"readiness\", (check) => check.dependency === null));\n const dependenciesOut: Record<string, boolean> = {};\n for (const name of dependencies) dependenciesOut[name] = dependencyReady(name);\n const controllers: Record<string, boolean> = {};\n for (const controller of description.controllers)\n controllers[controller.name] = open && own && controller.requires.every(dependencyReady);\n const checks: Record<string, CheckVerdict> = {};\n for (const [name, entry] of entries) {\n checks[name] = {\n gates: entry.check.gates,\n dependency: entry.check.dependency,\n tripped: entry.latch?.tripped ?? null,\n streak: entry.latch?.streak ?? 0,\n since: entry.latch?.since ?? null,\n last: entry.poller.last,\n };\n }\n const elapsed = clock.now() - startedAt;\n return {\n started,\n draining,\n ready,\n alive,\n controllers,\n dependencies: dependenciesOut,\n checks,\n startup: { budget, elapsed, overBudget: !started && elapsed > budget },\n };\n };\n\n const answer = (kind: ProbeKind, pass: boolean, controller?: string): ProbeAnswer => ({\n status: pass || kind === \"report\" ? 200 : 503,\n contentType: \"application/health+json\",\n body: {\n status: pass ? \"pass\" : \"fail\",\n service: description.name,\n probe: kind,\n ...(controller === undefined ? {} : { controller }),\n ...(kind === \"report\" ? { verdict: verdict() } : {}),\n },\n });\n\n return {\n verdict,\n metrics: counts.metrics,\n probe(kind, controller) {\n const now = verdict();\n if (kind === \"startup\") return answer(kind, now.started);\n if (kind === \"liveness\") return answer(kind, now.alive);\n if (kind === \"report\") return answer(kind, now.ready && now.alive);\n if (controller === undefined) return answer(kind, now.ready);\n // only an own key is a controller: a name such as \"constructor\" is not one\n const known = Object.hasOwn(now.controllers, controller) ? now.controllers[controller] : undefined;\n if (known === undefined) throw new Error(`${description.name} has no controller ${controller}`);\n return answer(kind, known, controller);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n forceFail(name, on) {\n if (on) forced.add(name);\n else forced.delete(name);\n },\n drain() {\n if (draining) return;\n draining = true;\n changed();\n },\n stop() {\n stopped = true;\n budgetTimer?.();\n budgetTimer = null;\n for (const entry of entries.values()) {\n entry.poller.stop();\n entry.latch?.stop();\n }\n },\n beginStartup() {\n if (gate === \"closed\") moveGate(\"starting\", \"startup.begin\");\n },\n failStartup(cause) {\n if (gate === \"open\" || gate === \"failed\") return;\n moveGate(\"failed\", \"startup.fail\", cause);\n budgetTimer?.();\n budgetTimer = null;\n },\n async warmUp() {\n if (started || stopped || gate === \"failed\" || gate === \"sweeping\") return;\n moveGate(\"sweeping\", \"mark-ready\");\n // one bounded sweep of each check: each poll ends at its timeout at the latest\n const sweep = clock.now();\n await Promise.all([...entries.values()].map((entry) => entry.poller.pollNow()));\n if (stopped || gate !== \"sweeping\") return;\n for (const entry of entries.values())\n entry.poller.start(entry.poller.jittered() - (clock.now() - sweep));\n started = true;\n budgetTimer?.();\n budgetTimer = null;\n moveGate(\"open\", \"sweep.done\");\n changed();\n },\n addCheck(check, run) {\n if (entries.has(check.name)) throw new Error(`${description.name} already has a check named ${check.name}`);\n add(check, run, true);\n changed();\n },\n addDependency(name) {\n if (dependencies.has(name)) return;\n dependencies.add(name);\n lateDependencies.add(name);\n changed();\n },\n };\n};\n"],"mappings":";;;;;;;;;;AA8HA,MAAa,iBACX,aACA,MACA,UAAwB,CAAC,MACb;CACZ,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,SAAS,QAAQ,UAAU,KAAK;CACtC,MAAM,SAAS,IAAI,IAAI,QAAQ,aAAa,CAAC,CAAC;CAC9C,MAAM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,WAAW,WAAW,SAAS,YAAY,SAAS,YAAY;GACpE,SAAS,YAAY,YAAY;GAEjC,MAAM,QAAQ,MAAM,IAAI;GACxB,MAAM,QAAQ,IAAI,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC,CAAC,KAAK,UAAU,MAAM,OAAO,QAAQ,CAAC,CAAC;GAC9E,IAAI,WAAW,SAAS,YAAY;GACpC,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,MAAM,MAAM,OAAO,SAAS,KAAK,MAAM,IAAI,IAAI,MAAM;GACpE,UAAU;GACV,cAAc;GACd,cAAc;GACd,SAAS,QAAQ,YAAY;GAC7B,QAAQ;EACV;EACA,SAAS,OAAO,KAAK;GACnB,IAAI,QAAQ,IAAI,MAAM,IAAI,GAAG,MAAM,IAAI,MAAM,GAAG,YAAY,KAAK,6BAA6B,MAAM,MAAM;GAC1G,IAAI,OAAO,KAAK,IAAI;GACpB,QAAQ;EACV;EACA,cAAc,MAAM;GAClB,IAAI,aAAa,IAAI,IAAI,GAAG;GAC5B,aAAa,IAAI,IAAI;GACrB,iBAAiB,IAAI,IAAI;GACzB,QAAQ;EACV;CACF;AACF"}
1
+ {"version":3,"file":"health.js","names":[],"sources":["../src/health.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock, unrefClock } from \"./clock.ts\";\nimport type { Check, Gate, ServiceDescription } from \"./description.ts\";\nimport type { MachineName, Recorder } from \"./events.ts\";\nimport type { Latch, Result, Trace } from \"./latch.ts\";\nimport type { Logger } from \"./logger.ts\";\nimport { latch } from \"./latch.ts\";\nimport type { HealthMetrics } from \"./metrics.ts\";\nimport { meter } from \"./metrics.ts\";\nimport type { CheckFn, Poller } from \"./poller.ts\";\nimport { poller } from \"./poller.ts\";\n\n/** These options start the runtime. Without them, it uses the real clock and `Math.random`. */\nexport interface StartOptions {\n readonly clock?: Clock | undefined;\n /** This function gives a number in [0, 1) for the jitter of each poll. */\n readonly random?: (() => number) | undefined;\n /** This list names the checks or dependencies whose polls fail at once (a seam for tests). */\n readonly forceFail?: readonly string[] | undefined;\n /** This function receives each transition of each machine of the runtime. */\n readonly record?: Recorder | undefined;\n /**\n * This logger receives each transition too, as a log entry with a level and fields (`logEvents`).\n * Without it, the runtime writes no log, as before. For the console, give `consoleLogger()`.\n */\n readonly logger?: Logger | undefined;\n /**\n * This function can replace the function of a check, for example to add a delay to each call\n * (a seam for tests: a degraded dependency). It gives the function to use.\n */\n readonly wrapCheck?: ((check: Check, run: CheckFn) => CheckFn) | undefined;\n}\n\n/** A check verdict is the cached state of one check, for the probes and the report. */\nexport interface CheckVerdict {\n readonly gates: Gate | null;\n readonly dependency: string | null;\n /** This flag tells if the latch of the check is tripped, or it is null for a check that only reports. */\n readonly tripped: boolean | null;\n readonly streak: number;\n /** This time is when the latch last changed, in milliseconds on the monotonic clock. */\n readonly since: number | null;\n readonly last: Result | null;\n}\n\n/** A verdict is the state of the service, from its cache. Nothing in it starts a check. */\nexport interface HealthVerdict {\n /** This flag becomes true one time, after the warm-up sweep. */\n readonly started: boolean;\n readonly draining: boolean;\n /** This flag tells if the service can take new work: started, not draining, and each readiness latch released. */\n readonly ready: boolean;\n /** This flag tells if each liveness latch is released. */\n readonly alive: boolean;\n /** These flags tell if each controller can take new work, from the dependencies that it needs. */\n readonly controllers: Readonly<Record<string, boolean>>;\n readonly dependencies: Readonly<Record<string, boolean>>;\n readonly checks: Readonly<Record<string, CheckVerdict>>;\n readonly startup: { readonly budget: number; readonly elapsed: number; readonly overBudget: boolean };\n}\n\n/** A probe kind is the question that a probe asks: the startup, the readiness, the liveness, or the whole report. */\nexport type ProbeKind = \"startup\" | \"readiness\" | \"liveness\" | \"report\";\n\n/** A probe answer is a status and a body, for any HTTP framework or none. */\nexport interface ProbeAnswer {\n readonly status: 200 | 503;\n readonly contentType: \"application/health+json\";\n readonly body: {\n readonly status: \"pass\" | \"fail\";\n readonly service: string;\n readonly probe: ProbeKind;\n readonly controller?: string | undefined;\n readonly verdict?: HealthVerdict | undefined;\n };\n}\n\n/** The health runtime of a started service. It reads its timing and its checks from the declaration. */\nexport interface Health {\n verdict(): HealthVerdict;\n /**\n * This method answers a probe from the cache, in constant time, and it starts no check. A\n * readiness probe with a controller asks about that controller. The report always answers 200.\n */\n probe(kind: ProbeKind, controller?: string): ProbeAnswer;\n /**\n * This method gives the counts of the runtime (B18). They are the outcomes, the durations and the\n * episodes of failure of each check, and the transitions of its machines. It starts no check.\n */\n metrics(): HealthMetrics;\n /** This method gives each change of the verdict to `listener`, and gives the function that stops it. */\n subscribe(listener: (verdict: HealthVerdict) => void): () => void;\n /** This method adds a name to the force-fail list, or removes it. */\n forceFail(name: string, on: boolean): void;\n /** This method fails readiness for good. The drain of the lifecycle starts with it. */\n drain(): void;\n /** This method stops each poller and each timer of the runtime. */\n stop(): void;\n}\n\n/** The runtime parts that the builder and the lifecycle use. */\nexport interface Runtime extends Health {\n /**\n * This method opens the startup gate: one bounded warm-up sweep of each check, then the loops of\n * the pollers. It is idempotent, and it does nothing after `failStartup()` or `stop()`.\n */\n warmUp(): Promise<void>;\n /** This method moves the gate from `closed` to `starting`: the lifecycle starts its components. */\n beginStartup(): void;\n /** This method moves the gate to `failed` for good: a component did not start. */\n failStartup(cause: string): void;\n addCheck(check: Check, run: CheckFn): void;\n addDependency(name: string): void;\n}\n\ninterface Entry {\n readonly check: Check;\n readonly poller: Poller;\n readonly latch: Latch | null;\n}\n\n/**\n * This function makes the runtime of a declaration. The service has no defaults of its own: each\n * timing, poll and coupling comes from the description.\n */\nexport const healthRuntime = (\n description: ServiceDescription,\n runs: ReadonlyMap<string, CheckFn>,\n options: StartOptions = {},\n): Runtime => {\n const clock = options.clock ?? realClock;\n const random = options.random ?? Math.random;\n const forced = new Set(options.forceFail ?? []);\n const startedAt = clock.now();\n const budget = valueIn(description.policies.startup, \"ms\");\n const entries = new Map<string, Entry>();\n const dependencies = new Set(description.dependencies.map((dependency) => dependency.name));\n // a dependency that joined after the start is tripped until a check on it passes one time\n const lateDependencies = new Set<string>();\n const listeners = new Set<(verdict: HealthVerdict) => void>();\n let started = false;\n let draining = false;\n let stopped = false;\n // the startup gate: closed, starting (components start), sweeping (the warm-up), open or failed\n let gate = \"closed\";\n\n const counts = meter();\n // each transition goes to the meter, and then to the recorder of the options\n const record: Recorder = (event) => {\n counts.event(event);\n options.record?.(event);\n };\n const tracer =\n (machine: MachineName, instance: string): Trace =>\n (from, to, on) =>\n record({ at: clock.now(), machine, instance, from, to, on });\n const gateTrace = tracer(\"gate\", description.name);\n const moveGate = (to: string, on: string, detail?: string): void => {\n const from = gate;\n gate = to;\n record({\n at: clock.now(),\n machine: \"gate\",\n instance: description.name,\n from,\n to,\n on,\n ...(detail === undefined ? {} : { detail }),\n });\n };\n // the startup budget: a gate that is not open at its end says so. The platform's startup probe\n // acts on it, and the runtime does not stop itself\n let budgetTimer: Cancel | null = clock.after(budget, () => {\n budgetTimer = null;\n if (gate !== \"open\" && gate !== \"failed\") gateTrace(gate, gate, \"startup.over-budget\");\n });\n // the budget only traces, thus it does not keep the process alive (SYS-126)\n budgetTimer.unref?.();\n\n const changed = (): void => {\n if (listeners.size === 0) return;\n const now = verdict();\n for (const listener of listeners) listener(now);\n };\n\n const add = (check: Check, given: CheckFn, late: boolean): void => {\n const run = options.wrapCheck?.(check, given) ?? given;\n const timing = check.gates === null ? null : description.policies[check.gates];\n // readiness is earned: its latch starts tripped. Liveness passes from the start (and a late\n // liveness check starts released too, or one late registration could restart the process)\n const made =\n timing === null\n ? null\n : latch(\n timing,\n // a check watches the parts of the service: the parts keep the process alive, and the\n // windows of the latch do not (SYS-126)\n unrefClock(clock),\n check.gates === \"readiness\",\n changed,\n tracer(timing.type === \"window\" ? \"window\" : \"latch\", check.name),\n );\n const entry: Entry = {\n check,\n latch: made,\n poller: poller({\n name: check.name,\n poll: check.poll,\n run,\n clock,\n random,\n // a check watches the parts of the service: the parts keep the process alive. The warm-up\n // awaits its sweep of polls, thus the timeout of a poll stays referenced (SYS-126)\n unrefLoop: true,\n forced: () =>\n forced.has(check.name) || (check.dependency !== null && forced.has(check.dependency)),\n record: (result) => {\n counts.poll(check, result);\n made?.record(result);\n // a late dependency is released by the first pass of a check on it\n if (result.outcome === \"ok\" && check.dependency !== null)\n if (lateDependencies.delete(check.dependency)) changed();\n },\n trace: tracer(\"poller\", check.name),\n }),\n };\n entries.set(check.name, entry);\n counts.add(check);\n if (late && !stopped) {\n // a late registration pulls readiness until its first pass: it polls at once, then on its loop\n void entry.poller.pollNow();\n entry.poller.start(entry.poller.jittered());\n }\n };\n\n for (const check of description.checks) {\n const run = runs.get(check.name);\n if (run === undefined) throw new Error(`check ${check.name} has no function: the runtime has no defaults`);\n add(check, run, false);\n }\n\n const latchesOf = (gateOf: Gate, keep: (check: Check) => boolean = () => true): Latch[] =>\n [...entries.values()].flatMap((entry) =>\n entry.check.gates === gateOf && entry.latch !== null && keep(entry.check) ? [entry.latch] : [],\n );\n const released = (latches: readonly Latch[]): boolean => latches.every((each) => !each.tripped);\n /** This function tells if a policy fails through a declared coupling from another policy. */\n const coupledOff = (to: Gate, base: Record<Gate, boolean>): boolean =>\n description.couplings.some((coupling) => coupling.to === to && !base[coupling.from]);\n\n const verdict = (): HealthVerdict => {\n const base: Record<Gate, boolean> = {\n readiness: released(latchesOf(\"readiness\")) && lateDependencies.size === 0,\n liveness: released(latchesOf(\"liveness\")),\n };\n const alive = base.liveness && !coupledOff(\"liveness\", base);\n const open = started && !draining && !coupledOff(\"readiness\", base);\n const ready = open && base.readiness;\n const dependencyReady = (name: string): boolean =>\n !lateDependencies.has(name) &&\n released(latchesOf(\"readiness\", (check) => check.dependency === name));\n const own = released(latchesOf(\"readiness\", (check) => check.dependency === null));\n const dependenciesOut: Record<string, boolean> = {};\n for (const name of dependencies) dependenciesOut[name] = dependencyReady(name);\n const controllers: Record<string, boolean> = {};\n for (const controller of description.controllers)\n controllers[controller.name] = open && own && controller.requires.every(dependencyReady);\n const checks: Record<string, CheckVerdict> = {};\n for (const [name, entry] of entries) {\n checks[name] = {\n gates: entry.check.gates,\n dependency: entry.check.dependency,\n tripped: entry.latch?.tripped ?? null,\n streak: entry.latch?.streak ?? 0,\n since: entry.latch?.since ?? null,\n last: entry.poller.last,\n };\n }\n const elapsed = clock.now() - startedAt;\n return {\n started,\n draining,\n ready,\n alive,\n controllers,\n dependencies: dependenciesOut,\n checks,\n startup: { budget, elapsed, overBudget: !started && elapsed > budget },\n };\n };\n\n const answer = (kind: ProbeKind, pass: boolean, controller?: string): ProbeAnswer => ({\n status: pass || kind === \"report\" ? 200 : 503,\n contentType: \"application/health+json\",\n body: {\n status: pass ? \"pass\" : \"fail\",\n service: description.name,\n probe: kind,\n ...(controller === undefined ? {} : { controller }),\n ...(kind === \"report\" ? { verdict: verdict() } : {}),\n },\n });\n\n return {\n verdict,\n metrics: counts.metrics,\n probe(kind, controller) {\n const now = verdict();\n if (kind === \"startup\") return answer(kind, now.started);\n if (kind === \"liveness\") return answer(kind, now.alive);\n if (kind === \"report\") return answer(kind, now.ready && now.alive);\n if (controller === undefined) return answer(kind, now.ready);\n // only an own key is a controller: a name such as \"constructor\" is not one\n const known = Object.hasOwn(now.controllers, controller) ? now.controllers[controller] : undefined;\n if (known === undefined) throw new Error(`${description.name} has no controller ${controller}`);\n return answer(kind, known, controller);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n forceFail(name, on) {\n if (on) forced.add(name);\n else forced.delete(name);\n },\n drain() {\n if (draining) return;\n draining = true;\n changed();\n },\n stop() {\n stopped = true;\n budgetTimer?.();\n budgetTimer = null;\n for (const entry of entries.values()) {\n entry.poller.stop();\n entry.latch?.stop();\n }\n },\n beginStartup() {\n if (gate === \"closed\") moveGate(\"starting\", \"startup.begin\");\n },\n failStartup(cause) {\n if (gate === \"open\" || gate === \"failed\") return;\n moveGate(\"failed\", \"startup.fail\", cause);\n budgetTimer?.();\n budgetTimer = null;\n },\n async warmUp() {\n if (started || stopped || gate === \"failed\" || gate === \"sweeping\") return;\n moveGate(\"sweeping\", \"mark-ready\");\n // one bounded sweep of each check: each poll ends at its timeout at the latest\n const sweep = clock.now();\n await Promise.all([...entries.values()].map((entry) => entry.poller.pollNow()));\n if (stopped || gate !== \"sweeping\") return;\n for (const entry of entries.values())\n entry.poller.start(entry.poller.jittered() - (clock.now() - sweep));\n started = true;\n budgetTimer?.();\n budgetTimer = null;\n moveGate(\"open\", \"sweep.done\");\n changed();\n },\n addCheck(check, run) {\n if (entries.has(check.name)) throw new Error(`${description.name} already has a check named ${check.name}`);\n add(check, run, true);\n changed();\n },\n addDependency(name) {\n if (dependencies.has(name)) return;\n dependencies.add(name);\n lateDependencies.add(name);\n changed();\n },\n };\n};\n"],"mappings":";;;;;;;;;;AA8HA,MAAa,iBACX,aACA,MACA,UAAwB,CAAC,MACb;CACZ,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,SAAS,QAAQ,UAAU,KAAK;CACtC,MAAM,SAAS,IAAI,IAAI,QAAQ,aAAa,CAAC,CAAC;CAC9C,MAAM,YAAY,MAAM,IAAI;CAC5B,MAAM,SAAS,QAAQ,YAAY,SAAS,SAAS,IAAI;CACzD,MAAM,0BAAU,IAAI,IAAmB;CACvC,MAAM,eAAe,IAAI,IAAI,YAAY,aAAa,KAAK,eAAe,WAAW,IAAI,CAAC;CAE1F,MAAM,mCAAmB,IAAI,IAAY;CACzC,MAAM,4BAAY,IAAI,IAAsC;CAC5D,IAAI,UAAU;CACd,IAAI,WAAW;CACf,IAAI,UAAU;CAEd,IAAI,OAAO;CAEX,MAAM,SAAS,MAAM;CAErB,MAAM,UAAoB,UAAU;EAClC,OAAO,MAAM,KAAK;EAClB,QAAQ,SAAS,KAAK;CACxB;CACA,MAAM,UACH,SAAsB,cACtB,MAAM,IAAI,OACT,OAAO;EAAE,IAAI,MAAM,IAAI;EAAG;EAAS;EAAU;EAAM;EAAI;CAAG,CAAC;CAC/D,MAAM,Y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