@mark1russell7/service 0.8.4 → 0.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/{backoff-B-jGWVDm.d.ts → backoff-QTRGfkEK.d.ts} +1 -3
- package/build/backoff.d.ts +1 -1
- package/build/backoff.js +1 -2
- package/build/{builder-DQj3NNNc.d.ts → builder-zO48Vgoj.d.ts} +4 -10
- package/build/{call-context-gR8FhbF_.d.ts → call-context-DDhcVvn5.d.ts} +1 -3
- package/build/channel.d.ts +0 -2
- package/build/channel.js +1 -2
- package/build/{core-Dt0HEVMq.d.ts → core-BSzt4RI2.d.ts} +5 -9
- package/build/{dial-CSQOl-yj.d.ts → dial-ChwIcvd4.d.ts} +2 -4
- package/build/grpc.d.ts +4 -14
- package/build/grpc.js +7 -12
- package/build/grpc.js.map +1 -1
- package/build/heartbeat.d.ts +0 -2
- package/build/heartbeat.js +1 -2
- package/build/host.d.ts +3 -23
- package/build/host.js +21 -33
- package/build/host.js.map +1 -1
- package/build/http-client.d.ts +4 -16
- package/build/http-client.js +7 -13
- package/build/http-client.js.map +1 -1
- package/build/http.d.ts +3 -9
- package/build/http.js +6 -10
- package/build/http.js.map +1 -1
- package/build/index.d.ts +10 -22
- package/build/index.js +26 -43
- package/build/index.js.map +1 -1
- package/build/{knobs-D2ClI68I.js → knobs-BJcz6m01.js} +3 -5
- package/build/{knobs-D2ClI68I.js.map → knobs-BJcz6m01.js.map} +1 -1
- package/build/{lifecycle-Br0jAjTk.d.ts → lifecycle-D0J-zwZF.d.ts} +2 -14
- package/build/{limiter-BTgM4aXZ.js → limiter-BwGxEWpP.js} +4 -6
- package/build/{limiter-BTgM4aXZ.js.map → limiter-BwGxEWpP.js.map} +1 -1
- package/build/{limiter-D1aluA0V.d.ts → limiter-Djw39d_S.d.ts} +3 -5
- package/build/limiter.d.ts +3 -3
- package/build/limiter.js +2 -2
- package/build/{logger-BN2BfPgU.d.ts → logger-B6drv9w0.d.ts} +2 -16
- package/build/{machine-p4lENJ86.js → machine-mIW1qgEE.js} +7 -11
- package/build/{machine-p4lENJ86.js.map → machine-mIW1qgEE.js.map} +1 -1
- package/build/mongodb.d.ts +3 -13
- package/build/mongodb.js +6 -11
- package/build/mongodb.js.map +1 -1
- package/build/{operation-DL5RxFds.js → operation-DF73RZOI.js} +2 -3
- package/build/{operation-DL5RxFds.js.map → operation-DF73RZOI.js.map} +1 -1
- package/build/otel.d.ts +2 -4
- package/build/otel.js +1 -2
- package/build/pg.d.ts +2 -12
- package/build/pg.js +6 -11
- package/build/pg.js.map +1 -1
- package/build/{policy-G-Y3Meku.js → policy-B23MY52l.js} +2 -3
- package/build/{policy-G-Y3Meku.js.map → policy-B23MY52l.js.map} +1 -1
- package/build/{policy-CwYR95Sz.d.ts → policy-CBcK2XGg.d.ts} +1 -3
- package/build/{ports-CSr7qWrA.d.ts → ports-DZoipkSD.d.ts} +2 -4
- package/build/{process-DG_im2zc.js → process-Oe0Abbsm.js} +2 -3
- package/build/{process-DG_im2zc.js.map → process-Oe0Abbsm.js.map} +1 -1
- package/build/{queue-fIkOXKVG.d.ts → queue-DXdw1vLO.d.ts} +3 -7
- package/build/rabbitmq.d.ts +4 -14
- package/build/rabbitmq.js +6 -11
- package/build/rabbitmq.js.map +1 -1
- package/build/redis.d.ts +3 -15
- package/build/redis.js +10 -16
- package/build/redis.js.map +1 -1
- package/build/{requests-BIq9Tr4P.js → requests-DD2ALv0_.js} +6 -9
- package/build/{requests-BIq9Tr4P.js.map → requests-DD2ALv0_.js.map} +1 -1
- package/build/{retrier-Nt6r4r6R.js → retrier-BObZq10-.js} +3 -4
- package/build/{retrier-Nt6r4r6R.js.map → retrier-BObZq10-.js.map} +1 -1
- package/build/{rules-BBRopO1e.d.ts → rules-HyFCBStQ.d.ts} +1 -5
- package/build/rules.d.ts +1 -1
- package/build/rules.js +1 -2
- package/build/{store-1CsNoJ8O.d.ts → store-DFwFKrsB.d.ts} +2 -4
- package/build/testing.d.ts +4 -14
- package/build/testing.js +9 -15
- package/build/testing.js.map +1 -1
- package/build/{timing-DGRi3XCI.js → timing-DZl36uXs.js} +2 -3
- package/build/{timing-DGRi3XCI.js.map → timing-DZl36uXs.js.map} +1 -1
- package/build/websocket.d.ts +3 -13
- package/build/websocket.js +7 -12
- package/build/websocket.js.map +1 -1
- package/package.json +4 -3
package/build/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../src/fakes.ts","../src/contract.ts","../src/http/fake-server.ts","../src/conformance.ts","../src/host/fakes.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 { mulberry32 } from \"@mark1russell7/rigor-generators\";\nimport type { Clock } from \"./clock.ts\";\nimport type { ExitSignal, ExitTrigger, ProcessPort, UncaughtOrigin } from \"./process.ts\";\n\n// the fake clock lives beside the clock, in @mark1russell7/algebra/clock\nexport type { FakeClock } from \"@mark1russell7/algebra/clock\";\nexport { fakeClock } from \"@mark1russell7/algebra/clock\";\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 /** This method sends an error that no code caught to each handler of `onUncaught`. The default origin is `uncaughtException`. */\n uncaught(error: unknown, origin?: UncaughtOrigin): 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 uncaughtHandlers = new Set<(error: unknown, origin: UncaughtOrigin) => 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 onUncaught(handler) {\n // each registration is a handler of its own, as with `on`\n const own = (error: unknown, origin: UncaughtOrigin): void => handler(error, origin);\n uncaughtHandlers.add(own);\n return () => {\n uncaughtHandlers.delete(own);\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 uncaught: (error, origin = \"uncaughtException\") => {\n for (const handler of [...uncaughtHandlers]) handler(error, origin);\n },\n get exits() {\n return [...exits];\n },\n get handlers() {\n let count = uncaughtHandlers.size;\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/**\n * This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is\n * `mulberry32` of @mark1russell7/rigor-generators.\n */\nexport const seeded = (seed: number): (() => number) => mulberry32(seed);\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","// A fake server of node:http for the unit tests: no socket and no port. It gives the events and the\n// methods that the transport and the probe server use, as Node gives them. The tests that use real\n// sockets run in CI only (HTTP_IT=1).\n\nimport { EventEmitter } from \"node:events\";\nimport type { Server } from \"node:http\";\n\n/** A fake socket is the stream of one fake connection. Its close comes on the next tick, as in Node. */\nexport class FakeSocket extends EventEmitter {\n destroyed = false;\n readonly written: string[] = [];\n /** This flag tells if the client stopped its reads. Then the bytes of an ended response do not go. */\n paused = false;\n private readonly reads: Array<() => void> = [];\n /** This method stops the reads of the client, as a client that does not read its socket. */\n pause(): this {\n this.paused = true;\n return this;\n }\n /** This method starts the reads of the client again: each ended response finishes. */\n resume(): this {\n this.paused = false;\n for (const read of this.reads.splice(0)) read();\n return this;\n }\n /** This method starts `read` when the client reads the bytes: at once, or at the next `resume()`. */\n whenRead(read: () => void): void {\n if (this.paused) this.reads.push(read);\n else read();\n }\n write(data: string): boolean {\n if (!this.destroyed) this.written.push(data);\n return true;\n }\n end(data?: string): this {\n if (data !== undefined) this.write(data);\n this.destroy();\n return this;\n }\n destroy(): this {\n if (this.destroyed) return this;\n this.destroyed = true;\n process.nextTick(() => this.emit(\"close\", false));\n return this;\n }\n}\n\n/** A fake response answers one fake request. It uses its own `writeHead` for implicit headers, as Node does. */\nexport class FakeResponse extends EventEmitter {\n statusCode = 200;\n headersSent = false;\n writableEnded = false;\n writableFinished = false;\n /** This flag is the flag of Node that `closeIdleConnections` reads: true from the `end()` of the response. */\n finished = false;\n shouldKeepAlive = true;\n readonly headers: Map<string, string> = new Map();\n readonly chunks: string[] = [];\n constructor(readonly socket: FakeSocket) {\n super();\n }\n setHeader(name: string, value: string | number): this {\n this.headers.set(name.toLowerCase(), String(value));\n return this;\n }\n getHeader(name: string): string | undefined {\n return this.headers.get(name.toLowerCase());\n }\n hasHeader(name: string): boolean {\n return this.headers.has(name.toLowerCase());\n }\n removeHeader(name: string): void {\n this.headers.delete(name.toLowerCase());\n }\n /** This method takes the forms of Node: a status, a status message or not, and the headers as an object or a flat list. */\n writeHead(status: number, message?: string | Readonly<Record<string, string>> | readonly string[], given?: Readonly<Record<string, string>> | readonly string[]): this {\n if (this.headersSent) throw new Error(\"the headers went already\");\n this.statusCode = status;\n const headers = typeof message === \"string\" ? given : message;\n if (Array.isArray(headers)) for (let at = 0; at + 1 < headers.length; at += 2) this.setHeader(headers[at]!, headers[at + 1]!);\n else for (const [name, value] of Object.entries(headers ?? {})) this.setHeader(name, value as string);\n // Node closes the connection after the response when it cannot keep it\n if (!this.shouldKeepAlive) this.setHeader(\"connection\", \"close\");\n this.headersSent = true;\n return this;\n }\n write(chunk: string | Uint8Array): boolean {\n if (!this.headersSent) this.writeHead(this.statusCode);\n this.chunks.push(typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString());\n return true;\n }\n /**\n * This method ends the response. Its bytes go when the client reads them, and then `finish` comes.\n * A destroyed socket takes no bytes, thus the client does not get the answer, as in Node.\n */\n end(chunk?: string | Uint8Array): this {\n if (this.writableEnded) return this;\n if (chunk !== undefined) this.write(chunk);\n else if (!this.headersSent) this.writeHead(this.statusCode);\n this.writableEnded = true;\n this.finished = true;\n this.socket.whenRead(() => {\n if (this.socket.destroyed) return;\n this.writableFinished = true;\n this.emit(\"finish\");\n process.nextTick(() => this.emit(\"close\"));\n });\n return this;\n }\n destroy(): this {\n this.socket.destroy();\n return this;\n }\n /** This flag tells if the socket of the response is destroyed. */\n get destroyed(): boolean {\n return this.socket.destroyed;\n }\n /** This flag tells if the connection closes after the response. */\n get last(): boolean {\n return !this.shouldKeepAlive || this.getHeader(\"connection\") === \"close\";\n }\n}\n\n/** A fake answer is what the client of a fake request gets. */\nexport interface FakeAnswer {\n readonly status: number;\n readonly headers: ReadonlyMap<string, string>;\n readonly body: string;\n}\n\n/** A fake connection is one client connection to the fake server. */\nexport class FakeConnection {\n idle = true;\n upgraded = false;\n /** This response is the response of the last request on the connection, for a test that reads a stream as it comes. */\n response: FakeResponse | null = null;\n constructor(\n readonly server: FakeServer,\n readonly socket: FakeSocket,\n ) {}\n /** This method sends a request on the connection, and gives the answer, or an error when the connection closes first. */\n request(url: string, method = \"GET\", headers: Readonly<Record<string, string>> = {}): Promise<FakeAnswer> {\n if (this.socket.destroyed) return Promise.reject(new Error(\"ECONNRESET: the connection is closed\"));\n this.idle = false;\n const req = Object.assign(new EventEmitter(), { url, method, headers });\n const res = new FakeResponse(this.socket);\n this.response = res;\n return new Promise<FakeAnswer>((resolve, reject) => {\n const lost = (): void => reject(new Error(\"ECONNRESET: the connection closed before the answer\"));\n this.socket.once(\"close\", lost);\n res.once(\"finish\", () => {\n this.socket.off(\"close\", lost);\n resolve({ status: res.statusCode, headers: new Map(res.headers), body: res.chunks.join(\"\") });\n if (res.last) this.socket.destroy();\n else this.idle = true;\n });\n // a socket that closes before the bytes of the response went closes the response too\n this.socket.once(\"close\", () => {\n if (!res.writableFinished) res.emit(\"close\");\n });\n this.server.emit(\"request\", req, res);\n });\n }\n /** This method sends an upgrade request on the connection. The server then owns the socket. */\n upgrade(url: string): FakeSocket {\n this.idle = false;\n this.upgraded = true;\n const req = Object.assign(new EventEmitter(), { url, method: \"GET\", headers: { upgrade: \"websocket\" } });\n this.server.emit(\"upgrade\", req, this.socket, Buffer.alloc(0));\n return this.socket;\n }\n}\n\n/** A fake server is a server of `node:http` with no socket. A test connects to it and sends requests. */\nexport class FakeServer extends EventEmitter {\n listening = false;\n keepAliveTimeout = 5000;\n keepAliveTimeoutBuffer = 1000;\n readonly listens: unknown[] = [];\n readonly connections: Set<FakeConnection> = new Set();\n failListen: Error | null = null;\n private closing = false;\n listen(options: unknown): this {\n this.listens.push(options);\n process.nextTick(() => {\n if (this.failListen !== null) {\n this.emit(\"error\", this.failListen);\n return;\n }\n this.listening = true;\n this.closing = false;\n this.emit(\"listening\");\n });\n return this;\n }\n close(done?: (error?: Error) => void): this {\n if (done !== undefined) this.once(\"close\", () => done());\n this.listening = false;\n this.closing = true;\n this.closeIdleConnections();\n this.closeIfDrained();\n return this;\n }\n /**\n * This method destroys each idle connection, as Node does. A connection is idle before its first\n * request, and from the `end()` of its response, also while the bytes of the response still go.\n */\n closeIdleConnections(): void {\n for (const connection of this.connections)\n if (!connection.upgraded && (connection.idle || connection.response?.finished === true)) connection.socket.destroy();\n }\n /** This method destroys each connection of HTTP. As in Node, an upgraded connection is not in the list. */\n closeAllConnections(): void {\n for (const connection of this.connections) if (!connection.upgraded) connection.socket.destroy();\n }\n /** This method opens a connection, or it throws a refusal when the listener is closed. */\n connect(): FakeConnection {\n if (!this.listening) throw Object.assign(new Error(\"ECONNREFUSED: the listener is closed\"), { code: \"ECONNREFUSED\" });\n const socket = new FakeSocket();\n const connection = new FakeConnection(this, socket);\n this.connections.add(connection);\n socket.once(\"close\", () => {\n this.connections.delete(connection);\n this.closeIfDrained();\n });\n this.emit(\"connection\", socket);\n return connection;\n }\n /** This method sends one request on a new connection. */\n async request(url: string, method = \"GET\", headers: Readonly<Record<string, string>> = {}): Promise<FakeAnswer> {\n return this.connect().request(url, method, headers);\n }\n private closeIfDrained(): void {\n if (!this.closing || this.listening || this.connections.size > 0) return;\n this.closing = false;\n process.nextTick(() => this.emit(\"close\"));\n }\n /** This value is the fake server with the type of a server of `node:http`, for the code under test. */\n get asServer(): Server {\n return this as unknown as Server;\n }\n}\n\n/** A pushed source is an async iterable whose items, end and failure a test gives. Its `return()` ends it. */\nexport interface PushedSource<T> {\n readonly iterable: AsyncIterable<T>;\n push(value: T): void;\n finish(): void;\n fail(error: unknown): void;\n /** This flag tells if a reader stopped the source through `return()`. */\n readonly returned: boolean;\n}\n\n/** This function makes a pushed source, a stream of a work for the tests of a stream. */\nexport const pushedSource = <T>(): PushedSource<T> => {\n const queue: Array<IteratorResult<T>> = [];\n let wake: (() => void) | null = null;\n let failure: unknown = null;\n let returned = false;\n const poke = (): void => {\n wake?.();\n wake = null;\n };\n const iterable: AsyncIterable<T> = {\n [Symbol.asyncIterator]: () => ({\n async next(): Promise<IteratorResult<T>> {\n for (;;) {\n if (failure !== null) throw failure;\n if (returned) return { value: undefined, done: true };\n const step = queue.shift();\n if (step !== undefined) return step;\n await new Promise<void>((resolve) => (wake = resolve));\n }\n },\n async return(): Promise<IteratorResult<T>> {\n returned = true;\n poke();\n return { value: undefined, done: true };\n },\n }),\n };\n return {\n iterable,\n push: (value) => {\n queue.push({ value, done: false });\n poke();\n },\n finish: () => {\n queue.push({ value: undefined, done: true });\n poke();\n },\n fail: (error) => {\n failure = error;\n poke();\n },\n get returned() {\n return returned;\n },\n };\n};\n","import type { Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { ownStream } from \"./drains.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport { pushedSource } from \"./http/fake-server.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.ts\";\nimport type { RequestEnd, RequestFn, Tracker } from \"./requests.ts\";\nimport { tracker } from \"./requests.ts\";\n\n/** A held work is one unit of work that stays in flight until the test releases it. */\nexport interface HeldWork {\n /** This method lets the work end. Its promise ends when the caller of the work has its answer, or its error. */\n release(): Promise<void>;\n /** This flag tells if the work got the cooperative abort of the drain. */\n readonly aborted: boolean;\n}\n\n/**\n * A transport subject is a transport and the client side of its work. The kit offers work through\n * it, holds work in flight through it, and reads the count of the transport.\n */\nexport interface TransportSubject {\n readonly impl: TransportImpl;\n /** This lifecycle goes to `start()`. Without it, the kit gives a detached lifecycle. */\n readonly life?: Lifecycle | undefined;\n /** This method offers one unit of new work. It gives true when the transport took it, and false when it refused it. */\n offer(): Promise<boolean>;\n /** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */\n hold(): Promise<HeldWork>;\n /**\n * This method sends one call through the transport, for the stream cases (option `streams`). The\n * handler of the call gives `call.work` to `life.request(call.controller, call.route, ...)` of the\n * lifecycle of the start, and writes its stream to the caller. It gives what the caller sees.\n */\n call?(call: StreamCall): CallerView | Promise<CallerView>;\n /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\n}\n\n/** A stream call is one request of the stream cases. The kit gives its work, and the subject sends it. */\nexport interface StreamCall {\n /** This name is the controller of the request in the lifecycle of the kit. */\n readonly controller: string;\n /** This name is the route of the request in the lifecycle of the kit. */\n readonly route: string;\n /** This function is the work of the request: one value, or a stream of values. */\n readonly work: RequestFn<unknown>;\n /** True tells that the answer is a stream of items. False tells that the answer is unary: one status and one value. */\n readonly stream: boolean;\n}\n\n/** A seen end is the end of a call, as its caller read it. */\nexport interface SeenEnd {\n readonly kind: RequestEnd[\"kind\"];\n /**\n * True tells that the end came in the body of the answer, after its status, for example as the\n * last line of a stream. False tells that the end came as the status of the answer.\n */\n readonly inBand: boolean;\n}\n\n/** A caller view is what the caller of a call has read so far. The kit reads it again until it changes. */\nexport interface CallerView {\n /** These values are the items that the caller read, in their sequence. */\n readonly items: readonly unknown[];\n /** This end is the end that the caller read, or null while the call is open. */\n readonly end: SeenEnd | null;\n}\n\n/**\n * This function gives a detached lifecycle: a lifecycle with no service, for the start of a\n * transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request\n * and each use of its health throws, because no service declares a route.\n */\nexport const detachedLifecycle = (): Lifecycle => {\n const none = (): never => {\n throw new Error(\"a detached lifecycle has no service: give the transport the lifecycle of a service\");\n };\n const health = { verdict: none, probe: none, metrics: none, subscribe: none, forceFail: none, drain: none, stop: none } as Health;\n return {\n health,\n state: \"running\",\n exitCode: null,\n errors: [],\n started: Promise.resolve(),\n done: new Promise<number>(() => {}),\n signal: new AbortController().signal,\n shutdown: none,\n request: none,\n inFlight: () => 0,\n keepAlive: () => true,\n };\n};\n\n/** These names are the controller and the route of each call of the stream cases. */\nconst CALLS = { controller: \"conformance\", route: \"call\" } as const;\n\n/**\n * This function gives a lifecycle with request tracking for the stream cases, and its tracker. The\n * kit uses the tracker for the stages of the shutdown, as the lifecycle of a service does. Its\n * requests are not idempotent, and it admits each request until the stop of its intake.\n */\nconst trackedLifecycle = (clock: Clock): { readonly life: Lifecycle; readonly requests: Tracker } => {\n const requests = tracker([{ name: CALLS.controller, requires: [], routes: { [CALLS.route]: { idempotent: false } } }], clock, () => null);\n const life: Lifecycle = {\n ...detachedLifecycle(),\n // the lifecycle owns each stream that it makes, thus the drain of the transport waits for the end of its cut\n request: (controller, route, work, options) => ownStream(requests.request(controller, route, work, options), life),\n inFlight: (controller) => requests.inFlight(controller),\n };\n return { life, requests };\n};\n\n/** A subject factory makes a new subject for each case, on the clock of the case. */\nexport type SubjectFactory = (clock: Clock) => TransportSubject | Promise<TransportSubject>;\n\n/** A conformance record is one measurement of a case, for the raw records of a run in CI. */\nexport interface ConformanceRecord {\n readonly case: string;\n readonly what: string;\n /** This time is the limit of the contract, in milliseconds. */\n readonly expected: number;\n /** This time is what the case measured, in milliseconds of the real clock. */\n readonly measured: number;\n}\n\n/** These options tune the conformance kit. */\nexport interface ConformanceOptions {\n /** This name goes before the name of each case. */\n readonly name?: string | undefined;\n /** This clock moves the cases: `fake` gives exact and fast cases, and `real` measures the timing. The default is `fake`. */\n readonly clock?: \"fake\" | \"real\" | undefined;\n /** This time is the cap of each drain of the cases, in milliseconds. The default is 1000. */\n readonly cap?: number | undefined;\n /** This time is the most that a close can take, in milliseconds of the real clock. The default is 1000. */\n readonly closeBound?: number | undefined;\n /** This time is the most that an event can take to reach the transport, in real milliseconds. The default is 100. */\n readonly slack?: number | undefined;\n /** False tells that the work of the transport cannot see the cooperative abort. The default is true. */\n readonly cooperative?: boolean | undefined;\n /** This count is the number of works that the count case holds. The default is 3. */\n readonly holds?: number | undefined;\n /**\n * True adds the stream cases (S6 D4). Then the subject gives `call`, and the kit gives the\n * transport a lifecycle with request tracking. The default is false.\n */\n readonly streams?: boolean | undefined;\n /** This function receives each measurement, for the raw records of a run. */\n readonly record?: ((record: ConformanceRecord) => void) | undefined;\n}\n\ninterface Time {\n readonly clock: Clock;\n pass(ms: number): Promise<void>;\n}\n\ninterface Tracked {\n readonly settled: boolean;\n readonly error: unknown;\n readonly failed: boolean;\n}\n\nconst realNow = (): number => performance.now();\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 *\n * The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a\n * unary call is a stream of one item. The kit gives the transport a lifecycle with request\n * tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.\n * - A unary call gives one value, and its end comes as the status of the answer.\n * - A stream stays in flight until its end, not until its first item.\n * - A failure after the first item ends the stream with an error line in the body, not a status.\n * A failure before the first item gets a status.\n * - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.\n * - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.\n */\nexport const transportConformance = (make: SubjectFactory, options: ConformanceOptions = {}): ContractCase[] => {\n const name = options.name ?? \"transport\";\n const fake = (options.clock ?? \"fake\") === \"fake\";\n const cap = options.cap ?? 1000;\n const closeBound = options.closeBound ?? 1000;\n const slack = options.slack ?? 100;\n const cooperative = options.cooperative ?? true;\n const holds = options.holds ?? 3;\n\n const timeOf = (): Time => {\n if (!fake) return { clock: realClock, pass: 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 if (!(options.streams ?? false)) return cases;\n\n /** A fed stream is a stream call whose items, end and failure the case gives. */\n interface Fed {\n readonly view: CallerView;\n push(value: unknown): void;\n finish(): void;\n fail(error: Error): void;\n /** This flag tells if the work got the abort of its signal. */\n readonly aborted: boolean;\n }\n\n const eachStream = (\n title: string,\n body: (subject: TransportSubject, time: Time, requests: Tracker) => Promise<void>,\n ): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n const { life, requests } = trackedLifecycle(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, life);\n check(subject.call !== undefined, \"the option streams needs a subject that gives call()\");\n await body(subject, time, requests);\n } finally {\n // each work of the case ends, thus no stream stays open after the case\n requests.stopIntake();\n requests.cooperativeAbort();\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const call = (subject: TransportSubject, given: StreamCall): Promise<CallerView> => Promise.resolve(subject.call!(given));\n\n const openStream = async (subject: TransportSubject): Promise<Fed> => {\n const source = pushedSource<unknown>();\n let started = false;\n let signal: AbortSignal | null = null;\n const view = await call(subject, {\n ...CALLS,\n stream: true,\n work: (given) => {\n started = true;\n signal = given;\n return source.iterable;\n },\n });\n check(await within(slack, () => started), \"the work of a stream call did not start\");\n return {\n view,\n push: (value) => source.push(value),\n finish: () => source.finish(),\n fail: (error) => source.fail(error),\n get aborted() {\n return (signal as AbortSignal | null)?.aborted === true;\n },\n };\n };\n\n const pushes = async (fed: Fed, value: number, what: string): Promise<void> => {\n const before = fed.view.items.length;\n fed.push(value);\n check(await within(slack, () => fed.view.items.length > before), `${what}: the caller did not get the item ${value}`);\n };\n\n const ends = async (view: CallerView, kind: RequestEnd[\"kind\"], inBand: boolean, what: string): Promise<void> => {\n check(await within(slack, () => view.end !== null), `${what}: the caller got no end`);\n const end = view.end!;\n const where = (body: boolean): string => (body ? \"in the body\" : \"as a status\");\n check(\n end.kind === kind && end.inBand === inBand,\n `${what}: the caller got the end ${end.kind} ${where(end.inBand)}, not ${kind} ${where(inBand)}`,\n );\n };\n\n /** This function stops the intake of the tracker and of the transport, as the stage `stop intake` does. */\n const stopBoth = async (subject: TransportSubject, requests: Tracker): Promise<void> => {\n requests.stopIntake();\n await subject.impl.stopIntake();\n };\n\n /**\n * This function starts the drain of the transport and of the tracker, as the stage `drain` does.\n * The abort of `signal` is also the cooperative abort of the tracker. It tracks the drain of the transport.\n */\n const drainBoth = (subject: TransportSubject, requests: Tracker, deadline: number, signal: AbortSignal): Tracked => {\n if (signal.aborted) requests.cooperativeAbort();\n else signal.addEventListener(\"abort\", () => requests.cooperativeAbort(), { once: true });\n void requests.drain(deadline);\n return track(attempt(() => subject.impl.drain(deadline, signal)));\n };\n\n const failure = (): Error => new Error(\"the failure of the conformance kit\");\n\n const streamCases: ContractCase[] = [\n eachStream(\"a unary call is a stream of one item: one value, and its end as the status\", async (subject) => {\n let started = false;\n let give: (value: unknown) => void = () => {};\n const view = await call(subject, {\n ...CALLS,\n stream: false,\n work: () => {\n started = true;\n return new Promise<unknown>((resolve) => {\n give = resolve;\n });\n },\n });\n check(await within(slack, () => started), \"the work of a unary call did not start\");\n await count(subject, 1, \"a unary call is in flight\");\n give(7);\n await ends(view, \"done\", false, \"a unary call\");\n check(view.items.length === 1 && view.items[0] === 7, `a unary call gave the items ${JSON.stringify(view.items)}, not [7]`);\n await count(subject, 0, \"a unary call ended\");\n }),\n\n eachStream(\"a stream stays in flight until its end, not until its first item\", async (subject) => {\n const fed = await openStream(subject);\n await count(subject, 1, \"a stream is open\");\n for (const value of [1, 2]) {\n await pushes(fed, value, \"an open stream\");\n await count(subject, 1, `a stream is open after its item ${value}`);\n }\n check(fed.view.end === null, \"the caller got an end before the end of the stream\");\n fed.finish();\n await ends(fed.view, \"done\", true, \"a stream that ended\");\n check(JSON.stringify(fed.view.items) === \"[1,2]\", `a stream gave the items ${JSON.stringify(fed.view.items)}, not [1,2]`);\n await count(subject, 0, \"a stream ended\");\n }),\n\n eachStream(\"a failure after the first item ends the stream with an error line, not a status\", async (subject) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before its failure\");\n fed.fail(failure());\n await ends(fed.view, \"failed\", true, \"a stream that failed after its first item\");\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"a failure before the first item gets a status, not an error line\", async (subject) => {\n const fed = await openStream(subject);\n fed.fail(failure());\n await ends(fed.view, \"failed\", false, \"a stream that failed before its first item\");\n check(fed.view.items.length === 0, `a stream that failed before its first item gave ${fed.view.items.length} items`);\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"drain waits for an open stream, and the cooperative abort ends the stream with its end\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const abort = new AbortController();\n const deadline = time.clock.now() + cap;\n const drained = drainBoth(subject, requests, deadline, abort.signal);\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while a stream was open, before its deadline\");\n check(fed.view.end === null, \"the caller got an end before the cooperative abort\");\n await count(subject, 1, \"a stream is open in the drain\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => fed.aborted), \"the work of the stream did not get the cooperative abort\");\n await ends(fed.view, \"cut\", true, \"a stream after the cooperative abort\");\n check(await within(slack, () => drained.settled), \"drain did not end when the stream ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the stream ended\");\n await count(subject, 0, \"the cooperative abort left a stream in flight\");\n }),\n\n eachStream(\"drain cuts an open stream at its deadline, and the caller gets the end of the cut\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const drained = drainBoth(subject, requests, time.clock.now() + cap, new AbortController().signal);\n await time.pass(cap);\n await ends(fed.view, \"cut\", true, \"a stream at the deadline of the drain\");\n check(await within(slack, () => drained.settled), \"drain did not end after the cut of the stream\");\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n await count(subject, 0, \"the cut left a stream in flight\");\n }),\n ];\n return [...cases, ...streamCases];\n};\n","import type { FakeClock } from \"../fakes.ts\";\nimport { fakeClock } from \"../fakes.ts\";\nimport type { Logger } from \"../logger.ts\";\nimport type { ChildHandle, CommandOptions, CommandResult, HostPorts, ProcessMark, SpawnRequest, StopSignal } from \"./ports.ts\";\n\n/** A fake child is a child process of a fake host. A test ends it, or a stop ends it. */\nexport interface FakeChild extends ChildHandle {\n readonly request: SpawnRequest;\n /** These are the messages that went on its IPC channel. */\n readonly sent: readonly unknown[];\n /** This flag tells if the child ended. */\n readonly ended: boolean;\n /** This method ends the child with a code, or with a signal and a null code. A second use does nothing. */\n exit(code: number | null, signal?: string | null): void;\n /** This method sends data on the output of the child. */\n output(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array): void;\n}\n\n/** A recorded command is one command that went through the fake command port. */\nexport interface RecordedCommand {\n readonly file: string;\n readonly args: readonly string[];\n readonly options: CommandOptions | undefined;\n}\n\n/** A recorded signal is one signal that went through the fake process port. */\nexport interface RecordedSignal {\n readonly pid: number;\n readonly signal: StopSignal;\n readonly group: boolean;\n}\n\n/** These options go with a fake host. */\nexport interface FakeHostOptions {\n /** This text is the platform. The default is `linux`. */\n readonly platform?: string | undefined;\n readonly env?: Readonly<Record<string, string | undefined>> | undefined;\n /** The default is `/home/test`. */\n readonly homeDir?: string | undefined;\n /** The default is `test`. */\n readonly user?: string | undefined;\n /** This record names the host process. The default is the ID 100, which started at the wall time 0. */\n readonly self?: ProcessMark | undefined;\n /** This time is the wall time at the clock time 0, in milliseconds after the epoch. The default is 1 000 000 000 000. */\n readonly wallStart?: number | undefined;\n /** These files are in the fake file system at the start. */\n readonly files?: Readonly<Record<string, string | Uint8Array>> | undefined;\n /**\n * This function gives the result of a command. When it gives undefined, the fake answers. `taskkill`\n * with `/F` ends the process and gives 0. `taskkill` without `/F` gives 1, or ends a polite child. Each other command gives 0.\n */\n readonly answer?: ((command: RecordedCommand) => CommandResult | undefined) | undefined;\n readonly logger?: Logger | undefined;\n}\n\n/**\n * A fake host is the host ports of a test, and the state behind them. It starts no process, writes no\n * file and installs no task. Each effect is a record or a change of its state.\n */\nexport interface FakeHost {\n readonly ports: HostPorts;\n readonly clock: FakeClock;\n /** These are the files of the fake file system. */\n readonly files: Map<string, string | Uint8Array>;\n readonly commands: RecordedCommand[];\n readonly signals: RecordedSignal[];\n readonly children: FakeChild[];\n /** This table holds each live process: its ID, and its start time or null. */\n readonly processes: Map<number, number | null>;\n /** This map gives the HTTP status of each address. An address that it does not have gives no answer. */\n readonly http: Map<string, number | null>;\n /** This set holds each `host:port` that takes a TCP connection. */\n readonly tcp: Set<string>;\n /** True makes each child end with the code 0 at a staged stop: SIGTERM, SIGINT, an IPC message or `taskkill` without `/F`. */\n polite: boolean;\n /** This function makes a file operation fail. It gets the name of the operation and the path. */\n failFiles: ((operation: string, path: string) => boolean) | null;\n /** This function makes a spawn fail, thus the child has no ID and ends. */\n failSpawn: ((request: SpawnRequest) => boolean) | null;\n /** This method gives the text of a file, or null. */\n text(path: string): string | null;\n /** This method lets the promises that are ready continue, without a move of the clock. */\n settle(): Promise<void>;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst bytesOf = (data: string | Uint8Array): Uint8Array => (typeof data === \"string\" ? encoder.encode(data) : data);\n\n/** This function makes a fake host. Give its `ports` to the host functions in a test. */\nexport const fakeHost = (options: FakeHostOptions = {}): FakeHost => {\n const clock = fakeClock();\n const wallStart = options.wallStart ?? 1_000_000_000_000;\n const wall = (): number => wallStart + clock.now();\n const self = options.self ?? { pid: 100, startedAt: wallStart };\n const files = new Map<string, string | Uint8Array>(Object.entries(options.files ?? {}));\n const commands: RecordedCommand[] = [];\n const signals: RecordedSignal[] = [];\n const children: FakeChild[] = [];\n const processes = new Map<number, number | null>([[self.pid, self.startedAt]]);\n const live = new Map<number, FakeChild>();\n let nextPid = 1000;\n\n const check = (operation: string, path: string): void => {\n if (host.failFiles?.(operation, path) === true) throw new Error(`the fake ${operation} of ${path} failed`);\n };\n\n const politeStop = (pid: number): void => {\n const child = live.get(pid);\n if (host.polite && child !== undefined) queueMicrotask(() => child.exit(0));\n };\n const hardStop = (pid: number, signal: string | null): void => {\n const child = live.get(pid);\n if (child !== undefined) queueMicrotask(() => child.exit(null, signal));\n else processes.delete(pid);\n };\n\n const spawn = (request: SpawnRequest): FakeChild => {\n const failed = host.failSpawn?.(request) === true;\n const pid = failed ? null : nextPid++;\n const outputs: Array<(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void> = [];\n const exits: Array<(code: number | null, signal: string | null) => void> = [];\n const sent: unknown[] = [];\n let end: { code: number | null; signal: string | null } | null = null;\n const child: FakeChild = {\n request,\n pid,\n ipc: request.ipc,\n sent,\n get ended() {\n return end !== null;\n },\n onOutput(handler) {\n outputs.push(handler);\n },\n onExit(handler) {\n exits.push(handler);\n if (end !== null) handler(end.code, end.signal);\n },\n send(message) {\n if (!request.ipc || end !== null) return false;\n sent.push(message);\n if (pid !== null) politeStop(pid);\n return true;\n },\n exit(code, signal = null) {\n if (end !== null) return;\n end = { code, signal };\n if (pid !== null) {\n processes.delete(pid);\n live.delete(pid);\n }\n for (const handler of exits) handler(code, signal);\n },\n output(stream, chunk) {\n for (const handler of outputs) handler(stream, chunk);\n },\n };\n children.push(child);\n if (pid === null) queueMicrotask(() => child.exit(null));\n else {\n processes.set(pid, wall());\n live.set(pid, child);\n }\n return child;\n };\n\n const signal = (pid: number, sig: StopSignal, group: boolean): boolean => {\n if (!processes.has(pid)) return false;\n signals.push({ pid, signal: sig, group });\n if (sig === \"SIGKILL\") hardStop(pid, \"SIGKILL\");\n else politeStop(pid);\n return true;\n };\n\n const defaultAnswer = (command: RecordedCommand): CommandResult => {\n if (command.file !== \"taskkill\") return { code: 0, out: \"\" };\n const at = command.args.indexOf(\"/PID\");\n const pid = Number(command.args[at + 1]);\n if (at < 0 || !processes.has(pid)) return { code: 128, out: `ERROR: The process \"${command.args[at + 1] ?? \"\"}\" not found.` };\n if (command.args.includes(\"/F\")) {\n hardStop(pid, null);\n return { code: 0, out: `SUCCESS: The process with PID ${pid} has been terminated.` };\n }\n if (host.polite && live.has(pid)) {\n politeStop(pid);\n return { code: 0, out: `SUCCESS: Sent termination signal to the process with PID ${pid}.` };\n }\n return { code: 1, out: `ERROR: The process with PID ${pid} could not be terminated.` };\n };\n\n const ports: HostPorts = {\n platform: options.platform ?? \"linux\",\n commands: {\n async run(file, args, commandOptions) {\n const command: RecordedCommand = { file, args: [...args], options: commandOptions };\n commands.push(command);\n return options.answer?.(command) ?? defaultAnswer(command);\n },\n },\n files: {\n async read(path) {\n check(\"read\", path);\n const data = files.get(path);\n return data === undefined ? null : typeof data === \"string\" ? data : decoder.decode(data);\n },\n async write(path, data) {\n check(\"write\", path);\n files.set(path, data);\n },\n async create(path, data) {\n check(\"create\", path);\n if (files.has(path)) return false;\n files.set(path, data);\n return true;\n },\n async append(path, data) {\n check(\"append\", path);\n const before = files.get(path);\n if (before === undefined) files.set(path, data);\n else if (typeof before === \"string\" && typeof data === \"string\") files.set(path, before + data);\n else {\n const head = bytesOf(before);\n const tail = bytesOf(data);\n const joined = new Uint8Array(head.length + tail.length);\n joined.set(head, 0);\n joined.set(tail, head.length);\n files.set(path, joined);\n }\n },\n async size(path) {\n check(\"size\", path);\n const data = files.get(path);\n return data === undefined ? null : bytesOf(data).length;\n },\n async rename(from, to) {\n check(\"rename\", from);\n const data = files.get(from);\n if (data === undefined) throw new Error(`the fake file ${from} does not exist`);\n files.delete(from);\n files.set(to, data);\n },\n async remove(path) {\n check(\"remove\", path);\n files.delete(path);\n },\n },\n processes: {\n alive: (pid) => processes.has(pid),\n startOf: async (pid) => processes.get(pid) ?? null,\n signal: (pid, sig) => signal(pid, sig, false),\n signalGroup: (pid, sig) => ports.platform !== \"win32\" && live.has(pid) && signal(pid, sig, true),\n spawn,\n },\n net: {\n httpStatus: async (url) => host.http.get(url) ?? null,\n tcpConnect: async (hostName, port) => host.tcp.has(`${hostName}:${port}`),\n },\n clock,\n wall,\n self,\n env: options.env ?? {},\n homeDir: options.homeDir ?? \"/home/test\",\n user: () => options.user ?? \"test\",\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n\n const host: FakeHost = {\n ports,\n clock,\n files,\n commands,\n signals,\n children,\n processes,\n http: new Map(),\n tcp: new Set(),\n polite: false,\n failFiles: null,\n failSpawn: null,\n text(path) {\n const data = files.get(path);\n return data === undefined ? null : typeof data === \"string\" ? data : decoder.decode(data);\n },\n async settle() {\n for (let turn = 0; turn < 2000; turn += 1) await Promise.resolve();\n },\n };\n return host;\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. A test logger keeps each log entry. `contractCases` generates the contract test of a\n// declaration, and `transportConformance` generates the conformance test of a transport. A fake host\n// gives the ports of the host entry, thus a test installs no task and starts no process.\n\nimport type { AddressInfo, Server, Socket } from \"node:net\";\nimport { createServer } from \"node:net\";\nimport type { Outcome } from \"./latch.ts\";\nimport type { LogEntry, LogLevel, Logger } from \"./logger.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 CallerView,\n ConformanceOptions,\n ConformanceRecord,\n HeldWork,\n SeenEnd,\n StreamCall,\n SubjectFactory,\n TransportSubject,\n} from \"./conformance.ts\";\nexport { detachedLifecycle, transportConformance } from \"./conformance.ts\";\nexport type { FakeChild, FakeHost, FakeHostOptions, RecordedCommand, RecordedSignal } from \"./host/fakes.ts\";\nexport { fakeHost } from \"./host/fakes.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 test logger is a logger that keeps each entry, thus a test can examine the log of the runtime. */\nexport interface TestLogger extends Logger {\n /** These are the entries, in the sequence of their calls. */\n readonly entries: readonly LogEntry[];\n /** This method gives the message of each entry, or of each entry at one level. */\n messages(level?: LogLevel): string[];\n /** This method removes each entry. */\n clear(): void;\n}\n\n/** This function makes a test logger with no entries. */\nexport const testLogger = (): TestLogger => {\n const entries: LogEntry[] = [];\n return {\n entries,\n log(level, message, fields) {\n entries.push({ level, message, fields });\n },\n messages: (level) => entries.filter((entry) => level === undefined || entry.level === level).map((entry) => entry.message),\n clear() {\n entries.length = 0;\n },\n };\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(() => resol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AkC;CAC3D,IAAI,SAAS;CACb,MAAM,0BAAU,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/http/fake-server.ts","../src/conformance.ts","../src/host/fakes.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 { mulberry32 } from \"@mark1russell7/rigor-generators\";\nimport type { Clock } from \"./clock.ts\";\nimport type { ExitSignal, ExitTrigger, ProcessPort, UncaughtOrigin } from \"./process.ts\";\n\n// the fake clock lives beside the clock, in @mark1russell7/algebra/clock\nexport type { FakeClock } from \"@mark1russell7/algebra/clock\";\nexport { fakeClock } from \"@mark1russell7/algebra/clock\";\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 /** This method sends an error that no code caught to each handler of `onUncaught`. The default origin is `uncaughtException`. */\n uncaught(error: unknown, origin?: UncaughtOrigin): 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 uncaughtHandlers = new Set<(error: unknown, origin: UncaughtOrigin) => 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 onUncaught(handler) {\n // each registration is a handler of its own, as with `on`\n const own = (error: unknown, origin: UncaughtOrigin): void => handler(error, origin);\n uncaughtHandlers.add(own);\n return () => {\n uncaughtHandlers.delete(own);\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 uncaught: (error, origin = \"uncaughtException\") => {\n for (const handler of [...uncaughtHandlers]) handler(error, origin);\n },\n get exits() {\n return [...exits];\n },\n get handlers() {\n let count = uncaughtHandlers.size;\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/**\n * This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is\n * `mulberry32` of @mark1russell7/rigor-generators.\n */\nexport const seeded = (seed: number): (() => number) => mulberry32(seed);\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","// A fake server of node:http for the unit tests: no socket and no port. It gives the events and the\n// methods that the transport and the probe server use, as Node gives them. The tests that use real\n// sockets run in CI only (HTTP_IT=1).\n\nimport { EventEmitter } from \"node:events\";\nimport type { Server } from \"node:http\";\n\n/** A fake socket is the stream of one fake connection. Its close comes on the next tick, as in Node. */\nexport class FakeSocket extends EventEmitter {\n destroyed = false;\n readonly written: string[] = [];\n /** This flag tells if the client stopped its reads. Then the bytes of an ended response do not go. */\n paused = false;\n private readonly reads: Array<() => void> = [];\n /** This method stops the reads of the client, as a client that does not read its socket. */\n pause(): this {\n this.paused = true;\n return this;\n }\n /** This method starts the reads of the client again: each ended response finishes. */\n resume(): this {\n this.paused = false;\n for (const read of this.reads.splice(0)) read();\n return this;\n }\n /** This method starts `read` when the client reads the bytes: at once, or at the next `resume()`. */\n whenRead(read: () => void): void {\n if (this.paused) this.reads.push(read);\n else read();\n }\n write(data: string): boolean {\n if (!this.destroyed) this.written.push(data);\n return true;\n }\n end(data?: string): this {\n if (data !== undefined) this.write(data);\n this.destroy();\n return this;\n }\n destroy(): this {\n if (this.destroyed) return this;\n this.destroyed = true;\n process.nextTick(() => this.emit(\"close\", false));\n return this;\n }\n}\n\n/** A fake response answers one fake request. It uses its own `writeHead` for implicit headers, as Node does. */\nexport class FakeResponse extends EventEmitter {\n statusCode = 200;\n headersSent = false;\n writableEnded = false;\n writableFinished = false;\n /** This flag is the flag of Node that `closeIdleConnections` reads: true from the `end()` of the response. */\n finished = false;\n shouldKeepAlive = true;\n readonly headers: Map<string, string> = new Map();\n readonly chunks: string[] = [];\n constructor(readonly socket: FakeSocket) {\n super();\n }\n setHeader(name: string, value: string | number): this {\n this.headers.set(name.toLowerCase(), String(value));\n return this;\n }\n getHeader(name: string): string | undefined {\n return this.headers.get(name.toLowerCase());\n }\n hasHeader(name: string): boolean {\n return this.headers.has(name.toLowerCase());\n }\n removeHeader(name: string): void {\n this.headers.delete(name.toLowerCase());\n }\n /** This method takes the forms of Node: a status, a status message or not, and the headers as an object or a flat list. */\n writeHead(status: number, message?: string | Readonly<Record<string, string>> | readonly string[], given?: Readonly<Record<string, string>> | readonly string[]): this {\n if (this.headersSent) throw new Error(\"the headers went already\");\n this.statusCode = status;\n const headers = typeof message === \"string\" ? given : message;\n if (Array.isArray(headers)) for (let at = 0; at + 1 < headers.length; at += 2) this.setHeader(headers[at]!, headers[at + 1]!);\n else for (const [name, value] of Object.entries(headers ?? {})) this.setHeader(name, value as string);\n // Node closes the connection after the response when it cannot keep it\n if (!this.shouldKeepAlive) this.setHeader(\"connection\", \"close\");\n this.headersSent = true;\n return this;\n }\n write(chunk: string | Uint8Array): boolean {\n if (!this.headersSent) this.writeHead(this.statusCode);\n this.chunks.push(typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString());\n return true;\n }\n /**\n * This method ends the response. Its bytes go when the client reads them, and then `finish` comes.\n * A destroyed socket takes no bytes, thus the client does not get the answer, as in Node.\n */\n end(chunk?: string | Uint8Array): this {\n if (this.writableEnded) return this;\n if (chunk !== undefined) this.write(chunk);\n else if (!this.headersSent) this.writeHead(this.statusCode);\n this.writableEnded = true;\n this.finished = true;\n this.socket.whenRead(() => {\n if (this.socket.destroyed) return;\n this.writableFinished = true;\n this.emit(\"finish\");\n process.nextTick(() => this.emit(\"close\"));\n });\n return this;\n }\n destroy(): this {\n this.socket.destroy();\n return this;\n }\n /** This flag tells if the socket of the response is destroyed. */\n get destroyed(): boolean {\n return this.socket.destroyed;\n }\n /** This flag tells if the connection closes after the response. */\n get last(): boolean {\n return !this.shouldKeepAlive || this.getHeader(\"connection\") === \"close\";\n }\n}\n\n/** A fake answer is what the client of a fake request gets. */\nexport interface FakeAnswer {\n readonly status: number;\n readonly headers: ReadonlyMap<string, string>;\n readonly body: string;\n}\n\n/** A fake connection is one client connection to the fake server. */\nexport class FakeConnection {\n idle = true;\n upgraded = false;\n /** This response is the response of the last request on the connection, for a test that reads a stream as it comes. */\n response: FakeResponse | null = null;\n constructor(\n readonly server: FakeServer,\n readonly socket: FakeSocket,\n ) {}\n /** This method sends a request on the connection, and gives the answer, or an error when the connection closes first. */\n request(url: string, method = \"GET\", headers: Readonly<Record<string, string>> = {}): Promise<FakeAnswer> {\n if (this.socket.destroyed) return Promise.reject(new Error(\"ECONNRESET: the connection is closed\"));\n this.idle = false;\n const req = Object.assign(new EventEmitter(), { url, method, headers });\n const res = new FakeResponse(this.socket);\n this.response = res;\n return new Promise<FakeAnswer>((resolve, reject) => {\n const lost = (): void => reject(new Error(\"ECONNRESET: the connection closed before the answer\"));\n this.socket.once(\"close\", lost);\n res.once(\"finish\", () => {\n this.socket.off(\"close\", lost);\n resolve({ status: res.statusCode, headers: new Map(res.headers), body: res.chunks.join(\"\") });\n if (res.last) this.socket.destroy();\n else this.idle = true;\n });\n // a socket that closes before the bytes of the response went closes the response too\n this.socket.once(\"close\", () => {\n if (!res.writableFinished) res.emit(\"close\");\n });\n this.server.emit(\"request\", req, res);\n });\n }\n /** This method sends an upgrade request on the connection. The server then owns the socket. */\n upgrade(url: string): FakeSocket {\n this.idle = false;\n this.upgraded = true;\n const req = Object.assign(new EventEmitter(), { url, method: \"GET\", headers: { upgrade: \"websocket\" } });\n this.server.emit(\"upgrade\", req, this.socket, Buffer.alloc(0));\n return this.socket;\n }\n}\n\n/** A fake server is a server of `node:http` with no socket. A test connects to it and sends requests. */\nexport class FakeServer extends EventEmitter {\n listening = false;\n keepAliveTimeout = 5000;\n keepAliveTimeoutBuffer = 1000;\n readonly listens: unknown[] = [];\n readonly connections: Set<FakeConnection> = new Set();\n failListen: Error | null = null;\n private closing = false;\n listen(options: unknown): this {\n this.listens.push(options);\n process.nextTick(() => {\n if (this.failListen !== null) {\n this.emit(\"error\", this.failListen);\n return;\n }\n this.listening = true;\n this.closing = false;\n this.emit(\"listening\");\n });\n return this;\n }\n close(done?: (error?: Error) => void): this {\n if (done !== undefined) this.once(\"close\", () => done());\n this.listening = false;\n this.closing = true;\n this.closeIdleConnections();\n this.closeIfDrained();\n return this;\n }\n /**\n * This method destroys each idle connection, as Node does. A connection is idle before its first\n * request, and from the `end()` of its response, also while the bytes of the response still go.\n */\n closeIdleConnections(): void {\n for (const connection of this.connections)\n if (!connection.upgraded && (connection.idle || connection.response?.finished === true)) connection.socket.destroy();\n }\n /** This method destroys each connection of HTTP. As in Node, an upgraded connection is not in the list. */\n closeAllConnections(): void {\n for (const connection of this.connections) if (!connection.upgraded) connection.socket.destroy();\n }\n /** This method opens a connection, or it throws a refusal when the listener is closed. */\n connect(): FakeConnection {\n if (!this.listening) throw Object.assign(new Error(\"ECONNREFUSED: the listener is closed\"), { code: \"ECONNREFUSED\" });\n const socket = new FakeSocket();\n const connection = new FakeConnection(this, socket);\n this.connections.add(connection);\n socket.once(\"close\", () => {\n this.connections.delete(connection);\n this.closeIfDrained();\n });\n this.emit(\"connection\", socket);\n return connection;\n }\n /** This method sends one request on a new connection. */\n async request(url: string, method = \"GET\", headers: Readonly<Record<string, string>> = {}): Promise<FakeAnswer> {\n return this.connect().request(url, method, headers);\n }\n private closeIfDrained(): void {\n if (!this.closing || this.listening || this.connections.size > 0) return;\n this.closing = false;\n process.nextTick(() => this.emit(\"close\"));\n }\n /** This value is the fake server with the type of a server of `node:http`, for the code under test. */\n get asServer(): Server {\n return this as unknown as Server;\n }\n}\n\n/** A pushed source is an async iterable whose items, end and failure a test gives. Its `return()` ends it. */\nexport interface PushedSource<T> {\n readonly iterable: AsyncIterable<T>;\n push(value: T): void;\n finish(): void;\n fail(error: unknown): void;\n /** This flag tells if a reader stopped the source through `return()`. */\n readonly returned: boolean;\n}\n\n/** This function makes a pushed source, a stream of a work for the tests of a stream. */\nexport const pushedSource = <T>(): PushedSource<T> => {\n const queue: Array<IteratorResult<T>> = [];\n let wake: (() => void) | null = null;\n let failure: unknown = null;\n let returned = false;\n const poke = (): void => {\n wake?.();\n wake = null;\n };\n const iterable: AsyncIterable<T> = {\n [Symbol.asyncIterator]: () => ({\n async next(): Promise<IteratorResult<T>> {\n for (;;) {\n if (failure !== null) throw failure;\n if (returned) return { value: undefined, done: true };\n const step = queue.shift();\n if (step !== undefined) return step;\n await new Promise<void>((resolve) => (wake = resolve));\n }\n },\n async return(): Promise<IteratorResult<T>> {\n returned = true;\n poke();\n return { value: undefined, done: true };\n },\n }),\n };\n return {\n iterable,\n push: (value) => {\n queue.push({ value, done: false });\n poke();\n },\n finish: () => {\n queue.push({ value: undefined, done: true });\n poke();\n },\n fail: (error) => {\n failure = error;\n poke();\n },\n get returned() {\n return returned;\n },\n };\n};\n","import type { Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { ownStream } from \"./drains.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport { pushedSource } from \"./http/fake-server.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.ts\";\nimport type { RequestEnd, RequestFn, Tracker } from \"./requests.ts\";\nimport { tracker } from \"./requests.ts\";\n\n/** A held work is one unit of work that stays in flight until the test releases it. */\nexport interface HeldWork {\n /** This method lets the work end. Its promise ends when the caller of the work has its answer, or its error. */\n release(): Promise<void>;\n /** This flag tells if the work got the cooperative abort of the drain. */\n readonly aborted: boolean;\n}\n\n/**\n * A transport subject is a transport and the client side of its work. The kit offers work through\n * it, holds work in flight through it, and reads the count of the transport.\n */\nexport interface TransportSubject {\n readonly impl: TransportImpl;\n /** This lifecycle goes to `start()`. Without it, the kit gives a detached lifecycle. */\n readonly life?: Lifecycle | undefined;\n /** This method offers one unit of new work. It gives true when the transport took it, and false when it refused it. */\n offer(): Promise<boolean>;\n /** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */\n hold(): Promise<HeldWork>;\n /**\n * This method sends one call through the transport, for the stream cases (option `streams`). The\n * handler of the call gives `call.work` to `life.request(call.controller, call.route, ...)` of the\n * lifecycle of the start, and writes its stream to the caller. It gives what the caller sees.\n */\n call?(call: StreamCall): CallerView | Promise<CallerView>;\n /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\n}\n\n/** A stream call is one request of the stream cases. The kit gives its work, and the subject sends it. */\nexport interface StreamCall {\n /** This name is the controller of the request in the lifecycle of the kit. */\n readonly controller: string;\n /** This name is the route of the request in the lifecycle of the kit. */\n readonly route: string;\n /** This function is the work of the request: one value, or a stream of values. */\n readonly work: RequestFn<unknown>;\n /** True tells that the answer is a stream of items. False tells that the answer is unary: one status and one value. */\n readonly stream: boolean;\n}\n\n/** A seen end is the end of a call, as its caller read it. */\nexport interface SeenEnd {\n readonly kind: RequestEnd[\"kind\"];\n /**\n * True tells that the end came in the body of the answer, after its status, for example as the\n * last line of a stream. False tells that the end came as the status of the answer.\n */\n readonly inBand: boolean;\n}\n\n/** A caller view is what the caller of a call has read so far. The kit reads it again until it changes. */\nexport interface CallerView {\n /** These values are the items that the caller read, in their sequence. */\n readonly items: readonly unknown[];\n /** This end is the end that the caller read, or null while the call is open. */\n readonly end: SeenEnd | null;\n}\n\n/**\n * This function gives a detached lifecycle: a lifecycle with no service, for the start of a\n * transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request\n * and each use of its health throws, because no service declares a route.\n */\nexport const detachedLifecycle = (): Lifecycle => {\n const none = (): never => {\n throw new Error(\"a detached lifecycle has no service: give the transport the lifecycle of a service\");\n };\n const health = { verdict: none, probe: none, metrics: none, subscribe: none, forceFail: none, drain: none, stop: none } as Health;\n return {\n health,\n state: \"running\",\n exitCode: null,\n errors: [],\n started: Promise.resolve(),\n done: new Promise<number>(() => {}),\n signal: new AbortController().signal,\n shutdown: none,\n request: none,\n inFlight: () => 0,\n keepAlive: () => true,\n };\n};\n\n/** These names are the controller and the route of each call of the stream cases. */\nconst CALLS = { controller: \"conformance\", route: \"call\" } as const;\n\n/**\n * This function gives a lifecycle with request tracking for the stream cases, and its tracker. The\n * kit uses the tracker for the stages of the shutdown, as the lifecycle of a service does. Its\n * requests are not idempotent, and it admits each request until the stop of its intake.\n */\nconst trackedLifecycle = (clock: Clock): { readonly life: Lifecycle; readonly requests: Tracker } => {\n const requests = tracker([{ name: CALLS.controller, requires: [], routes: { [CALLS.route]: { idempotent: false } } }], clock, () => null);\n const life: Lifecycle = {\n ...detachedLifecycle(),\n // the lifecycle owns each stream that it makes, thus the drain of the transport waits for the end of its cut\n request: (controller, route, work, options) => ownStream(requests.request(controller, route, work, options), life),\n inFlight: (controller) => requests.inFlight(controller),\n };\n return { life, requests };\n};\n\n/** A subject factory makes a new subject for each case, on the clock of the case. */\nexport type SubjectFactory = (clock: Clock) => TransportSubject | Promise<TransportSubject>;\n\n/** A conformance record is one measurement of a case, for the raw records of a run in CI. */\nexport interface ConformanceRecord {\n readonly case: string;\n readonly what: string;\n /** This time is the limit of the contract, in milliseconds. */\n readonly expected: number;\n /** This time is what the case measured, in milliseconds of the real clock. */\n readonly measured: number;\n}\n\n/** These options tune the conformance kit. */\nexport interface ConformanceOptions {\n /** This name goes before the name of each case. */\n readonly name?: string | undefined;\n /** This clock moves the cases: `fake` gives exact and fast cases, and `real` measures the timing. The default is `fake`. */\n readonly clock?: \"fake\" | \"real\" | undefined;\n /** This time is the cap of each drain of the cases, in milliseconds. The default is 1000. */\n readonly cap?: number | undefined;\n /** This time is the most that a close can take, in milliseconds of the real clock. The default is 1000. */\n readonly closeBound?: number | undefined;\n /** This time is the most that an event can take to reach the transport, in real milliseconds. The default is 100. */\n readonly slack?: number | undefined;\n /** False tells that the work of the transport cannot see the cooperative abort. The default is true. */\n readonly cooperative?: boolean | undefined;\n /** This count is the number of works that the count case holds. The default is 3. */\n readonly holds?: number | undefined;\n /**\n * True adds the stream cases (S6 D4). Then the subject gives `call`, and the kit gives the\n * transport a lifecycle with request tracking. The default is false.\n */\n readonly streams?: boolean | undefined;\n /** This function receives each measurement, for the raw records of a run. */\n readonly record?: ((record: ConformanceRecord) => void) | undefined;\n}\n\ninterface Time {\n readonly clock: Clock;\n pass(ms: number): Promise<void>;\n}\n\ninterface Tracked {\n readonly settled: boolean;\n readonly error: unknown;\n readonly failed: boolean;\n}\n\nconst realNow = (): number => performance.now();\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 *\n * The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a\n * unary call is a stream of one item. The kit gives the transport a lifecycle with request\n * tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.\n * - A unary call gives one value, and its end comes as the status of the answer.\n * - A stream stays in flight until its end, not until its first item.\n * - A failure after the first item ends the stream with an error line in the body, not a status.\n * A failure before the first item gets a status.\n * - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.\n * - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.\n */\nexport const transportConformance = (make: SubjectFactory, options: ConformanceOptions = {}): ContractCase[] => {\n const name = options.name ?? \"transport\";\n const fake = (options.clock ?? \"fake\") === \"fake\";\n const cap = options.cap ?? 1000;\n const closeBound = options.closeBound ?? 1000;\n const slack = options.slack ?? 100;\n const cooperative = options.cooperative ?? true;\n const holds = options.holds ?? 3;\n\n const timeOf = (): Time => {\n if (!fake) return { clock: realClock, pass: 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 if (!(options.streams ?? false)) return cases;\n\n /** A fed stream is a stream call whose items, end and failure the case gives. */\n interface Fed {\n readonly view: CallerView;\n push(value: unknown): void;\n finish(): void;\n fail(error: Error): void;\n /** This flag tells if the work got the abort of its signal. */\n readonly aborted: boolean;\n }\n\n const eachStream = (\n title: string,\n body: (subject: TransportSubject, time: Time, requests: Tracker) => Promise<void>,\n ): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n const { life, requests } = trackedLifecycle(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, life);\n check(subject.call !== undefined, \"the option streams needs a subject that gives call()\");\n await body(subject, time, requests);\n } finally {\n // each work of the case ends, thus no stream stays open after the case\n requests.stopIntake();\n requests.cooperativeAbort();\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const call = (subject: TransportSubject, given: StreamCall): Promise<CallerView> => Promise.resolve(subject.call!(given));\n\n const openStream = async (subject: TransportSubject): Promise<Fed> => {\n const source = pushedSource<unknown>();\n let started = false;\n let signal: AbortSignal | null = null;\n const view = await call(subject, {\n ...CALLS,\n stream: true,\n work: (given) => {\n started = true;\n signal = given;\n return source.iterable;\n },\n });\n check(await within(slack, () => started), \"the work of a stream call did not start\");\n return {\n view,\n push: (value) => source.push(value),\n finish: () => source.finish(),\n fail: (error) => source.fail(error),\n get aborted() {\n return (signal as AbortSignal | null)?.aborted === true;\n },\n };\n };\n\n const pushes = async (fed: Fed, value: number, what: string): Promise<void> => {\n const before = fed.view.items.length;\n fed.push(value);\n check(await within(slack, () => fed.view.items.length > before), `${what}: the caller did not get the item ${value}`);\n };\n\n const ends = async (view: CallerView, kind: RequestEnd[\"kind\"], inBand: boolean, what: string): Promise<void> => {\n check(await within(slack, () => view.end !== null), `${what}: the caller got no end`);\n const end = view.end!;\n const where = (body: boolean): string => (body ? \"in the body\" : \"as a status\");\n check(\n end.kind === kind && end.inBand === inBand,\n `${what}: the caller got the end ${end.kind} ${where(end.inBand)}, not ${kind} ${where(inBand)}`,\n );\n };\n\n /** This function stops the intake of the tracker and of the transport, as the stage `stop intake` does. */\n const stopBoth = async (subject: TransportSubject, requests: Tracker): Promise<void> => {\n requests.stopIntake();\n await subject.impl.stopIntake();\n };\n\n /**\n * This function starts the drain of the transport and of the tracker, as the stage `drain` does.\n * The abort of `signal` is also the cooperative abort of the tracker. It tracks the drain of the transport.\n */\n const drainBoth = (subject: TransportSubject, requests: Tracker, deadline: number, signal: AbortSignal): Tracked => {\n if (signal.aborted) requests.cooperativeAbort();\n else signal.addEventListener(\"abort\", () => requests.cooperativeAbort(), { once: true });\n void requests.drain(deadline);\n return track(attempt(() => subject.impl.drain(deadline, signal)));\n };\n\n const failure = (): Error => new Error(\"the failure of the conformance kit\");\n\n const streamCases: ContractCase[] = [\n eachStream(\"a unary call is a stream of one item: one value, and its end as the status\", async (subject) => {\n let started = false;\n let give: (value: unknown) => void = () => {};\n const view = await call(subject, {\n ...CALLS,\n stream: false,\n work: () => {\n started = true;\n return new Promise<unknown>((resolve) => {\n give = resolve;\n });\n },\n });\n check(await within(slack, () => started), \"the work of a unary call did not start\");\n await count(subject, 1, \"a unary call is in flight\");\n give(7);\n await ends(view, \"done\", false, \"a unary call\");\n check(view.items.length === 1 && view.items[0] === 7, `a unary call gave the items ${JSON.stringify(view.items)}, not [7]`);\n await count(subject, 0, \"a unary call ended\");\n }),\n\n eachStream(\"a stream stays in flight until its end, not until its first item\", async (subject) => {\n const fed = await openStream(subject);\n await count(subject, 1, \"a stream is open\");\n for (const value of [1, 2]) {\n await pushes(fed, value, \"an open stream\");\n await count(subject, 1, `a stream is open after its item ${value}`);\n }\n check(fed.view.end === null, \"the caller got an end before the end of the stream\");\n fed.finish();\n await ends(fed.view, \"done\", true, \"a stream that ended\");\n check(JSON.stringify(fed.view.items) === \"[1,2]\", `a stream gave the items ${JSON.stringify(fed.view.items)}, not [1,2]`);\n await count(subject, 0, \"a stream ended\");\n }),\n\n eachStream(\"a failure after the first item ends the stream with an error line, not a status\", async (subject) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before its failure\");\n fed.fail(failure());\n await ends(fed.view, \"failed\", true, \"a stream that failed after its first item\");\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"a failure before the first item gets a status, not an error line\", async (subject) => {\n const fed = await openStream(subject);\n fed.fail(failure());\n await ends(fed.view, \"failed\", false, \"a stream that failed before its first item\");\n check(fed.view.items.length === 0, `a stream that failed before its first item gave ${fed.view.items.length} items`);\n await count(subject, 0, \"a stream failed\");\n }),\n\n eachStream(\"drain waits for an open stream, and the cooperative abort ends the stream with its end\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const abort = new AbortController();\n const deadline = time.clock.now() + cap;\n const drained = drainBoth(subject, requests, deadline, abort.signal);\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while a stream was open, before its deadline\");\n check(fed.view.end === null, \"the caller got an end before the cooperative abort\");\n await count(subject, 1, \"a stream is open in the drain\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => fed.aborted), \"the work of the stream did not get the cooperative abort\");\n await ends(fed.view, \"cut\", true, \"a stream after the cooperative abort\");\n check(await within(slack, () => drained.settled), \"drain did not end when the stream ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the stream ended\");\n await count(subject, 0, \"the cooperative abort left a stream in flight\");\n }),\n\n eachStream(\"drain cuts an open stream at its deadline, and the caller gets the end of the cut\", async (subject, time, requests) => {\n const fed = await openStream(subject);\n await pushes(fed, 1, \"a stream before the drain\");\n await stopBoth(subject, requests);\n const drained = drainBoth(subject, requests, time.clock.now() + cap, new AbortController().signal);\n await time.pass(cap);\n await ends(fed.view, \"cut\", true, \"a stream at the deadline of the drain\");\n check(await within(slack, () => drained.settled), \"drain did not end after the cut of the stream\");\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n await count(subject, 0, \"the cut left a stream in flight\");\n }),\n ];\n return [...cases, ...streamCases];\n};\n","import type { FakeClock } from \"../fakes.ts\";\nimport { fakeClock } from \"../fakes.ts\";\nimport type { Logger } from \"../logger.ts\";\nimport type { ChildHandle, CommandOptions, CommandResult, HostPorts, ProcessMark, SpawnRequest, StopSignal } from \"./ports.ts\";\n\n/** A fake child is a child process of a fake host. A test ends it, or a stop ends it. */\nexport interface FakeChild extends ChildHandle {\n readonly request: SpawnRequest;\n /** These are the messages that went on its IPC channel. */\n readonly sent: readonly unknown[];\n /** This flag tells if the child ended. */\n readonly ended: boolean;\n /** This method ends the child with a code, or with a signal and a null code. A second use does nothing. */\n exit(code: number | null, signal?: string | null): void;\n /** This method sends data on the output of the child. */\n output(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array): void;\n}\n\n/** A recorded command is one command that went through the fake command port. */\nexport interface RecordedCommand {\n readonly file: string;\n readonly args: readonly string[];\n readonly options: CommandOptions | undefined;\n}\n\n/** A recorded signal is one signal that went through the fake process port. */\nexport interface RecordedSignal {\n readonly pid: number;\n readonly signal: StopSignal;\n readonly group: boolean;\n}\n\n/** These options go with a fake host. */\nexport interface FakeHostOptions {\n /** This text is the platform. The default is `linux`. */\n readonly platform?: string | undefined;\n readonly env?: Readonly<Record<string, string | undefined>> | undefined;\n /** The default is `/home/test`. */\n readonly homeDir?: string | undefined;\n /** The default is `test`. */\n readonly user?: string | undefined;\n /** This record names the host process. The default is the ID 100, which started at the wall time 0. */\n readonly self?: ProcessMark | undefined;\n /** This time is the wall time at the clock time 0, in milliseconds after the epoch. The default is 1 000 000 000 000. */\n readonly wallStart?: number | undefined;\n /** These files are in the fake file system at the start. */\n readonly files?: Readonly<Record<string, string | Uint8Array>> | undefined;\n /**\n * This function gives the result of a command. When it gives undefined, the fake answers. `taskkill`\n * with `/F` ends the process and gives 0. `taskkill` without `/F` gives 1, or ends a polite child. Each other command gives 0.\n */\n readonly answer?: ((command: RecordedCommand) => CommandResult | undefined) | undefined;\n readonly logger?: Logger | undefined;\n}\n\n/**\n * A fake host is the host ports of a test, and the state behind them. It starts no process, writes no\n * file and installs no task. Each effect is a record or a change of its state.\n */\nexport interface FakeHost {\n readonly ports: HostPorts;\n readonly clock: FakeClock;\n /** These are the files of the fake file system. */\n readonly files: Map<string, string | Uint8Array>;\n readonly commands: RecordedCommand[];\n readonly signals: RecordedSignal[];\n readonly children: FakeChild[];\n /** This table holds each live process: its ID, and its start time or null. */\n readonly processes: Map<number, number | null>;\n /** This map gives the HTTP status of each address. An address that it does not have gives no answer. */\n readonly http: Map<string, number | null>;\n /** This set holds each `host:port` that takes a TCP connection. */\n readonly tcp: Set<string>;\n /** True makes each child end with the code 0 at a staged stop: SIGTERM, SIGINT, an IPC message or `taskkill` without `/F`. */\n polite: boolean;\n /** This function makes a file operation fail. It gets the name of the operation and the path. */\n failFiles: ((operation: string, path: string) => boolean) | null;\n /** This function makes a spawn fail, thus the child has no ID and ends. */\n failSpawn: ((request: SpawnRequest) => boolean) | null;\n /** This method gives the text of a file, or null. */\n text(path: string): string | null;\n /** This method lets the promises that are ready continue, without a move of the clock. */\n settle(): Promise<void>;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst bytesOf = (data: string | Uint8Array): Uint8Array => (typeof data === \"string\" ? encoder.encode(data) : data);\n\n/** This function makes a fake host. Give its `ports` to the host functions in a test. */\nexport const fakeHost = (options: FakeHostOptions = {}): FakeHost => {\n const clock = fakeClock();\n const wallStart = options.wallStart ?? 1_000_000_000_000;\n const wall = (): number => wallStart + clock.now();\n const self = options.self ?? { pid: 100, startedAt: wallStart };\n const files = new Map<string, string | Uint8Array>(Object.entries(options.files ?? {}));\n const commands: RecordedCommand[] = [];\n const signals: RecordedSignal[] = [];\n const children: FakeChild[] = [];\n const processes = new Map<number, number | null>([[self.pid, self.startedAt]]);\n const live = new Map<number, FakeChild>();\n let nextPid = 1000;\n\n const check = (operation: string, path: string): void => {\n if (host.failFiles?.(operation, path) === true) throw new Error(`the fake ${operation} of ${path} failed`);\n };\n\n const politeStop = (pid: number): void => {\n const child = live.get(pid);\n if (host.polite && child !== undefined) queueMicrotask(() => child.exit(0));\n };\n const hardStop = (pid: number, signal: string | null): void => {\n const child = live.get(pid);\n if (child !== undefined) queueMicrotask(() => child.exit(null, signal));\n else processes.delete(pid);\n };\n\n const spawn = (request: SpawnRequest): FakeChild => {\n const failed = host.failSpawn?.(request) === true;\n const pid = failed ? null : nextPid++;\n const outputs: Array<(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void> = [];\n const exits: Array<(code: number | null, signal: string | null) => void> = [];\n const sent: unknown[] = [];\n let end: { code: number | null; signal: string | null } | null = null;\n const child: FakeChild = {\n request,\n pid,\n ipc: request.ipc,\n sent,\n get ended() {\n return end !== null;\n },\n onOutput(handler) {\n outputs.push(handler);\n },\n onExit(handler) {\n exits.push(handler);\n if (end !== null) handler(end.code, end.signal);\n },\n send(message) {\n if (!request.ipc || end !== null) return false;\n sent.push(message);\n if (pid !== null) politeStop(pid);\n return true;\n },\n exit(code, signal = null) {\n if (end !== null) return;\n end = { code, signal };\n if (pid !== null) {\n processes.delete(pid);\n live.delete(pid);\n }\n for (const handler of exits) handler(code, signal);\n },\n output(stream, chunk) {\n for (const handler of outputs) handler(stream, chunk);\n },\n };\n children.push(child);\n if (pid === null) queueMicrotask(() => child.exit(null));\n else {\n processes.set(pid, wall());\n live.set(pid, child);\n }\n return child;\n };\n\n const signal = (pid: number, sig: StopSignal, group: boolean): boolean => {\n if (!processes.has(pid)) return false;\n signals.push({ pid, signal: sig, group });\n if (sig === \"SIGKILL\") hardStop(pid, \"SIGKILL\");\n else politeStop(pid);\n return true;\n };\n\n const defaultAnswer = (command: RecordedCommand): CommandResult => {\n if (command.file !== \"taskkill\") return { code: 0, out: \"\" };\n const at = command.args.indexOf(\"/PID\");\n const pid = Number(command.args[at + 1]);\n if (at < 0 || !processes.has(pid)) return { code: 128, out: `ERROR: The process \"${command.args[at + 1] ?? \"\"}\" not found.` };\n if (command.args.includes(\"/F\")) {\n hardStop(pid, null);\n return { code: 0, out: `SUCCESS: The process with PID ${pid} has been terminated.` };\n }\n if (host.polite && live.has(pid)) {\n politeStop(pid);\n return { code: 0, out: `SUCCESS: Sent termination signal to the process with PID ${pid}.` };\n }\n return { code: 1, out: `ERROR: The process with PID ${pid} could not be terminated.` };\n };\n\n const ports: HostPorts = {\n platform: options.platform ?? \"linux\",\n commands: {\n async run(file, args, commandOptions) {\n const command: RecordedCommand = { file, args: [...args], options: commandOptions };\n commands.push(command);\n return options.answer?.(command) ?? defaultAnswer(command);\n },\n },\n files: {\n async read(path) {\n check(\"read\", path);\n const data = files.get(path);\n return data === undefined ? null : typeof data === \"string\" ? data : decoder.decode(data);\n },\n async write(path, data) {\n check(\"write\", path);\n files.set(path, data);\n },\n async create(path, data) {\n check(\"create\", path);\n if (files.has(path)) return false;\n files.set(path, data);\n return true;\n },\n async append(path, data) {\n check(\"append\", path);\n const before = files.get(path);\n if (before === undefined) files.set(path, data);\n else if (typeof before === \"string\" && typeof data === \"string\") files.set(path, before + data);\n else {\n const head = bytesOf(before);\n const tail = bytesOf(data);\n const joined = new Uint8Array(head.length + tail.length);\n joined.set(head, 0);\n joined.set(tail, head.length);\n files.set(path, joined);\n }\n },\n async size(path) {\n check(\"size\", path);\n const data = files.get(path);\n return data === undefined ? null : bytesOf(data).length;\n },\n async rename(from, to) {\n check(\"rename\", from);\n const data = files.get(from);\n if (data === undefined) throw new Error(`the fake file ${from} does not exist`);\n files.delete(from);\n files.set(to, data);\n },\n async remove(path) {\n check(\"remove\", path);\n files.delete(path);\n },\n },\n processes: {\n alive: (pid) => processes.has(pid),\n startOf: async (pid) => processes.get(pid) ?? null,\n signal: (pid, sig) => signal(pid, sig, false),\n signalGroup: (pid, sig) => ports.platform !== \"win32\" && live.has(pid) && signal(pid, sig, true),\n spawn,\n },\n net: {\n httpStatus: async (url) => host.http.get(url) ?? null,\n tcpConnect: async (hostName, port) => host.tcp.has(`${hostName}:${port}`),\n },\n clock,\n wall,\n self,\n env: options.env ?? {},\n homeDir: options.homeDir ?? \"/home/test\",\n user: () => options.user ?? \"test\",\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n\n const host: FakeHost = {\n ports,\n clock,\n files,\n commands,\n signals,\n children,\n processes,\n http: new Map(),\n tcp: new Set(),\n polite: false,\n failFiles: null,\n failSpawn: null,\n text(path) {\n const data = files.get(path);\n return data === undefined ? null : typeof data === \"string\" ? data : decoder.decode(data);\n },\n async settle() {\n for (let turn = 0; turn < 2000; turn += 1) await Promise.resolve();\n },\n };\n return host;\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. A test logger keeps each log entry. `contractCases` generates the contract test of a\n// declaration, and `transportConformance` generates the conformance test of a transport. A fake host\n// gives the ports of the host entry, thus a test installs no task and starts no process.\n\nimport type { AddressInfo, Server, Socket } from \"node:net\";\nimport { createServer } from \"node:net\";\nimport type { Outcome } from \"./latch.ts\";\nimport type { LogEntry, LogLevel, Logger } from \"./logger.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 CallerView,\n ConformanceOptions,\n ConformanceRecord,\n HeldWork,\n SeenEnd,\n StreamCall,\n SubjectFactory,\n TransportSubject,\n} from \"./conformance.ts\";\nexport { detachedLifecycle, transportConformance } from \"./conformance.ts\";\nexport type { FakeChild, FakeHost, FakeHostOptions, RecordedCommand, RecordedSignal } from \"./host/fakes.ts\";\nexport { fakeHost } from \"./host/fakes.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 test logger is a logger that keeps each entry, thus a test can examine the log of the runtime. */\nexport interface TestLogger extends Logger {\n /** These are the entries, in the sequence of their calls. */\n readonly entries: readonly LogEntry[];\n /** This method gives the message of each entry, or of each entry at one level. */\n messages(level?: LogLevel): string[];\n /** This method removes each entry. */\n clear(): void;\n}\n\n/** This function makes a test logger with no entries. */\nexport const testLogger = (): TestLogger => {\n const entries: LogEntry[] = [];\n return {\n entries,\n log(level, message, fields) {\n entries.push({ level, message, fields });\n },\n messages: (level) => entries.filter((entry) => level === undefined || entry.level === level).map((entry) => entry.message),\n clear() {\n entries.length = 0;\n },\n };\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":";;;;;;;;;;;AA8CA,MAAa,eAAe,UAA8B,CAAC,MAAmB;CAC5E,MAAM,2BAAW,IAAI,IAAmD;CACxE,MAAM,mCAAmB,IAAI,IAAsD;CACnF,MAAM,QAAkB,CAAC;CACzB,MAAM,MAAgB,CAAC;CACvB,IAAI,UAAU;CACd,IAAI,QAAQ;CACZ,MAAM,aAAuB,CAAC;CAC9B,MAAM,SAAS,SAAuB;EACpC,IAAI,KAAK,QAAQ,UAAU,KAAA,IAAY,OAAO,GAAG,QAAQ,MAAM,IAAI,EAAE,GAAG,MAAM;CAChF;CACA,MAAM,QAAQ,MAAmB,YAA4B;EAC3D,KAAK,MAAM,WAAW,CAAC,GAAI,SAAS,IAAI,IAAI,KAAK,CAAC,CAAE,GAAG,QAAQ,OAAO;CACxE;CACA,OAAO;EACL,GAAG,SAAS,SAAS;GACnB,MAAM,MAAM,SAAS,IAAI,OAAO,qBAAK,IAAI,IAAI;GAC7C,IAAI,IAAI,OAAO;GACf,SAAS,IAAI,SAAS,GAAG;GACzB,aAAa;IACX,IAAI,OAAO,OAAO;GACpB;EACF;EACA,WAAW,SAAS;GAElB,MAAM,OAAO,OAAgB,WAAiC,QAAQ,OAAO,MAAM;GACnF,iBAAiB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Exact, quantity, rationals, valueIn } from "@mark1russell7/quantity";
|
|
3
|
-
|
|
3
|
+
// src/timing.ts
|
|
4
4
|
const seconds = (amount) => convertExact(rationals.fromNumber(amount.value), amount.unit, "s");
|
|
5
5
|
const out = (value) => quantity(rationals.toNumber(value), "s");
|
|
6
6
|
const fraction = (jitter) => {
|
|
@@ -82,7 +82,6 @@ const heartbeatDetection = (interval, timeout, misses) => interval.value === "in
|
|
|
82
82
|
value: "infinite",
|
|
83
83
|
unit: "s"
|
|
84
84
|
} : quantity(detectionTime(valueIn(interval, "ms"), valueIn(timeout, "ms"), misses) / 1e3, "s");
|
|
85
|
-
//#endregion
|
|
86
85
|
export { recoverSpan as a, heartbeatDetection as i, asWindow as n, failSpan as r, asDebounce as t };
|
|
87
86
|
|
|
88
|
-
//# sourceMappingURL=timing-
|
|
87
|
+
//# sourceMappingURL=timing-DZl36uXs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timing-
|
|
1
|
+
{"version":3,"file":"timing-DZl36uXs.js","names":["r"],"sources":["../src/timing.ts"],"sourcesContent":["import type { Extent, Quantity, Rational } from \"@mark1russell7/quantity\";\nimport { convertExact, quantity, rationals as r, valueIn } from \"@mark1russell7/quantity\";\nimport { detectionTime } from \"./heartbeat.ts\";\n\n/**\n * All policies have the same timing shape. A timing is a count of polls (a debounce) or a\n * duration (a window), and each converts to the other. A long window is easier to read as a\n * duration, and that is the only difference between the two.\n */\nexport type Timing =\n | {\n readonly type: \"debounce\";\n /** This interval is the time between two polls of the signal. */\n readonly interval: Quantity;\n /** This count is the number of failed polls in sequence before the policy fails. */\n readonly failAfter: number;\n /** This count is the number of passed polls in sequence before the policy recovers. */\n readonly recoverAfter: number;\n }\n | {\n readonly type: \"window\";\n /** This duration is how long the signal fails before the policy fails, on the monotonic clock. */\n readonly failAfter: Quantity;\n /** This duration is how long the signal passes before the policy recovers. Without it, the first pass recovers the policy. */\n readonly recoverAfter?: Quantity | undefined;\n };\n\n/** A poll has an interval, a jitter as a fraction (±20 % is 0.2) and a timeout. */\nexport interface Poll {\n readonly interval: Quantity;\n readonly jitter: number;\n readonly timeout: Quantity;\n}\n\n/** A span is a range of times, from the earliest to the latest. */\nexport interface Span {\n readonly min: Quantity;\n readonly max: Quantity;\n}\n\n/**\n * This type tells how a failed step answers a poll.\n * - An `\"error\"` step refuses at once.\n * - A `\"timeout\"` step (a black hole) answers only when the timeout of the poll ends. Each poll\n * makes a new call, and each call ends at its timeout. Thus the step is slower by that timeout,\n * at the two ends of the span.\n * - A `\"hang\"` step makes a use that does not end. The first poll fails at its timeout. While the\n * use stays pending, the runtime does not start the check again, and each later poll fails at\n * once. Thus a debounce of two polls or more fails as fast as on an error.\n */\nexport type FailsBy = \"error\" | \"timeout\" | \"hang\";\n\nconst seconds = (amount: Quantity): Rational =>\n convertExact(r.fromNumber(amount.value), amount.unit, \"s\");\nconst out = (value: Rational): Quantity => quantity(r.toNumber(value), \"s\");\nconst fraction = (jitter: number): Rational => {\n if (!(jitter >= 0 && jitter < 1))\n throw new RangeError(`jitter is a fraction below 1, not ${jitter}`);\n return r.fromNumber(jitter);\n};\nconst count = (polls: number, what: string): Rational => {\n if (!Number.isInteger(polls) || polls < 1)\n throw new RangeError(`${what} is a whole number of polls, not ${polls}`);\n return r.rational(BigInt(polls));\n};\n\n/** N polls with jitter take from N − 1 short intervals to N long intervals. */\nconst debounced = (polls: Rational, interval: Rational, jitter: Rational): [Rational, Rational] => [\n r.mul(r.sub(polls, r.ONE), r.mul(interval, r.sub(r.ONE, jitter))),\n r.mul(polls, r.mul(interval, r.add(r.ONE, jitter))),\n];\n\n/**\n * This function gives the time that a policy takes to fail after its signal becomes bad. A\n * debounce of N polls takes approximately N intervals, with the jitter. A window takes its\n * duration, plus one interval at most for the poll that starts its sequence. A step that fails by\n * a timeout adds the timeout of the poll. At 3 polls of 5 s ± 20 %, the latch fails in 8–18 s on\n * an error, and in 12–22 s on a 4 s timeout. A step that hangs adds the timeout only where its\n * first failure ends the sequence: a window, or a debounce of one poll.\n */\nexport const failSpan = (timing: Timing, poll: Poll, by: FailsBy = \"error\"): Span => {\n const jitter = fraction(poll.jitter);\n const first = timing.type === \"window\" || timing.failAfter === 1;\n const late =\n by === \"timeout\" || (by === \"hang\" && first) ? seconds(poll.timeout) : r.ZERO;\n if (timing.type === \"debounce\") {\n const [min, max] = debounced(\n count(timing.failAfter, \"failAfter\"),\n seconds(timing.interval),\n jitter,\n );\n return { min: out(r.add(min, late)), max: out(r.add(max, late)) };\n }\n const duration = seconds(timing.failAfter);\n const interval = r.mul(seconds(poll.interval), r.add(r.ONE, jitter));\n return { min: out(r.add(duration, late)), max: out(r.add(r.add(duration, interval), late)) };\n};\n\n/** This function gives the time that a policy takes to recover after its signal becomes good. */\nexport const recoverSpan = (timing: Timing, poll: Poll): Span => {\n const jitter = fraction(poll.jitter);\n if (timing.type === \"debounce\") {\n const [min, max] = debounced(\n count(timing.recoverAfter, \"recoverAfter\"),\n seconds(timing.interval),\n jitter,\n );\n return { min: out(min), max: out(max) };\n }\n const duration = timing.recoverAfter === undefined ? r.ZERO : seconds(timing.recoverAfter);\n const interval = r.mul(seconds(poll.interval), r.add(r.ONE, jitter));\n return { min: out(duration), max: out(r.add(duration, interval)) };\n};\n\n/** This function gives the window that a debounce approximates: N polls of an interval fail after N intervals. */\nexport const asWindow = (timing: Timing): Timing =>\n timing.type === \"window\"\n ? timing\n : {\n type: \"window\",\n failAfter: out(r.mul(count(timing.failAfter, \"failAfter\"), seconds(timing.interval))),\n recoverAfter: out(\n r.mul(count(timing.recoverAfter, \"recoverAfter\"), seconds(timing.interval)),\n ),\n };\n\n/** This function gives the debounce that approximates a window on a poll: the polls that fit, rounded up. */\nexport const asDebounce = (timing: Timing, poll: Poll): Timing => {\n if (timing.type === \"debounce\") return timing;\n const interval = seconds(poll.interval);\n const polls = (duration: Rational | undefined): number =>\n duration === undefined ? 1 : Math.max(1, Number(r.ceil(r.div(duration, interval)).n));\n return {\n type: \"debounce\",\n interval: poll.interval,\n failAfter: polls(seconds(timing.failAfter)),\n recoverAfter: polls(\n timing.recoverAfter === undefined ? undefined : seconds(timing.recoverAfter),\n ),\n };\n};\n\n/**\n * This function gives the most time that a heartbeat takes to find a silent peer, as an amount\n * for the ordering law (`detectionTime`). An interval of \"infinite\" is a heartbeat that is off.\n */\nexport const heartbeatDetection = (interval: Extent, timeout: Quantity, misses: number): Extent =>\n interval.value === \"infinite\"\n ? { value: \"infinite\", unit: \"s\" }\n : quantity(detectionTime(valueIn(interval as Quantity, \"ms\"), valueIn(timeout, \"ms\"), misses) / 1000, \"s\");\n"],"mappings":";;;AAoDA,MAAM,WAAW,WACf,aAAaA,UAAE,WAAW,OAAO,KAAK,GAAG,OAAO,MAAM,GAAG;AAC3D,MAAM,OAAO,UAA8B,SAASA,UAAE,SAAS,KAAK,GAAG,GAAG;AAC1E,MAAM,YAAY,WAA6B;CAC7C,IAAI,EAAE,UAAU,KAAK,SAAS,IAC5B,MAAM,IAAI,WAAW,qCAAqC,QAAQ;CACpE,OAAOA,UAAE,WAAW,MAAM;AAC5B;AACA,MAAM,SAAS,OAAe,SAA2B;CACvD,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WAAW,GAAG,KAAK,mCAAmC,OAAO;CACzE,OAAOA,UAAE,SAAS,OAAO,KAAK,CAAC;AACjC;;AAGA,MAAM,aAAa,OAAiB,UAAoB,WAA2C,CACjGA,UAAE,IAAIA,UAAE,IAAI,OAAOA,UAAE,GAAG,GAAGA,UAAE,IAAI,UAAUA,UAAE,IAAIA,UAAE,KAAK,MAAM,CAAC,CAAC,GAChEA,UAAE,IAAI,OAAOA,UAAE,IAAI,UAAUA,UAAE,IAAIA,UAAE,KAAK,MAAM,CAAC,CAAC,CACpD;;;;;;;;;AAUA,MAAa,YAAY,QAAgB,MAAY,KAAc,YAAkB;CACnF,MAAM,SAAS,SAAS,KAAK,MAAM;CACnC,MAAM,QAAQ,OAAO,SAAS,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