@mark1russell7/service 0.5.12 → 0.5.14

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":"testing.js","names":[],"sources":["../src/fakes.ts","../src/contract.ts","../src/conformance.ts","../src/testing.ts"],"sourcesContent":["// The fakes of the runtime for tests: a fake clock gives exact, repeatable timing, a seeded random\n// gives the same jitter on each run, and a fake process takes signals and keeps the exit codes.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { ExitSignal, ExitTrigger, ProcessPort } from \"./process.ts\";\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n\n/** A fake process receives triggers from a test, and keeps each exit code in place of an exit. */\nexport interface FakeProcess extends ProcessPort {\n /** This method sends a signal to each handler of it. */\n signal(name: ExitSignal): void;\n /** This method sends a trigger to each handler of it: a signal, or a process trigger, for example `stdin-close`. */\n trigger(name: ExitTrigger): void;\n /** This method sends a message of the IPC channel to each handler of the trigger `ipc-message`. */\n message(value: unknown): void;\n /** These are the exit codes, in sequence. A correct runtime exits one time. */\n readonly exits: readonly number[];\n /** This count is the number of handlers that are registered. */\n readonly handlers: number;\n /** These are the triggers that have a handler, in the sequence of their first handler. */\n readonly triggers: readonly ExitTrigger[];\n /** These are the times of the clock of the options at each flush and each exit, when the options give a clock. */\n readonly log: readonly string[];\n /** This count is the number of flushes of the output. */\n readonly flushes: number;\n /** This count is the number of holds of the process that are not released. */\n readonly holds: number;\n /** These counts are the holds that were not released at each exit, in sequence. */\n readonly heldAtExit: readonly number[];\n}\n\n/** These options shape a fake process. */\nexport interface FakeProcessOptions {\n /** This function is the flush of the output, for example a wait on a fake clock. Without it, a flush ends at once. */\n readonly flush?: (() => Promise<void> | void) | undefined;\n /** This clock stamps each line of the log. */\n readonly clock?: Clock | undefined;\n}\n\n/** This function makes a fake process. */\nexport const fakeProcess = (options: FakeProcessOptions = {}): FakeProcess => {\n const handlers = new Map<ExitTrigger, Set<(message?: unknown) => void>>();\n const exits: number[] = [];\n const log: string[] = [];\n let flushes = 0;\n let holds = 0;\n const heldAtExit: number[] = [];\n const stamp = (what: string): void => {\n log.push(options.clock === undefined ? what : `${options.clock.now()} ${what}`);\n };\n const send = (name: ExitTrigger, message?: unknown): void => {\n for (const handler of [...(handlers.get(name) ?? [])]) handler(message);\n };\n return {\n on(trigger, handler) {\n const set = handlers.get(trigger) ?? new Set();\n set.add(handler);\n handlers.set(trigger, set);\n return () => {\n set.delete(handler);\n };\n },\n async flush() {\n stamp(\"flush\");\n await options.flush?.();\n flushes += 1;\n stamp(\"flushed\");\n },\n hold() {\n holds += 1;\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n holds -= 1;\n };\n },\n exit(code) {\n stamp(`exit ${code}`);\n heldAtExit.push(holds);\n exits.push(code);\n },\n signal: (name) => send(name),\n trigger: (name) => send(name),\n message: (value) => send(\"ipc-message\", value),\n get exits() {\n return [...exits];\n },\n get handlers() {\n let count = 0;\n for (const set of handlers.values()) count += set.size;\n return count;\n },\n get triggers() {\n return [...handlers.keys()];\n },\n get log() {\n return [...log];\n },\n get flushes() {\n return flushes;\n },\n get holds() {\n return holds;\n },\n get heldAtExit() {\n return [...heldAtExit];\n },\n };\n};\n\n/** This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). */\nexport const seeded = (seed: number): (() => number) => {\n let state = seed >>> 0;\n return () => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n","import { valueIn } from \"@mark1russell7/quantity\";\nimport type { ServiceBuilder } from \"./builder.ts\";\nimport type { Check, ServiceDescription } from \"./description.ts\";\nimport type { FakeClock } from \"./fakes.ts\";\nimport { fakeClock, seeded } from \"./fakes.ts\";\nimport type { Health, HealthVerdict, StartOptions } from \"./health.ts\";\nimport { failSpan, recoverSpan } from \"./timing.ts\";\n\n/** A contract case is one generated case of the contract test of a declaration. It throws on a failure. */\nexport interface ContractCase {\n readonly name: string;\n run(): Promise<void>;\n}\n\n/** These options tune the contract test. */\nexport interface ContractOptions {\n /** This number is the latency that a degraded dependency adds to each check, in milliseconds. The default of the contract is 100. */\n readonly degradeBy?: number | undefined;\n /** This number is the seed of the jitter. */\n readonly seed?: number | undefined;\n}\n\nconst ms = (amount: { readonly value: number; readonly unit: string }): number => valueIn(amount, \"ms\");\n\n/** The part of a verdict that the contract compares: what a caller and the platform see. */\nconst visible = (verdict: HealthVerdict) => ({\n ready: verdict.ready,\n alive: verdict.alive,\n controllers: verdict.controllers,\n dependencies: verdict.dependencies,\n});\n\nconst same = (expected: unknown, actual: unknown): boolean => JSON.stringify(expected) === JSON.stringify(actual);\n\nconst failure = (what: string, expected: unknown, actual: unknown): Error =>\n new Error(`${what}: expected ${JSON.stringify(expected)}, but the verdict was ${JSON.stringify(actual)}`);\n\n/**\n * This function generates the contract test of a declaration. `declare` gives a new builder with\n * the declaration and the function of each check, each time. The checks must pass at rest. The\n * cases are:\n * - The service at rest: each controller and each dependency is ready, and the service is alive.\n * - Each dependency unavailable: its polls fail at once (the force-fail list). The dependency and\n * each controller that needs it become not ready, and the other controllers stay ready. Liveness\n * stays, unless a liveness check exercises the dependency.\n * - Each dependency degraded: each call of its checks takes the latency longer. Nothing can fail.\n * - Each dependency recovers: after it is unavailable, the service is again at rest.\n * - A negative control: a client that the declaration does not name fails, and nothing changes.\n *\n * A dependency that no check exercises is a finding: the service cannot see it fail.\n */\nexport const contractCases = (declare: () => ServiceBuilder, options: ContractOptions = {}): ContractCase[] => {\n const degradeBy = options.degradeBy ?? 100;\n const seed = options.seed ?? 1;\n const description: ServiceDescription = declare().describe();\n const service = description.name;\n const gating = description.checks.filter((check) => check.gates !== null);\n const timingOf = (check: Check) => description.policies[check.gates!];\n const failMax = (check: Check): number => ms(failSpan(timingOf(check), check.poll, \"error\").max);\n const recoverMax = (check: Check): number => ms(recoverSpan(timingOf(check), check.poll).max);\n const most = (values: readonly number[]): number => values.reduce((a, b) => Math.max(a, b), 0);\n const settleTime = most(gating.filter((check) => check.gates === \"readiness\").map(recoverMax)) + 1;\n const quietTime = most(gating.map(failMax)) + 1;\n\n /** This function starts the declaration on a fake clock, and moves it to rest. */\n const boot = async (\n extra: (clock: FakeClock) => Partial<StartOptions> = () => ({}),\n ): Promise<{ health: Health; clock: FakeClock; rest: ReturnType<typeof visible> }> => {\n const clock = fakeClock();\n // the warm-up sweep can wait on the clock (a degraded check), thus the clock moves while it starts\n const starting = declare().start({ clock, random: seeded(seed), ...extra(clock) });\n let started = false;\n void starting.then(\n () => (started = true),\n () => (started = true),\n );\n for (let step = 0; step < 1000 && !started; step += 1) await clock.advance(10);\n const health = await starting;\n await clock.advance(settleTime);\n return { health, clock, rest: visible(health.verdict()) };\n };\n const stop = (health: Health): void => health.stop();\n\n const cases: ContractCase[] = [\n {\n name: `${service}: at rest, each controller and each dependency is ready, and the service is alive`,\n async run() {\n const { health, rest } = await boot();\n try {\n const expected = {\n ready: true,\n alive: true,\n controllers: Object.fromEntries(description.controllers.map((each) => [each.name, true])),\n dependencies: Object.fromEntries(description.dependencies.map((each) => [each.name, true])),\n };\n if (!same(expected, rest)) throw failure(\"at rest\", expected, rest);\n } finally {\n stop(health);\n }\n },\n },\n ];\n\n for (const dependency of description.dependencies) {\n const on = gating.filter((check) => check.dependency === dependency.name);\n const readiness = on.filter((check) => check.gates === \"readiness\");\n const liveness = on.filter((check) => check.gates === \"liveness\");\n const unavailable = (rest: ReturnType<typeof visible>) => ({\n ready: readiness.length === 0 ? rest.ready : false,\n alive: liveness.length === 0 ? rest.alive : false,\n controllers: Object.fromEntries(\n description.controllers.map((each) => [\n each.name,\n each.requires.includes(dependency.name) && readiness.length > 0 ? false : rest.controllers[each.name],\n ]),\n ),\n dependencies: { ...rest.dependencies, [dependency.name]: readiness.length === 0 },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} unavailable`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it fail`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n const now = visible(health.verdict());\n const expected = unavailable(rest);\n if (!same(expected, now)) throw failure(`${dependency.name} unavailable`, expected, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} degraded by ${degradeBy} ms, and nothing fails`,\n async run() {\n const tight = on.filter((check) => ms(check.poll.timeout) <= degradeBy);\n if (tight.length > 0)\n throw new Error(\n `${tight.map((check) => `${check.name} times out in ${ms(check.poll.timeout)} ms`).join(\", \")}: a latency of ${degradeBy} ms fails it`,\n );\n const { health, clock, rest } = await boot((at) => ({\n wrapCheck: (check, run) =>\n check.dependency !== dependency.name\n ? run\n : (signal) => new Promise((resolve) => at.after(degradeBy, () => resolve(run(signal)))),\n }));\n try {\n await clock.advance(quietTime + most(on.map((check) => ms(check.poll.interval))));\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} degraded`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} recovers`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it recover`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n health.forceFail(dependency.name, false);\n await clock.advance(most(on.map(recoverMax)) + 1);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} recovered`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n }\n\n const never = `${service}.client-never-registered`;\n cases.push({\n name: `${service}: a client never registered fails, and nothing changes (the negative control)`,\n async run() {\n if (description.dependencies.some((each) => each.name === never))\n throw new Error(`the declaration has a dependency named ${never}`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(never, true);\n await clock.advance(quietTime);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(\"the negative control\", rest, now);\n } finally {\n stop(health);\n }\n // and a check on a client never registered is refused before the start\n let refused = false;\n try {\n declare()\n .check({\n name: `${never}.check`,\n dependency: never,\n step: \"round-trip\",\n ownConnection: true,\n gates: null,\n poll: gating[0]?.poll ?? { interval: { value: 1, unit: \"s\" }, jitter: 0, timeout: { value: 0.5, unit: \"s\" } },\n })\n .describe();\n } catch {\n refused = true;\n }\n if (!refused) throw new Error(`the declaration accepted a check on ${never}, which is not a dependency`);\n },\n });\n\n return cases;\n};\n","import type { Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.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 /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\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, 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/** 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 /** 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();\nconst turn = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\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 */\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: sleep };\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 return cases;\n};\n","// @mark1russell7/service/testing: the seams of the runtime for tests. A fake clock gives exact,\n// repeatable timing. A seeded random gives the same jitter on each run. A fake process takes\n// signals and keeps the exit codes. A quiet server answers until it goes quiet, and then it holds\n// its connections open without an answer. `contractCases` generates the contract test of a\n// declaration, and `transportConformance` generates the conformance test of a transport.\n\nimport type { AddressInfo, Server, Socket } from \"node:net\";\nimport { createServer } from \"node:net\";\nimport type { Outcome } from \"./latch.ts\";\nimport type { CheckFn } from \"./poller.ts\";\n\nexport type { FakeClock, FakeProcess, FakeProcessOptions } from \"./fakes.ts\";\nexport { fakeClock, fakeProcess, seeded } from \"./fakes.ts\";\nexport type { ContractCase, ContractOptions } from \"./contract.ts\";\nexport { contractCases } from \"./contract.ts\";\nexport type {\n ConformanceOptions,\n ConformanceRecord,\n HeldWork,\n SubjectFactory,\n TransportSubject,\n} from \"./conformance.ts\";\nexport { detachedLifecycle, transportConformance } from \"./conformance.ts\";\n\n/**\n * A behavior is what a scripted check does when the runtime starts it:\n * - `\"ok\"`, `\"error\"` and `\"indeterminate\"` give that outcome at once.\n * - `\"throw\"` throws at once.\n * - `\"timeout\"` gives no answer until the runtime aborts the use at the timeout of the poll.\n * - `\"hang\"` gives no answer, and it ignores the abort, until `heal()`.\n */\nexport type Behavior = Outcome | \"throw\" | \"timeout\" | \"hang\";\n\n/** A scripted check is a check function whose behavior a test sets. */\nexport interface ScriptedCheck {\n readonly run: CheckFn;\n /** This behavior applies to each later call. */\n behavior: Behavior;\n /** This count is the number of calls of the check. */\n readonly calls: number;\n /** This count is the number of calls that are pending. */\n readonly hung: number;\n /** This method ends each hung call with a pass, as when a driver gets its answer late. */\n heal(): void;\n}\n\n/** This function makes a scripted check with a behavior at the start. */\nexport const scriptedCheck = (behavior: Behavior = \"ok\"): ScriptedCheck => {\n let calls = 0;\n const hung = new Set<() => void>();\n const script: ScriptedCheck = {\n behavior,\n get calls() {\n return calls;\n },\n get hung() {\n return hung.size;\n },\n heal() {\n for (const end of [...hung]) end();\n },\n run: (signal) => {\n calls += 1;\n const now = script.behavior;\n if (now === \"throw\") throw new Error(\"the scripted check threw\");\n if (now === \"timeout\")\n return new Promise<Outcome>((_, reject) =>\n signal.addEventListener(\"abort\", () => reject(new Error(\"aborted at the timeout\"))),\n );\n if (now === \"hang\")\n return new Promise<Outcome>((resolve) => {\n const end = (): void => {\n hung.delete(end);\n resolve(\"ok\");\n };\n hung.add(end);\n });\n return now;\n },\n };\n return script;\n};\n\n/** A quiet server is a TCP echo server that can stop its answers and keep its connections open. */\nexport interface QuietServer {\n readonly port: number;\n /** This method stops the answers. The connections stay open, and the server reads and discards the data. */\n quiet(): void;\n /** This method starts the answers again. */\n speak(): void;\n /** This count is the number of open connections. */\n readonly connections: number;\n close(): Promise<void>;\n}\n\n/**\n * This function starts a quiet server on the loopback address. A check against it passes while it\n * answers. When it goes quiet, the check sees a connection that is open but silent. A frozen peer\n * and a black hole that keeps the connection look the same.\n */\nexport const quietServer = async (): Promise<QuietServer> => {\n let silent = false;\n const sockets = new Set<Socket>();\n const server: Server = createServer((socket) => {\n sockets.add(socket);\n socket.on(\"close\", () => sockets.delete(socket));\n socket.on(\"error\", () => sockets.delete(socket));\n socket.on(\"data\", (chunk) => {\n if (!silent) socket.write(chunk);\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n return {\n port: (server.address() as AddressInfo).port,\n quiet: () => {\n silent = true;\n },\n speak: () => {\n silent = false;\n },\n get connections() {\n return sockets.size;\n },\n close: () =>\n new Promise<void>((resolve) => {\n for (const socket of sockets) socket.destroy();\n server.close(() => resolve());\n }),\n };\n};\n"],"mappings":";;;;;;AAoBA,MAAM,SAAS,YAA2B;CACxC,KAAK,IAAI,OAAO,GAAG,OAAO,IAAI,QAAQ,GAAG,MAAM,QAAQ,QAAQ;AACjE;;AAGA,MA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,IAAI,IAAY;CAChC,MAAM,SAAiB,cAAc,WAAW;EAC9C,QAAQ,IAAI,MAAM;EAClB,OAAO,GAAG,eAAe,QAAQ,OAAO,MAAM,CAAC;EAC/C,OAAO,GAAG,eAAe,QAAQ,OAAO,MAAM,CAAC;EAC/C,OAAO,GAAG,SAAS,UAAU;GAC3B,IAAI,CAAC,QAAQ,OAAO,MAAM,KAAK;EACjC,CAAC;CACH,CAAC;CACD,MAAM,IAAI,SAAe,SAAS,WAAW;EAC3C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,GAAG,mBAAmB,QAAQ,CAAC;CAC/C,CAAC;CACD,OAAO;EACL,MAAO,OAAO,QAAQ,CAAC,CAAiB;EACxC,aAAa;GACX,SAAS;EACX;EACA,aAAa;GACX,SAAS;EACX;EACA,IAAI,cAAc;GAChB,OAAO,QAAQ;EACjB;EACA,aACE,IAAI,SAAe,YAAY;GAC7B,KAAK,MAAM,UAAU,SAAS,OAAO,QAAQ;GAC7C,OAAO,YAAY,QAAQ,CAAC;EAC9B,CAAC;CACL;AACF"}
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/fakes.ts","../src/contract.ts","../src/conformance.ts","../src/testing.ts"],"sourcesContent":["// The fakes of the runtime for tests: a fake clock gives exact, repeatable timing, a seeded random\n// gives the same jitter on each run, and a fake process takes signals and keeps the exit codes.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { ExitSignal, ExitTrigger, ProcessPort } from \"./process.ts\";\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n\n/** A fake process receives triggers from a test, and keeps each exit code in place of an exit. */\nexport interface FakeProcess extends ProcessPort {\n /** This method sends a signal to each handler of it. */\n signal(name: ExitSignal): void;\n /** This method sends a trigger to each handler of it: a signal, or a process trigger, for example `stdin-close`. */\n trigger(name: ExitTrigger): void;\n /** This method sends a message of the IPC channel to each handler of the trigger `ipc-message`. */\n message(value: unknown): void;\n /** These are the exit codes, in sequence. A correct runtime exits one time. */\n readonly exits: readonly number[];\n /** This count is the number of handlers that are registered. */\n readonly handlers: number;\n /** These are the triggers that have a handler, in the sequence of their first handler. */\n readonly triggers: readonly ExitTrigger[];\n /** These are the times of the clock of the options at each flush and each exit, when the options give a clock. */\n readonly log: readonly string[];\n /** This count is the number of flushes of the output. */\n readonly flushes: number;\n /** This count is the number of holds of the process that are not released. */\n readonly holds: number;\n /** These counts are the holds that were not released at each exit, in sequence. */\n readonly heldAtExit: readonly number[];\n}\n\n/** These options shape a fake process. */\nexport interface FakeProcessOptions {\n /** This function is the flush of the output, for example a wait on a fake clock. Without it, a flush ends at once. */\n readonly flush?: (() => Promise<void> | void) | undefined;\n /** This clock stamps each line of the log. */\n readonly clock?: Clock | undefined;\n}\n\n/** This function makes a fake process. */\nexport const fakeProcess = (options: FakeProcessOptions = {}): FakeProcess => {\n const handlers = new Map<ExitTrigger, Set<(message?: unknown) => void>>();\n const exits: number[] = [];\n const log: string[] = [];\n let flushes = 0;\n let holds = 0;\n const heldAtExit: number[] = [];\n const stamp = (what: string): void => {\n log.push(options.clock === undefined ? what : `${options.clock.now()} ${what}`);\n };\n const send = (name: ExitTrigger, message?: unknown): void => {\n for (const handler of [...(handlers.get(name) ?? [])]) handler(message);\n };\n return {\n on(trigger, handler) {\n const set = handlers.get(trigger) ?? new Set();\n set.add(handler);\n handlers.set(trigger, set);\n return () => {\n set.delete(handler);\n };\n },\n async flush() {\n stamp(\"flush\");\n await options.flush?.();\n flushes += 1;\n stamp(\"flushed\");\n },\n hold() {\n holds += 1;\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n holds -= 1;\n };\n },\n exit(code) {\n stamp(`exit ${code}`);\n heldAtExit.push(holds);\n exits.push(code);\n },\n signal: (name) => send(name),\n trigger: (name) => send(name),\n message: (value) => send(\"ipc-message\", value),\n get exits() {\n return [...exits];\n },\n get handlers() {\n let count = 0;\n for (const set of handlers.values()) count += set.size;\n return count;\n },\n get triggers() {\n return [...handlers.keys()];\n },\n get log() {\n return [...log];\n },\n get flushes() {\n return flushes;\n },\n get holds() {\n return holds;\n },\n get heldAtExit() {\n return [...heldAtExit];\n },\n };\n};\n\n/** This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). */\nexport const seeded = (seed: number): (() => number) => {\n let state = seed >>> 0;\n return () => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n","import { valueIn } from \"@mark1russell7/quantity\";\nimport type { ServiceBuilder } from \"./builder.ts\";\nimport type { Check, ServiceDescription } from \"./description.ts\";\nimport type { FakeClock } from \"./fakes.ts\";\nimport { fakeClock, seeded } from \"./fakes.ts\";\nimport type { Health, HealthVerdict, StartOptions } from \"./health.ts\";\nimport { failSpan, recoverSpan } from \"./timing.ts\";\n\n/** A contract case is one generated case of the contract test of a declaration. It throws on a failure. */\nexport interface ContractCase {\n readonly name: string;\n run(): Promise<void>;\n}\n\n/** These options tune the contract test. */\nexport interface ContractOptions {\n /** This number is the latency that a degraded dependency adds to each check, in milliseconds. The default of the contract is 100. */\n readonly degradeBy?: number | undefined;\n /** This number is the seed of the jitter. */\n readonly seed?: number | undefined;\n}\n\nconst ms = (amount: { readonly value: number; readonly unit: string }): number => valueIn(amount, \"ms\");\n\n/** The part of a verdict that the contract compares: what a caller and the platform see. */\nconst visible = (verdict: HealthVerdict) => ({\n ready: verdict.ready,\n alive: verdict.alive,\n controllers: verdict.controllers,\n dependencies: verdict.dependencies,\n});\n\nconst same = (expected: unknown, actual: unknown): boolean => JSON.stringify(expected) === JSON.stringify(actual);\n\nconst failure = (what: string, expected: unknown, actual: unknown): Error =>\n new Error(`${what}: expected ${JSON.stringify(expected)}, but the verdict was ${JSON.stringify(actual)}`);\n\n/**\n * This function generates the contract test of a declaration. `declare` gives a new builder with\n * the declaration and the function of each check, each time. The checks must pass at rest. The\n * cases are:\n * - The service at rest: each controller and each dependency is ready, and the service is alive.\n * - Each dependency unavailable: its polls fail at once (the force-fail list). The dependency and\n * each controller that needs it become not ready, and the other controllers stay ready. Liveness\n * stays, unless a liveness check exercises the dependency.\n * - Each dependency degraded: each call of its checks takes the latency longer. Nothing can fail.\n * - Each dependency recovers: after it is unavailable, the service is again at rest.\n * - A negative control: a client that the declaration does not name fails, and nothing changes.\n *\n * A dependency that no check exercises is a finding: the service cannot see it fail.\n */\nexport const contractCases = (declare: () => ServiceBuilder, options: ContractOptions = {}): ContractCase[] => {\n const degradeBy = options.degradeBy ?? 100;\n const seed = options.seed ?? 1;\n const description: ServiceDescription = declare().describe();\n const service = description.name;\n const gating = description.checks.filter((check) => check.gates !== null);\n const timingOf = (check: Check) => description.policies[check.gates!];\n const failMax = (check: Check): number => ms(failSpan(timingOf(check), check.poll, \"error\").max);\n const recoverMax = (check: Check): number => ms(recoverSpan(timingOf(check), check.poll).max);\n const most = (values: readonly number[]): number => values.reduce((a, b) => Math.max(a, b), 0);\n const settleTime = most(gating.filter((check) => check.gates === \"readiness\").map(recoverMax)) + 1;\n const quietTime = most(gating.map(failMax)) + 1;\n\n /** This function starts the declaration on a fake clock, and moves it to rest. */\n const boot = async (\n extra: (clock: FakeClock) => Partial<StartOptions> = () => ({}),\n ): Promise<{ health: Health; clock: FakeClock; rest: ReturnType<typeof visible> }> => {\n const clock = fakeClock();\n // the warm-up sweep can wait on the clock (a degraded check), thus the clock moves while it starts\n const starting = declare().start({ clock, random: seeded(seed), ...extra(clock) });\n let started = false;\n void starting.then(\n () => (started = true),\n () => (started = true),\n );\n for (let step = 0; step < 1000 && !started; step += 1) await clock.advance(10);\n const health = await starting;\n await clock.advance(settleTime);\n return { health, clock, rest: visible(health.verdict()) };\n };\n const stop = (health: Health): void => health.stop();\n\n const cases: ContractCase[] = [\n {\n name: `${service}: at rest, each controller and each dependency is ready, and the service is alive`,\n async run() {\n const { health, rest } = await boot();\n try {\n const expected = {\n ready: true,\n alive: true,\n controllers: Object.fromEntries(description.controllers.map((each) => [each.name, true])),\n dependencies: Object.fromEntries(description.dependencies.map((each) => [each.name, true])),\n };\n if (!same(expected, rest)) throw failure(\"at rest\", expected, rest);\n } finally {\n stop(health);\n }\n },\n },\n ];\n\n for (const dependency of description.dependencies) {\n const on = gating.filter((check) => check.dependency === dependency.name);\n const readiness = on.filter((check) => check.gates === \"readiness\");\n const liveness = on.filter((check) => check.gates === \"liveness\");\n const unavailable = (rest: ReturnType<typeof visible>) => ({\n ready: readiness.length === 0 ? rest.ready : false,\n alive: liveness.length === 0 ? rest.alive : false,\n controllers: Object.fromEntries(\n description.controllers.map((each) => [\n each.name,\n each.requires.includes(dependency.name) && readiness.length > 0 ? false : rest.controllers[each.name],\n ]),\n ),\n dependencies: { ...rest.dependencies, [dependency.name]: readiness.length === 0 },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} unavailable`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it fail`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n const now = visible(health.verdict());\n const expected = unavailable(rest);\n if (!same(expected, now)) throw failure(`${dependency.name} unavailable`, expected, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} degraded by ${degradeBy} ms, and nothing fails`,\n async run() {\n const tight = on.filter((check) => ms(check.poll.timeout) <= degradeBy);\n if (tight.length > 0)\n throw new Error(\n `${tight.map((check) => `${check.name} times out in ${ms(check.poll.timeout)} ms`).join(\", \")}: a latency of ${degradeBy} ms fails it`,\n );\n const { health, clock, rest } = await boot((at) => ({\n wrapCheck: (check, run) =>\n check.dependency !== dependency.name\n ? run\n : (signal) => new Promise((resolve) => at.after(degradeBy, () => resolve(run(signal)))),\n }));\n try {\n await clock.advance(quietTime + most(on.map((check) => ms(check.poll.interval))));\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} degraded`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} recovers`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it recover`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n health.forceFail(dependency.name, false);\n await clock.advance(most(on.map(recoverMax)) + 1);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} recovered`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n }\n\n const never = `${service}.client-never-registered`;\n cases.push({\n name: `${service}: a client never registered fails, and nothing changes (the negative control)`,\n async run() {\n if (description.dependencies.some((each) => each.name === never))\n throw new Error(`the declaration has a dependency named ${never}`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(never, true);\n await clock.advance(quietTime);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(\"the negative control\", rest, now);\n } finally {\n stop(health);\n }\n // and a check on a client never registered is refused before the start\n let refused = false;\n try {\n declare()\n .check({\n name: `${never}.check`,\n dependency: never,\n step: \"round-trip\",\n ownConnection: true,\n gates: null,\n poll: gating[0]?.poll ?? { interval: { value: 1, unit: \"s\" }, jitter: 0, timeout: { value: 0.5, unit: \"s\" } },\n })\n .describe();\n } catch {\n refused = true;\n }\n if (!refused) throw new Error(`the declaration accepted a check on ${never}, which is not a dependency`);\n },\n });\n\n return cases;\n};\n","import type { Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.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 /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\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/** 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 /** 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();\nconst turn = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\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 */\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: sleep };\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 return cases;\n};\n","// @mark1russell7/service/testing: the seams of the runtime for tests. A fake clock gives exact,\n// repeatable timing. A seeded random gives the same jitter on each run. A fake process takes\n// signals and keeps the exit codes. A quiet server answers until it goes quiet, and then it holds\n// its connections open without an answer. `contractCases` generates the contract test of a\n// declaration, and `transportConformance` generates the conformance test of a transport.\n\nimport type { AddressInfo, Server, Socket } from \"node:net\";\nimport { createServer } from \"node:net\";\nimport type { Outcome } from \"./latch.ts\";\nimport type { CheckFn } from \"./poller.ts\";\n\nexport type { FakeClock, FakeProcess, FakeProcessOptions } from \"./fakes.ts\";\nexport { fakeClock, fakeProcess, seeded } from \"./fakes.ts\";\nexport type { ContractCase, ContractOptions } from \"./contract.ts\";\nexport { contractCases } from \"./contract.ts\";\nexport type {\n ConformanceOptions,\n ConformanceRecord,\n HeldWork,\n SubjectFactory,\n TransportSubject,\n} from \"./conformance.ts\";\nexport { detachedLifecycle, transportConformance } from \"./conformance.ts\";\n\n/**\n * A behavior is what a scripted check does when the runtime starts it:\n * - `\"ok\"`, `\"error\"` and `\"indeterminate\"` give that outcome at once.\n * - `\"throw\"` throws at once.\n * - `\"timeout\"` gives no answer until the runtime aborts the use at the timeout of the poll.\n * - `\"hang\"` gives no answer, and it ignores the abort, until `heal()`.\n */\nexport type Behavior = Outcome | \"throw\" | \"timeout\" | \"hang\";\n\n/** A scripted check is a check function whose behavior a test sets. */\nexport interface ScriptedCheck {\n readonly run: CheckFn;\n /** This behavior applies to each later call. */\n behavior: Behavior;\n /** This count is the number of calls of the check. */\n readonly calls: number;\n /** This count is the number of calls that are pending. */\n readonly hung: number;\n /** This method ends each hung call with a pass, as when a driver gets its answer late. */\n heal(): void;\n}\n\n/** This function makes a scripted check with a behavior at the start. */\nexport const scriptedCheck = (behavior: Behavior = \"ok\"): ScriptedCheck => {\n let calls = 0;\n const hung = new Set<() => void>();\n const script: ScriptedCheck = {\n behavior,\n get calls() {\n return calls;\n },\n get hung() {\n return hung.size;\n },\n heal() {\n for (const end of [...hung]) end();\n },\n run: (signal) => {\n calls += 1;\n const now = script.behavior;\n if (now === \"throw\") throw new Error(\"the scripted check threw\");\n if (now === \"timeout\")\n return new Promise<Outcome>((_, reject) =>\n signal.addEventListener(\"abort\", () => reject(new Error(\"aborted at the timeout\"))),\n );\n if (now === \"hang\")\n return new Promise<Outcome>((resolve) => {\n const end = (): void => {\n hung.delete(end);\n resolve(\"ok\");\n };\n hung.add(end);\n });\n return now;\n },\n };\n return script;\n};\n\n/** A quiet server is a TCP echo server that can stop its answers and keep its connections open. */\nexport interface QuietServer {\n readonly port: number;\n /** This method stops the answers. The connections stay open, and the server reads and discards the data. */\n quiet(): void;\n /** This method starts the answers again. */\n speak(): void;\n /** This count is the number of open connections. */\n readonly connections: number;\n close(): Promise<void>;\n}\n\n/**\n * This function starts a quiet server on the loopback address. A check against it passes while it\n * answers. When it goes quiet, the check sees a connection that is open but silent. A frozen peer\n * and a black hole that keeps the connection look the same.\n */\nexport const quietServer = async (): Promise<QuietServer> => {\n let silent = false;\n const sockets = new Set<Socket>();\n const server: Server = createServer((socket) => {\n sockets.add(socket);\n socket.on(\"close\", () => sockets.delete(socket));\n socket.on(\"error\", () => sockets.delete(socket));\n socket.on(\"data\", (chunk) => {\n if (!silent) socket.write(chunk);\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n return {\n port: (server.address() as AddressInfo).port,\n quiet: () => {\n silent = true;\n },\n speak: () => {\n silent = false;\n },\n get connections() {\n return sockets.size;\n },\n close: () =>\n new Promise<void>((resolve) => {\n for (const socket of sockets) socket.destroy();\n server.close(() => resolve());\n }),\n };\n};\n"],"mappings":";;;;;;AAoBA,MAAM,SAAS,YAA2B;CACxC,KAAK,IAAI,OAAO,GAAG,OAAO,IAAI,QAAQ,GAAG,MAAM,QAAQ,QAAQ;AACjE;;AAGA,MAAa,aAAa,QAAQ,MAAiB;CACjD,IAAI,MAAM;CACV,IAAI,WAAW;CACf,MAAM,SAA+E,CAAC;CACtF,MAAM,OAAO,QAAgB;EAC3B,IAAI;EACJ,KAAK,MAAM,SAAS,QAClB,IAAI,MAAM,QAAQ,MAAM,MAAM,QAAQ,SAAS,KAAA,KAAa,MAAM,KAAK,KAAK,MAAO,MAAM,OAAO,KAAK,MAAM,MAAM,QAAQ,KAAK,QAC5H,OAAO;EACX,OAAO;CACT;CACA,OAAO;EACL,WAAW;EACX,MAAM,IAAI,KAAa;GACrB,MAAM,QAAQ;IAAE,IAAI,MAAM,KAAK,IAAI,GAAG,EAAE;IAAG,OAAO;IAAY;IAAK,MAAM;GAAK;GAC9E,OAAO,KAAK,KAAK;GACjB,aAAa;IACX,MAAM,OAAO;GACf;EACF;EACA,MAAM,QAAQ,IAAI;GAEhB,MAAM,MAAM,MAAM,KAAK,IAAI,GAAG,EAAE;GAChC,MAAM,OAAO;GACb,SAAS;IACP,MAAM,QAAQ,IAAI,GAAG;IACrB,IAAI,UAAU,KAAA,GAAW;IACzB,M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}
@@ -0,0 +1,275 @@
1
+ import { jt as Operation, nt as Poll } from "./lifecycle-CMedxaQd.js";
2
+ import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, m as RetrySchedule, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, x as retrySchedule, y as retryBackoff } from "./core-D8iXeoE4.js";
3
+ import { n as statusLineJudge, t as Judge } from "./dial-DJolDmOK.js";
4
+ import { Extent, Quantity } from "@mark1russell7/quantity";
5
+ import { Machine } from "@mark1russell7/algebra";
6
+ //#region src/websocket/connection.d.ts
7
+ /**
8
+ * These are the listeners of one connection. The connection holds each event until the client
9
+ * listens. Thus an event that comes between the creation and the listen does not go away.
10
+ */
11
+ interface WsListeners {
12
+ /** This event tells that the upgrade ended with 101, and the connection can send. */
13
+ open(): void;
14
+ /** This event gives one message of the server. A text message is UTF-8 in the buffer. */
15
+ message(data: Buffer, binary: boolean): void;
16
+ /** This event gives the payload of one pong frame. */
17
+ pong(data: Buffer): void;
18
+ /** This event tells that the connection closed, with the code and the reason of the close frame. Code 1006 tells that no close frame came. */
19
+ close(code: number, reason: string): void;
20
+ /** This event gives an error of the connection. A close follows it. */
21
+ error(error: Error): void;
22
+ }
23
+ /**
24
+ * A connection is the part of a `WebSocket` of ws 8 that the wrapper uses. A fake for tests has
25
+ * each part too. Thus the package depends on no type of ws.
26
+ */
27
+ interface WsConnection {
28
+ /** This method gives the listeners of the connection. The connection then gives each event that it holds. */
29
+ listen(listeners: WsListeners): void;
30
+ /** This method writes one message. The callback gets an error when the write fails. It throws while the connection is not open. */
31
+ send(data: string | Buffer, callback: (error?: Error) => void): void;
32
+ /** This method writes one ping frame with this payload. It throws while the connection is not open. */
33
+ ping(data: Buffer): void;
34
+ /** This method writes a close frame, and waits for the close frame of the server. It destroys nothing. */
35
+ close(code: number, reason: string): void;
36
+ /** This method destroys the socket at once. The cells measured 0.3 ms to 1 ms from the call to the close of the socket. */
37
+ terminate(): void;
38
+ /** This field holds the socket after the upgrade, or undefined before it. The join reads its addresses. */
39
+ readonly socket: ClientSocket | undefined;
40
+ /** This text is the subprotocol that the server chose, or "" when it chose none. */
41
+ readonly protocol: string;
42
+ }
43
+ /**
44
+ * These are the options that the wrapper gives `new WebSocket(url, protocols, options)` of ws. Each
45
+ * time comes from the declaration. ws gives the options that it does not read to `net.connect`.
46
+ */
47
+ interface WsDriverOptions {
48
+ /** This time bounds the TCP connect and the upgrade, in milliseconds. */
49
+ readonly handshakeTimeout: number;
50
+ /** ws answers each ping of the server with a pong. The heartbeat of the server then finds the client alive. */
51
+ readonly autoPong: true;
52
+ /** This time bounds the close handshake of ws, in milliseconds. The wrapper gives its own bound, `close_bound`. */
53
+ readonly closeTimeout: number;
54
+ /** ws sets no keepalive on its socket. The wrapper turns it on only when the declaration gives an idle time. */
55
+ readonly keepAlive: boolean;
56
+ /** This time is the idle time of TCP keepalive, in milliseconds. Node truncates it to whole seconds. */
57
+ readonly keepAliveInitialDelay?: number | undefined;
58
+ /** These headers go with the upgrade request, for example `authorization`. */
59
+ readonly headers?: Readonly<Record<string, string>> | undefined;
60
+ }
61
+ /** These are the arguments of `new WebSocket(url, protocols, options)`. */
62
+ interface WsConnectOptions {
63
+ readonly url: string;
64
+ readonly protocols: readonly string[];
65
+ readonly options: WsDriverOptions;
66
+ }
67
+ /** A connection factory makes one connection from its options. The connection opens later, and tells it with the event `open`. */
68
+ type WsFactory = Factory<WsConnectOptions, WsConnection>;
69
+ /** This type is the part of a `WebSocket` of ws 8 that the adapter uses. */
70
+ interface WsDriver {
71
+ on(event: string, listener: (...args: never[]) => void): unknown;
72
+ send(data: string | Buffer, callback: (error?: Error | null) => void): void;
73
+ ping(data: Buffer): void;
74
+ close(code: number, reason: string): void;
75
+ terminate(): void;
76
+ readonly protocol: string;
77
+ }
78
+ /**
79
+ * This function adapts a `WebSocket` of ws to a connection. It listens to `error` at once, because
80
+ * in Node an error with no listener throws. It takes the socket from the event `upgrade`.
81
+ */
82
+ export declare const adaptWs: (ws: WsDriver) => WsConnection;
83
+ /**
84
+ * This factory makes a `WebSocket` of ws. It loads ws only when a client connects, thus a service
85
+ * that does not use WebSocket does not need it. The specifier is a value, thus the package needs no types of ws.
86
+ */
87
+ export declare const nodeWs: WsFactory;
88
+ //#endregion
89
+ //#region src/websocket/client.d.ts
90
+ /**
91
+ * These are the knobs of the client, each a time, by the names of the ordering law. The runtime has
92
+ * no defaults, thus each knob is necessary. A bound that nobody gives is "infinite", not zero. The
93
+ * constant `WS_CLIENT_STARTING_KNOBS` gives a declaration from the WS cells. The knobs that each client has come from the core.
94
+ */
95
+ interface WsKnobs extends ClientKnobs, RetryKnobs {
96
+ /** This time bounds the TCP connect and the upgrade (`handshakeTimeout` of ws). The wrapper also bounds the open with it. */
97
+ readonly connect_bound: Quantity;
98
+ /** This time bounds each call: a request until its reply, and a ping until its pong. The wrapper has this timer, because ws has none. */
99
+ readonly request_timeout: Quantity;
100
+ /** This time is the interval of the ping frames of the heartbeat, from the start of one to the start of the next. "infinite" sends no ping. */
101
+ readonly heartbeat_interval: Extent;
102
+ /** This time bounds each ping of the heartbeat. A ping with no pong in this time is a miss. */
103
+ readonly heartbeat_timeout: Quantity;
104
+ /** This time is the first delay before a new try to connect. The delay doubles after each try. */
105
+ readonly retry_base: Quantity;
106
+ /** This time is the most that one delay can be, before its jitter. */
107
+ readonly retry_cap: Quantity;
108
+ /** This time is the idle time of TCP keepalive (`keepAliveInitialDelay`), in whole seconds. "infinite" keeps keepalive off, as ws does. */
109
+ readonly keepalive_idle: Extent;
110
+ /** The client does not replace its connection at an age, thus this knob must be "infinite". */
111
+ readonly max_connection_age: Extent;
112
+ /** This time bounds the close at the shutdown: the calls in flight, then the close handshake. At the bound, `terminate()` destroys the socket. */
113
+ readonly close_bound: Quantity;
114
+ }
115
+ /** A reply is the id of the request that a message answers, and the error of the server when the reply tells one. */
116
+ interface WsReply {
117
+ readonly id: string;
118
+ readonly error?: string | undefined;
119
+ }
120
+ /**
121
+ * The replies of a protocol tell which message of the server answers which request. WebSocket has no
122
+ * reply of its own: each application protocol puts an id in its messages, for example JSON-RPC 2.0.
123
+ */
124
+ interface WsReplies {
125
+ /** This function reads one message of the server. It gives its reply, or null for a message that answers no request. */
126
+ reply(data: Buffer, binary: boolean): WsReply | null;
127
+ }
128
+ /** A WebSocket client spec is the declaration of one WebSocket client: where it connects, and its knobs. */
129
+ interface WsClientSpec extends ClientSpec<WsKnobs> {
130
+ /** This path is the path of the upgrade request. The default is "/". */
131
+ readonly path?: string | undefined;
132
+ /** These names are the subprotocols that the client offers (`Sec-WebSocket-Protocol`). */
133
+ readonly protocols?: readonly string[] | undefined;
134
+ /** These headers go with the upgrade request and with the dial, for example `authorization`. */
135
+ readonly headers?: Readonly<Record<string, string>> | undefined;
136
+ /** This count is the number of heartbeat misses in sequence that end the connection. The cells used 1. */
137
+ readonly heartbeatMisses: number;
138
+ /** These replies match a message of the server to its request. Without them, the client sends no request. */
139
+ readonly replies?: WsReplies | undefined;
140
+ /**
141
+ * These operations are the calls of the service, by name, with their idempotency. A message does
142
+ * not tell if the server removes its duplicates. Thus the client sends again only a call that this table names, and a ping.
143
+ */
144
+ readonly operations?: ClientSpec<WsKnobs>["operations"];
145
+ }
146
+ /** These options make a client. Without them, it uses ws, the real clock, `Math.random`, and a dial with the upgrade request. */
147
+ interface WsClientOptions extends ClientOptions<WsFactory> {
148
+ readonly random?: (() => number) | undefined;
149
+ /**
150
+ * This function waits one turn of the event loop. The heartbeat waits it before it counts a miss,
151
+ * thus a pong that is in the socket counts first. The default is `setImmediate`.
152
+ */
153
+ readonly turn?: (() => Promise<void>) | undefined;
154
+ }
155
+ /** A join is one generation of the client: one connection, when its upgrade ended with 101 (D1, D2). WebSocket gives no id of a connection. */
156
+ interface WsJoin extends ClientJoin {
157
+ /** This URL is the URL of the connection. */
158
+ readonly url: string;
159
+ /** This text is the subprotocol that the server chose, or "" when it chose none. */
160
+ readonly protocol: string;
161
+ }
162
+ /** A request is one message to the server, with the id that its reply gives back. */
163
+ interface WsRequest {
164
+ readonly id: string;
165
+ /** This data goes as one message. A string goes as a text message, and a buffer as a binary message. */
166
+ readonly data: string | Buffer;
167
+ }
168
+ /** A response is the message of the server that answered a request. */
169
+ interface WsResponse {
170
+ readonly data: Buffer;
171
+ readonly binary: boolean;
172
+ }
173
+ /** A message listener receives each message of the server that answers no request. */
174
+ type WsMessageListener = (data: Buffer, binary: boolean) => void;
175
+ /** A WebSocket client is a dependency of a service: its declaration, its handle, its checks and its calls. */
176
+ interface WsClient extends Client<ClientStep, WsJoin> {
177
+ /** This text is the state of the client, as `WS_CLIENT_MACHINE` names it. */
178
+ readonly status: string;
179
+ /**
180
+ * This method sends a request, and waits for its reply. A reply is `ok`, or a certain error when it
181
+ * tells one. The client sends again only an idempotent operation, one time at most, after an outcome that is not certain.
182
+ */
183
+ request(operation: string, call: WsRequest, options?: SendOptions): Promise<Sent<WsResponse>>;
184
+ /** This method sends a ping frame, and waits for a pong. A pong is `ok`. A ping is idempotent, thus the client can send it again. */
185
+ ping(options?: SendOptions): Promise<Sent<void>>;
186
+ /** This method sends one message with no reply. It gives true when ws took the message, and false when the client is not ready. */
187
+ send(data: string | Buffer): boolean;
188
+ /** This method adds a listener of the messages that answer no request. It gives the function that removes it. */
189
+ onMessage(listener: WsMessageListener): () => void;
190
+ }
191
+ /** These operations are in each table: a ping frame is idempotent (RFC 6455 §5.5.2). */
192
+ export declare const WS_OPERATIONS: Readonly<Record<string, Operation>>;
193
+ /** This function gives the problems of a spec: the knobs that the client cannot use. */
194
+ export declare const specProblems: (name: string, spec: WsClientSpec) => string[];
195
+ /** This function gives the URL of a spec. The client speaks ws:// only. */
196
+ export declare const wsUrl: (spec: WsClientSpec) => string;
197
+ /** This function gives the arguments of `new WebSocket` from a spec. Each timer of ws comes from the declaration. */
198
+ export declare const wsOptions: (spec: WsClientSpec) => WsConnectOptions;
199
+ /** This function gives the bytes of the dial: the upgrade request of RFC 6455 §4.1, with the subprotocols and the headers of the spec. */
200
+ export declare const upgradeRequest: (spec: Pick<WsClientSpec, "host" | "port" | "path" | "protocols" | "headers">) => string;
201
+ /** This judge reads the status line of the answer to the upgrade. Only 101 passes: a WebSocket server takes the upgrade. */
202
+ export declare const upgradeJudge: Judge;
203
+ /** This function makes the dial of a spec: a new TCP connection, the upgrade request, and a wait for 101. The dial then destroys its socket. */
204
+ export declare const wsDial: (spec: Pick<WsClientSpec, "path" | "protocols" | "headers">) => DialFn;
205
+ /**
206
+ * This function makes a WebSocket client, a dependency of a service over ws 8.
207
+ * - It has one connection as one generation. The end of the connection ends the generation. The
208
+ * client then connects again by itself, after a backoff.
209
+ * - Its calls are a request until its reply, and a ping until its pong. Each call has a timer of
210
+ * the wrapper, because ws has none.
211
+ * - Its heartbeat sends a ping frame each interval, one at a time. A ping with no pong in its timeout
212
+ * is a miss. At the last miss, `terminate()` destroys the socket at once, and the client connects again.
213
+ * - It tells the outcome of a call in three values, and it settles each call in flight at the end of its generation (C8, C10).
214
+ * - It records the URL and the ends of the socket of each connection at its open (D1).
215
+ *
216
+ * These parts come from the core of the clients: the outcomes, the second try and the wait for a ready
217
+ * client. The backoff and its schedule, the calls in flight, the bounded close and the checks come from
218
+ * the core too. The heartbeat is the heartbeat of the package. This entry gives what ws does in its own way.
219
+ */
220
+ export declare const wsClient: (name: string, spec: WsClientSpec, options?: WsClientOptions) => WsClient;
221
+ //#endregion
222
+ //#region src/websocket/machine.d.ts
223
+ /**
224
+ * The WebSocket client of the service as a `mark1russell7.machine/1` document. It is one generation
225
+ * at a time: one `WebSocket` of ws 8. The states:
226
+ * - `ready`: the upgrade ended with 101, and the client sends each call. Its heartbeat sends a ping frame each interval.
227
+ * - `failing`: no generation is open. The client connects again after its backoff.
228
+ * - `closing`: the calls in flight, then the close handshake, in `close_bound`. At the bound, `terminate()`.
229
+ *
230
+ * The end of the connection and the last miss of the heartbeat end the generation. A test records
231
+ * the transitions of the client and replays them against this document.
232
+ */
233
+ export declare const WS_CLIENT_MACHINE: Machine;
234
+ //#endregion
235
+ //#region src/websocket/meets.d.ts
236
+ /**
237
+ * This function gives the manifestations that a WebSocket client can meet, and the detectors of
238
+ * each, from its knobs. The WS cells measured them on ws 8:
239
+ * - At a heartbeat of 2 s, a timeout of 1 s and 1 miss, the drop came 0.999 s to 1.0035 s after the
240
+ * ping that got no pong. The slowest of 495 runs took 1.003761 s.
241
+ * - `terminate()` closes the socket 0.3 ms to 1 ms after the drop. The close of the global WebSocket
242
+ * only writes a close frame, and its socket stayed ESTABLISHED.
243
+ * - The kernel of a frozen server acknowledges each ping, thus only the heartbeat finds it.
244
+ * - At `tcp_retries2 = 3`, the kernel gave up before a pong timeout of 10 s.
245
+ * - Without a heartbeat, the client waited for the keepalive of undici: 70 s. ws sets no keepalive.
246
+ */
247
+ export declare const wsMeetings: (name: string, knobs: WsKnobs, misses: number) => Meeting[];
248
+ //#endregion
249
+ //#region src/websocket/starting.d.ts
250
+ /**
251
+ * This poll is the poll of the checks that `WS_CLIENT_STARTING_KNOBS` fits. It is `STARTING_POLL` of
252
+ * the core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.
253
+ */
254
+ export declare const WS_CLIENT_STARTING_POLL: Poll;
255
+ /** This count is the heartbeat misses to start from: 1, as in the WS cells. The drop came 0.999 s to 1.0035 s after the ping with no pong. */
256
+ export declare const WS_CLIENT_STARTING_MISSES = 1;
257
+ /**
258
+ * These knobs are a declaration to start from, from what the WS cells measured on ws 8. The runtime
259
+ * has no defaults: a service gives these knobs, or its own. Each value holds the borders that the cells measured:
260
+ * - `connect_bound` 5 s: the connect timeout of DP44. ws sets no handshake timeout by default.
261
+ * - `request_timeout` 9.5 s: in the slowest poll of 10 s (O13).
262
+ * - `heartbeat_interval` 4 s: in the WST cells, a ping each 4 s kept a flow through a router that
263
+ * forgets it at 5 s. A ping each 6 s did not (O03).
264
+ * - `heartbeat_timeout` 3 s: a stall of 1 s with a pong timeout of 3 s dropped nothing. The detection is 4 s + 3 s = 7 s.
265
+ * - `retry_base` 0.5 s and `retry_cap` 4 s: the reconnect of the cells, from 500 ms, doubling to 4 s.
266
+ * The client adds a jitter up to the base. Thus the most delay is 4.5 s, in the slowest poll of 10 s.
267
+ * - `keepalive_idle` "infinite": ws sets no keepalive, and the heartbeat refreshes an idle flow.
268
+ * - `max_connection_age` "infinite": the client does not replace its connection at an age.
269
+ * - `close_bound` 2 s: a close frame to a silent server gets no answer. The `closeTimeout` of ws is 30 s.
270
+ * - `retrans_giveup_time` 924.6 s: the give-up of Linux at `tcp_retries2 = 15`.
271
+ */
272
+ export declare const WS_CLIENT_STARTING_KNOBS: WsKnobs;
273
+ //#endregion
274
+ export { type Attempt, type CheckOptions, type Client, type ClientJoin, type ClientKnobs, type ClientOptions, type ClientSocket, type ClientSpec, type ClientStep, type Detector, type DialFn, type Factory, type Judge, MANIFESTATIONS, type Manifestation, type Meeting, type ReadyWait, type RetryKnobs, type RetrySchedule, STARTING_POLL, type SendOptions, type Sent, type Situation, type WsClient, type WsClientOptions, type WsClientSpec, type WsConnectOptions, type WsConnection, type WsDriverOptions, type WsFactory, type WsJoin, type WsKnobs, type WsListeners, type WsMessageListener, type WsReplies, type WsReply, type WsRequest, type WsResponse, firstDetector, readyWait, retryBackoff, retryProblems, retrySchedule, statusLineJudge, unwatched };
275
+ //# sourceMappingURL=websocket.d.ts.map