@mark1russell7/service 0.6.2 → 0.6.3

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.
Files changed (42) hide show
  1. package/README.md +88 -2
  2. package/build/{builder-0OlfomVU.d.ts → builder-bXJqMe2p.d.ts} +3 -2
  3. package/build/{core-Iy9rIXOT.d.ts → core-B1zbS4WY.d.ts} +4 -3
  4. package/build/{dial-DLT7bTlA.d.ts → dial-CSGKVlZe.d.ts} +2 -2
  5. package/build/grpc.d.ts +3 -3
  6. package/build/grpc.js +1 -1
  7. package/build/host.d.ts +556 -0
  8. package/build/host.js +1738 -0
  9. package/build/host.js.map +1 -0
  10. package/build/http-client.d.ts +3 -3
  11. package/build/http-client.js +1 -1
  12. package/build/http.d.ts +1 -1
  13. package/build/index.d.ts +4 -3
  14. package/build/index.js +3 -169
  15. package/build/index.js.map +1 -1
  16. package/build/lifecycle-Ks9Yd5CM.d.ts +387 -0
  17. package/build/{lifecycle-DXK880vG.d.ts → logger-DhFgh48y.d.ts} +2 -385
  18. package/build/{machine-Dq2OlzCG.js → machine-DKWLZOqu.js} +3 -2
  19. package/build/{machine-Dq2OlzCG.js.map → machine-DKWLZOqu.js.map} +1 -1
  20. package/build/mongodb.d.ts +3 -3
  21. package/build/mongodb.js +1 -1
  22. package/build/operation-DL5RxFds.js +25 -0
  23. package/build/operation-DL5RxFds.js.map +1 -0
  24. package/build/pg.d.ts +2 -2
  25. package/build/pg.js +1 -1
  26. package/build/ports-CZLzYK5d.d.ts +125 -0
  27. package/build/process-DG_im2zc.js +171 -0
  28. package/build/process-DG_im2zc.js.map +1 -0
  29. package/build/{queue-CvBNNZZJ.d.ts → queue-BjiGodqh.d.ts} +3 -2
  30. package/build/rabbitmq.d.ts +4 -4
  31. package/build/rabbitmq.js +1 -1
  32. package/build/redis.d.ts +2 -2
  33. package/build/redis.js +1 -1
  34. package/build/{retrier-CRda6z9G.js → retrier-Bzkme_yM.js} +2 -24
  35. package/build/retrier-Bzkme_yM.js.map +1 -0
  36. package/build/testing.d.ts +84 -3
  37. package/build/testing.js +226 -1
  38. package/build/testing.js.map +1 -1
  39. package/build/websocket.d.ts +3 -3
  40. package/build/websocket.js +1 -1
  41. package/package.json +5 -1
  42. package/build/retrier-CRda6z9G.js.map +0 -1
@@ -0,0 +1,171 @@
1
+ //#region src/process.ts
2
+ /** These are the signals that the runtime handles. */
3
+ const EXIT_SIGNALS = [
4
+ "SIGINT",
5
+ "SIGTERM",
6
+ "SIGQUIT"
7
+ ];
8
+ /** These are the process triggers that a declaration can opt in to. */
9
+ const PROCESS_TRIGGERS = [
10
+ "stdin-close",
11
+ "ipc-close",
12
+ "ipc-message"
13
+ ];
14
+ /** These are the origins of the errors that the option `uncaught` of `run()` receives. */
15
+ const UNCAUGHT_ORIGINS = ["uncaughtException", "unhandledRejection"];
16
+ /** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */
17
+ const isExitCode = (code) => Number.isInteger(code) && code >= 0 && code <= 255;
18
+ /** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */
19
+ const isExitSignal = (trigger) => EXIT_SIGNALS.includes(trigger);
20
+ /** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */
21
+ const isMessageShape = (value) => {
22
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
23
+ if (typeof value === "number") return Number.isFinite(value);
24
+ if (Array.isArray(value)) return value.every(isMessageShape);
25
+ if (typeof value !== "object") return false;
26
+ const prototype = Object.getPrototypeOf(value);
27
+ return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);
28
+ };
29
+ /** This function tells if a message of the IPC channel matches a shape. */
30
+ const matchesMessage = (shape, message) => {
31
+ if (shape === null || typeof shape !== "object") return Object.is(shape, message);
32
+ if (Array.isArray(shape)) {
33
+ const items = shape;
34
+ return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));
35
+ }
36
+ if (message === null || typeof message !== "object" || Array.isArray(message)) return false;
37
+ const fields = message;
38
+ return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));
39
+ };
40
+ /** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */
41
+ const HOLD_INTERVAL = 2147483647;
42
+ /** This function adds a handler to some events of an emitter. The handler operates one time at most. */
43
+ const once = (emitter, events, handler) => {
44
+ let called = false;
45
+ const fire = () => {
46
+ if (called) return;
47
+ called = true;
48
+ handler();
49
+ };
50
+ for (const event of events) emitter.on(event, fire);
51
+ return () => {
52
+ for (const event of events) emitter.off(event, fire);
53
+ };
54
+ };
55
+ /** This function gives a promise that ends when the data before it in a stream is written. */
56
+ const written = (stream) => new Promise((resolve) => {
57
+ if (stream === void 0 || stream.destroyed === true || stream.writable === false) {
58
+ resolve();
59
+ return;
60
+ }
61
+ try {
62
+ stream.write("", () => resolve());
63
+ } catch {
64
+ resolve();
65
+ }
66
+ });
67
+ /**
68
+ * This function makes a process port on a host. `find` gives the host at each use, or undefined
69
+ * when the platform has no process. Then the use throws.
70
+ */
71
+ const processPortOf = (find) => {
72
+ const hostProcess = () => {
73
+ const host = find();
74
+ if (host === void 0) throw new Error("no process: give the runtime a process port");
75
+ return host;
76
+ };
77
+ return {
78
+ on(trigger, handler) {
79
+ const host = hostProcess();
80
+ if (trigger === "stdin-close") {
81
+ const input = host.stdin;
82
+ if (input === void 0) return () => {};
83
+ if (input.readableEnded === true) {
84
+ let live = true;
85
+ queueMicrotask(() => {
86
+ if (live) handler();
87
+ });
88
+ return () => {
89
+ live = false;
90
+ };
91
+ }
92
+ return once(input, ["end", "close"], handler);
93
+ }
94
+ if (trigger === "ipc-close") return once(host, ["disconnect"], handler);
95
+ if (trigger === "ipc-message") {
96
+ const receive = (message) => handler(message);
97
+ host.on("message", receive);
98
+ return () => {
99
+ host.off("message", receive);
100
+ };
101
+ }
102
+ host.on(trigger, handler);
103
+ return () => {
104
+ host.off(trigger, handler);
105
+ };
106
+ },
107
+ onUncaught(handler) {
108
+ const host = hostProcess();
109
+ const offs = UNCAUGHT_ORIGINS.map((origin) => {
110
+ const receive = (error) => handler(error, origin);
111
+ host.on(origin, receive);
112
+ return () => {
113
+ host.off(origin, receive);
114
+ };
115
+ });
116
+ return () => {
117
+ for (const off of offs) off();
118
+ };
119
+ },
120
+ async flush() {
121
+ const host = hostProcess();
122
+ await Promise.all([written(host.stdout), written(host.stderr)]);
123
+ },
124
+ hold() {
125
+ hostProcess();
126
+ const timer = setInterval(() => {}, HOLD_INTERVAL);
127
+ let held = true;
128
+ return () => {
129
+ if (!held) return;
130
+ held = false;
131
+ clearInterval(timer);
132
+ };
133
+ },
134
+ exit(code) {
135
+ hostProcess().exit(code);
136
+ }
137
+ };
138
+ };
139
+ /** This port is the process of Node. */
140
+ const nodeProcess = processPortOf(() => globalThis.process);
141
+ /**
142
+ * This function gives a process port for a lifecycle in a process that another part owns. That
143
+ * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of
144
+ * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops
145
+ * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to
146
+ * that service, and does not use this port.
147
+ */
148
+ const embeddedProcess = () => {
149
+ let code = null;
150
+ let resolve = () => {};
151
+ return {
152
+ on() {
153
+ return () => {};
154
+ },
155
+ exit(requested) {
156
+ if (code !== null) return;
157
+ code = requested;
158
+ resolve(requested);
159
+ },
160
+ get exitCode() {
161
+ return code;
162
+ },
163
+ exited: new Promise((done) => {
164
+ resolve = done;
165
+ })
166
+ };
167
+ };
168
+ //#endregion
169
+ export { isExitCode as a, matchesMessage as c, embeddedProcess as i, nodeProcess as l, PROCESS_TRIGGERS as n, isExitSignal as o, UNCAUGHT_ORIGINS as r, isMessageShape as s, EXIT_SIGNALS as t, processPortOf as u };
170
+
171
+ //# sourceMappingURL=process-DG_im2zc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-DG_im2zc.js","names":[],"sources":["../src/process.ts"],"sourcesContent":["/** An exit signal is a signal that asks the process to stop: each one starts the shutdown. */\nexport type ExitSignal = \"SIGINT\" | \"SIGTERM\" | \"SIGQUIT\";\n\n/** These are the signals that the runtime handles. */\nexport const EXIT_SIGNALS: readonly ExitSignal[] = [\"SIGINT\", \"SIGTERM\", \"SIGQUIT\"];\n\n/**\n * A process trigger is an event of the process, other than a signal, that starts the shutdown. A\n * declaration opts in to each one (`svc.trigger`):\n * - `stdin-close`: the standard input ends or closes, as when the parent of a stdio child goes away.\n * The process must read its input, as a stdio transport does, or Node does not see the end.\n * - `ipc-close`: the IPC channel to the parent process closes.\n * - `ipc-message`: a message on the IPC channel matches a declared shape. Windows cannot give a\n * child a SIGTERM that the child can catch, thus a parent sends a message.\n */\nexport type ProcessTrigger = \"stdin-close\" | \"ipc-close\" | \"ipc-message\";\n\n/** These are the process triggers that a declaration can opt in to. */\nexport const PROCESS_TRIGGERS: readonly ProcessTrigger[] = [\"stdin-close\", \"ipc-close\", \"ipc-message\"];\n\n/** An exit trigger is an event that starts the shutdown: an exit signal, or a declared process trigger. */\nexport type ExitTrigger = ExitSignal | ProcessTrigger;\n\n/**\n * An uncaught origin tells how an error that no code caught came to the process. It is an exception\n * that no code caught, or a rejection of a promise that no code handled.\n */\nexport type UncaughtOrigin = \"uncaughtException\" | \"unhandledRejection\";\n\n/** These are the origins of the errors that the option `uncaught` of `run()` receives. */\nexport const UNCAUGHT_ORIGINS: readonly UncaughtOrigin[] = [\"uncaughtException\", \"unhandledRejection\"];\n\n/** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */\nexport const isExitCode = (code: number): boolean => Number.isInteger(code) && code >= 0 && code <= 255;\n\n/** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */\nexport const isExitSignal = (trigger: string): trigger is ExitSignal =>\n (EXIT_SIGNALS as readonly string[]).includes(trigger);\n\n/**\n * A message shape is a value of JSON that a message of the IPC channel can match. A string, a\n * number, a boolean or null matches an equal message. An object matches a message that has each of\n * its fields, and each value of the field matches. An array matches an array of the same length, item by item.\n */\nexport type MessageShape = string | number | boolean | null | readonly MessageShape[] | { readonly [field: string]: MessageShape };\n\n/** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */\nexport const isMessageShape = (value: unknown): value is MessageShape => {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isMessageShape);\n if (typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);\n};\n\n/** This function tells if a message of the IPC channel matches a shape. */\nexport const matchesMessage = (shape: MessageShape, message: unknown): boolean => {\n if (shape === null || typeof shape !== \"object\") return Object.is(shape, message);\n if (Array.isArray(shape)) {\n const items: readonly MessageShape[] = shape;\n return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));\n }\n if (message === null || typeof message !== \"object\" || Array.isArray(message)) return false;\n const fields = message as Readonly<Record<string, unknown>>;\n return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));\n};\n\n/**\n * A process port is the part of the process that the runtime uses: its exit triggers, its output\n * and its exit. The runtime owns the handlers, because Node as PID 1 without a handler ignores\n * SIGTERM. Only the runtime ends the process, and library code does not. A test gives a fake port,\n * sends triggers, and reads the exit code.\n */\nexport interface ProcessPort {\n /**\n * This method adds a handler for a trigger, and gives the function that removes it. The runtime\n * asks for a process trigger only when the declaration opts in to it. For `ipc-message`, the\n * handler gets each message of the IPC channel, and the runtime matches it.\n */\n on(trigger: ExitTrigger, handler: (message?: unknown) => void): () => void;\n /**\n * This method adds a handler for each error that no code caught, and gives the function that\n * removes it. The runtime asks for it only when `run()` gets the option `uncaught`. A port without\n * this method gets no handler, as the embedded port.\n */\n onUncaught?(handler: (error: unknown, origin: UncaughtOrigin) => void): () => void;\n /**\n * This method writes each buffered line of the output, and its promise ends when the output is\n * written. The stage `flush the output` uses it, in the cap of that stage.\n */\n flush?(): Promise<void> | void;\n /**\n * This method keeps the process alive, and gives the function that releases it. The lifecycle\n * holds its process from its start to its exit, as a listening socket does. Thus a process whose\n * timers do not keep it alive does not end in the middle of its work. It keeps its teardown and its exit code.\n */\n hold?(): () => void;\n /** This method ends the process with a code: the code of the exit request, 1 after an error, or 0. */\n exit(code: number): void;\n}\n\n/** A host stream is the part of a stream of Node that the port uses. */\nexport interface HostStream {\n readonly writable?: boolean;\n readonly destroyed?: boolean;\n readonly readableEnded?: boolean;\n write(chunk: string, done: (error?: unknown) => void): boolean;\n on(event: string, handler: () => void): unknown;\n off(event: string, handler: () => void): unknown;\n}\n\n/** A process host is the part of the process of Node that the port uses. Its event `message` gives the message of the IPC channel. */\nexport interface ProcessHost {\n on(signal: string, handler: (message?: unknown) => void): unknown;\n off(signal: string, handler: (message?: unknown) => void): unknown;\n exit(code: number): unknown;\n readonly stdin?: HostStream | undefined;\n readonly stdout?: HostStream | undefined;\n readonly stderr?: HostStream | undefined;\n}\n\n/** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */\nconst HOLD_INTERVAL = 0x7fffffff;\n\n/** This function adds a handler to some events of an emitter. The handler operates one time at most. */\nconst once = (emitter: HostStream | ProcessHost, events: readonly string[], handler: () => void): (() => void) => {\n let called = false;\n const fire = (): void => {\n if (called) return;\n called = true;\n handler();\n };\n for (const event of events) emitter.on(event, fire);\n return () => {\n for (const event of events) emitter.off(event, fire);\n };\n};\n\n/** This function gives a promise that ends when the data before it in a stream is written. */\nconst written = (stream: HostStream | undefined): Promise<void> =>\n new Promise<void>((resolve) => {\n if (stream === undefined || stream.destroyed === true || stream.writable === false) {\n resolve();\n return;\n }\n try {\n // the callback of an empty write comes after each write before it\n stream.write(\"\", () => resolve());\n } catch {\n resolve();\n }\n });\n\n/**\n * This function makes a process port on a host. `find` gives the host at each use, or undefined\n * when the platform has no process. Then the use throws.\n */\nexport const processPortOf = (find: () => ProcessHost | undefined): ProcessPort => {\n const hostProcess = (): ProcessHost => {\n const host = find();\n if (host === undefined) throw new Error(\"no process: give the runtime a process port\");\n return host;\n };\n return {\n on(trigger, handler) {\n const host = hostProcess();\n if (trigger === \"stdin-close\") {\n const input = host.stdin;\n if (input === undefined) return () => {};\n // an input that ended before the handler was added still starts the shutdown\n if (input.readableEnded === true) {\n let live = true;\n queueMicrotask(() => {\n if (live) handler();\n });\n return () => {\n live = false;\n };\n }\n return once(input, [\"end\", \"close\"], handler);\n }\n if (trigger === \"ipc-close\") return once(host, [\"disconnect\"], handler);\n if (trigger === \"ipc-message\") {\n // each message goes to the runtime, which matches it with the declared shapes\n const receive = (message?: unknown): void => handler(message);\n host.on(\"message\", receive);\n return () => {\n host.off(\"message\", receive);\n };\n }\n host.on(trigger, handler);\n return () => {\n host.off(trigger, handler);\n };\n },\n onUncaught(handler) {\n const host = hostProcess();\n // a handler of each origin: Node then does not end the process, and the runtime does the shutdown\n const offs = UNCAUGHT_ORIGINS.map((origin) => {\n const receive = (error?: unknown): void => handler(error, origin);\n host.on(origin, receive);\n return () => {\n host.off(origin, receive);\n };\n });\n return () => {\n for (const off of offs) off();\n };\n },\n async flush() {\n const host = hostProcess();\n await Promise.all([written(host.stdout), written(host.stderr)]);\n },\n hold() {\n hostProcess();\n // one interval that keeps the event loop alive: its timer does nothing, and the release stops it\n const timer = setInterval(() => {}, HOLD_INTERVAL);\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n clearInterval(timer);\n };\n },\n exit(code) {\n hostProcess().exit(code);\n },\n };\n};\n\n/** This port is the process of Node. */\nexport const nodeProcess: ProcessPort = processPortOf(() => (globalThis as { process?: ProcessHost }).process);\n\n/** An embedded process port records the exit code of a lifecycle that does not own its process. */\nexport interface EmbeddedProcess extends ProcessPort {\n /** This code is the code of the exit request of the lifecycle, or null before that request. */\n readonly exitCode: number | null;\n /** This promise ends with the exit code when the lifecycle asks for its exit. */\n readonly exited: Promise<number>;\n}\n\n/**\n * This function gives a process port for a lifecycle in a process that another part owns. That\n * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of\n * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops\n * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to\n * that service, and does not use this port.\n */\nexport const embeddedProcess = (): EmbeddedProcess => {\n let code: number | null = null;\n let resolve: (code: number) => void = () => {};\n const exited = new Promise<number>((done) => {\n resolve = done;\n });\n return {\n on() {\n // the owner of the process keeps its signals and triggers\n return () => {};\n },\n exit(requested) {\n if (code !== null) return;\n code = requested;\n resolve(requested);\n },\n get exitCode() {\n return code;\n },\n exited,\n };\n};\n"],"mappings":"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"}
@@ -1,5 +1,6 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { d as TransportImpl, r as Lifecycle, ut as ServiceDescription } from "./lifecycle-DXK880vG.js";
2
+ import { D as ServiceDescription } from "./logger-DhFgh48y.js";
3
+ import { d as TransportImpl, r as Lifecycle } from "./lifecycle-Ks9Yd5CM.js";
3
4
  import { Extent, Quantity } from "@mark1russell7/quantity";
4
5
  //#region src/units.d.ts
5
6
  /**
@@ -147,4 +148,4 @@ declare const redeliverOnce: <J>(then: JobAction | RedeliveryPolicy<J>, poison?:
147
148
  declare const queueDrain: <J>(knobs: QueueKnobs, options: QueueDrainOptions<J>) => QueueDrain;
148
149
  //#endregion
149
150
  export { JobSource as a, QueueKnobs as c, queueDrain as d, redeliverOnce as f, JobSettle as i, RedeliveryPolicy as l, JobContext as n, QueueDrain as o, UnitRequest as p, JobFailure as r, QueueDrainOptions as s, JobAction as t, RequeueCause as u };
150
- //# sourceMappingURL=queue-CvBNNZZJ.d.ts.map
151
+ //# sourceMappingURL=queue-BjiGodqh.d.ts.map
@@ -1,7 +1,7 @@
1
- import { mt as Poll } from "./lifecycle-DXK880vG.js";
2
- import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, y as retryBackoff } from "./core-Iy9rIXOT.js";
3
- import { t as Judge } from "./dial-DLT7bTlA.js";
4
- import { i as JobSettle } from "./queue-CvBNNZZJ.js";
1
+ import { j as Poll } from "./logger-DhFgh48y.js";
2
+ import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, y as retryBackoff } from "./core-B1zbS4WY.js";
3
+ import { t as Judge } from "./dial-CSGKVlZe.js";
4
+ import { i as JobSettle } from "./queue-BjiGodqh.js";
5
5
  import { Extent, Quantity } from "@mark1russell7/quantity";
6
6
  import { Machine } from "@mark1russell7/algebra";
7
7
  //#region src/rabbitmq/connection.d.ts
package/build/rabbitmq.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { realClock } from "./clock.js";
2
- import { A as retrySchedule, B as zeroProblems, C as notSent, D as readyWait, F as timeProblems, G as immediate, H as NEVER, I as trackWithTimer, J as keepaliveSilent, K as keepaliveAnswered, L as wholeProblems, M as sendWithReissue, N as socketEnds, O as retryBackoff, P as stepChecks, R as withinBound, S as ms, U as WHAT, V as MANIFESTATIONS, W as firstDetector, X as unwatched, Y as kernelGiveUp, _ as inFlight, a as helloDial, b as message, c as ageProblems, d as clientProblems, f as clientRecorder, h as finiteMs, j as roundTripCheck, k as retryProblems, l as attachClient, m as dialCheck, n as closeTimer, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, w as operationTable, y as localStateCheck, z as wrapperTimerProblems } from "./machine-Dq2OlzCG.js";
2
+ import { A as retrySchedule, B as zeroProblems, C as notSent, D as readyWait, F as timeProblems, G as immediate, H as NEVER, I as trackWithTimer, J as keepaliveSilent, K as keepaliveAnswered, L as wholeProblems, M as sendWithReissue, N as socketEnds, O as retryBackoff, P as stepChecks, R as withinBound, S as ms, U as WHAT, V as MANIFESTATIONS, W as firstDetector, X as unwatched, Y as kernelGiveUp, _ as inFlight, a as helloDial, b as message, c as ageProblems, d as clientProblems, f as clientRecorder, h as finiteMs, j as roundTripCheck, k as retryProblems, l as attachClient, m as dialCheck, n as closeTimer, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, w as operationTable, y as localStateCheck, z as wrapperTimerProblems } from "./machine-DKWLZOqu.js";
3
3
  import { quantity } from "@mark1russell7/quantity";
4
4
  //#region src/rabbitmq/connection.ts
5
5
  /**
package/build/redis.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { Gt as Operation, bt as heartbeatDetection } from "./lifecycle-DXK880vG.js";
3
- import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, c as ClientSpec, d as Factory, g as SendOptions, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation, y as retryBackoff } from "./core-Iy9rIXOT.js";
2
+ import { L as heartbeatDetection, ct as Operation } from "./logger-DhFgh48y.js";
3
+ import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, c as ClientSpec, d as Factory, g as SendOptions, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation, y as retryBackoff } from "./core-B1zbS4WY.js";
4
4
  import { n as LimiterStore } from "./store-Cwuepb-z.js";
5
5
  import { Extent, Quantity } from "@mark1russell7/quantity";
6
6
  import { Machine } from "@mark1russell7/algebra";
package/build/redis.js CHANGED
@@ -2,7 +2,7 @@ import { realClock } from "./clock.js";
2
2
  import { heartbeat } from "./heartbeat.js";
3
3
  import { i as heartbeatDetection } from "./timing-DGRi3XCI.js";
4
4
  import { backoffDelay } from "./backoff.js";
5
- import { C as notSent, D as readyWait, F as timeProblems, G as immediate, J as keepaliveSilent, K as keepaliveAnswered, M as sendWithReissue, N as socketEnds, O as retryBackoff, P as stepChecks, R as withinBound, S as ms, U as WHAT, V as MANIFESTATIONS, W as firstDetector, X as unwatched, Y as kernelGiveUp, _ as inFlight, a as helloDial, b as message, d as clientProblems, f as clientRecorder, h as finiteMs, j as roundTripCheck, k as retryProblems, l as attachClient, m as dialCheck, n as closeTimer, q as keepaliveReset, r as transition, t as clientKnob, u as clientBounds, w as operationTable, x as missesProblems, y as localStateCheck } from "./machine-Dq2OlzCG.js";
5
+ import { C as notSent, D as readyWait, F as timeProblems, G as immediate, J as keepaliveSilent, K as keepaliveAnswered, M as sendWithReissue, N as socketEnds, O as retryBackoff, P as stepChecks, R as withinBound, S as ms, U as WHAT, V as MANIFESTATIONS, W as firstDetector, X as unwatched, Y as kernelGiveUp, _ as inFlight, a as helloDial, b as message, d as clientProblems, f as clientRecorder, h as finiteMs, j as roundTripCheck, k as retryProblems, l as attachClient, m as dialCheck, n as closeTimer, q as keepaliveReset, r as transition, t as clientKnob, u as clientBounds, w as operationTable, x as missesProblems, y as localStateCheck } from "./machine-DKWLZOqu.js";
6
6
  //#region src/redis/connection.ts
7
7
  /**
8
8
  * This factory makes an ioredis client. It loads ioredis only when a client connects, thus a
@@ -1,27 +1,5 @@
1
1
  import { realClock } from "./clock.js";
2
2
  import { backoffDelay, backoffProblems } from "./backoff.js";
3
- import { compare, convertible } from "@mark1russell7/quantity";
4
- //#region src/operation.ts
5
- /**
6
- * This function tells if an operation can go again `since` its first issue. An idempotent
7
- * operation can always go again, and other operations cannot. A keyed operation can go again
8
- * while the server keeps its key.
9
- */
10
- const mayReissue = (operation, since) => {
11
- const { idempotent } = operation;
12
- if (typeof idempotent === "boolean") return idempotent;
13
- return compare(since, idempotent.window) < 0;
14
- };
15
- /** This function gives the problems in the declaration of an operation that `describe()` refuses. */
16
- const operationProblems = (owner, name, operation) => {
17
- const { idempotent } = operation;
18
- if (typeof idempotent === "boolean") return [];
19
- const problems = [];
20
- if (idempotent.key.trim().length === 0) problems.push(`${owner}'s ${name} names no key`);
21
- if (!convertible(idempotent.window.unit, "s")) problems.push(`${owner}'s ${name} holds its key for a span that is not a time`);
22
- return problems;
23
- };
24
- //#endregion
25
3
  //#region src/retrier.ts
26
4
  /** This function makes a retrier with no check of its policy. A client of the package uses it with its own knobs. */
27
5
  const retrierOn = (clock, backoff, random, signal) => {
@@ -68,6 +46,6 @@ const retrier = (options) => {
68
46
  return retrierOn(clock, backoff, random, signal);
69
47
  };
70
48
  //#endregion
71
- export { operationProblems as i, retrierOn as n, mayReissue as r, retrier as t };
49
+ export { retrierOn as n, retrier as t };
72
50
 
73
- //# sourceMappingURL=retrier-CRda6z9G.js.map
51
+ //# sourceMappingURL=retrier-Bzkme_yM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retrier-Bzkme_yM.js","names":[],"sources":["../src/retrier.ts"],"sourcesContent":["import type { Backoff } from \"./backoff.ts\";\nimport { backoffDelay, backoffProblems } from \"./backoff.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a retrier: a backoff policy, the clock of its timers, and the signal that cancels it. */\nexport interface RetrierOptions extends Backoff {\n /** This clock starts each retry. The default is the real clock. A test gives a fake clock. */\n readonly clock?: Clock | undefined;\n /** This function gives a number in [0, 1) for the jitter of each delay. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /**\n * This signal cancels the retrier when it aborts, for example the `signal` of the lifecycle, which\n * aborts in the drain. After the abort, `schedule` starts nothing.\n */\n readonly signal?: AbortSignal | undefined;\n}\n\n/** A retrier starts a function again after the backoff of each try, on its clock. */\nexport interface Retrier {\n /** This count is the number of tries since the last reset. */\n readonly attempts: number;\n /** This flag tells if a retry waits for its timer. */\n readonly pending: boolean;\n /**\n * This method counts one more try, and starts `run` after the backoff delay of that try. It gives\n * the delay in milliseconds. A retry that waits stops, thus one retry at most waits. After the\n * abort of the signal, it starts nothing and gives null. The function catches its own errors.\n */\n schedule(run: () => void): number | null;\n /** This method sets the count of tries to 0, for example after a start that succeeded. A retry that waits stays. */\n reset(): void;\n /** This method stops the retry that waits. The count of tries stays. */\n cancel(): void;\n}\n\n/** This function makes a retrier with no check of its policy. A client of the package uses it with its own knobs. */\nexport const retrierOn = (clock: Clock, backoff: Backoff, random: () => number, signal?: AbortSignal): Retrier => {\n let tries = 0;\n let timer: Cancel | null = null;\n const cancel = (): void => {\n timer?.();\n timer = null;\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n return {\n get attempts() {\n return tries;\n },\n get pending() {\n return timer !== null;\n },\n schedule(run) {\n if (signal?.aborted === true) return null;\n tries += 1;\n const delay = Math.round(backoffDelay(backoff, tries, random));\n timer?.();\n timer = clock.after(delay, () => {\n timer = null;\n run();\n });\n return delay;\n },\n cancel,\n reset() {\n tries = 0;\n },\n };\n};\n\n/**\n * This function makes a retrier over `backoffDelay`. The first try waits `base`, and each try after\n * it waits `factor` times more, to the `cap`, with the jitter of the policy. It refuses a policy\n * with a problem of `backoffProblems`.\n */\nexport const retrier = (options: RetrierOptions): Retrier => {\n const { clock = realClock, random = Math.random, signal, ...backoff } = options;\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retrier has a bad backoff: ${problems.join(\"; \")}`);\n return retrierOn(clock, backoff, random, signal);\n};\n"],"mappings":";;;;AAqCA,MAAa,aAAa,OAAc,SAAkB,QAAsB,WAAkC;CAChH,IAAI,QAAQ;CACZ,IAAI,QAAuB;CAC3B,MAAM,eAAqB;EACzB,QAAQ;EACR,QAAQ;CACV;CACA,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;CACxD,OAAO;EACL,IAAI,WAAW;GACb,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO,UAAU;EACnB;EACA,SAAS,KAAK;GACZ,IAAI,QAAQ,YAAY,MAAM,OAAO;GACrC,SAAS;GACT,MAAM,QAAQ,KAAK,MAAM,aAAa,SAAS,OAAO,MAAM,CAAC;GAC7D,QAAQ;GACR,QAAQ,MAAM,MAAM,aAAa;IAC/B,QAAQ;IACR,IAAI;GACN,CAAC;GACD,OAAO;EACT;EACA;EACA,QAAQ;GACN,QAAQ;EACV;CACF;AACF;;;;;;AAOA,MAAa,WAAW,YAAqC;CAC3D,MAAM,EAAE,QAAQ,WAAW,SAAS,KAAK,QAAQ,QAAQ,GAAG,YAAY;CACxE,MAAM,WAAW,gBAAgB,OAAO;CACxC,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,kCAAkC,SAAS,KAAK,IAAI,GAAG;CAChG,OAAO,UAAU,OAAO,SAAS,QAAQ,MAAM;AACjD"}
@@ -1,6 +1,8 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { D as CheckFn, Dt as ExitSignal, H as Logger, It as UncaughtOrigin, K as Outcome, Nt as ProcessPort, Ot as ExitTrigger, R as LogEntry, V as LogLevel, d as TransportImpl, r as Lifecycle } from "./lifecycle-DXK880vG.js";
3
- import { n as ServiceBuilder } from "./builder-0OlfomVU.js";
2
+ import { $ as UncaughtOrigin, G as ExitTrigger, W as ExitSignal, X as ProcessPort, c as Logger, i as LogEntry, s as LogLevel } from "./logger-DhFgh48y.js";
3
+ import { D as CheckFn, F as Outcome, d as TransportImpl, r as Lifecycle } from "./lifecycle-Ks9Yd5CM.js";
4
+ import { n as ServiceBuilder } from "./builder-bXJqMe2p.js";
5
+ import { c as ProcessMark, d as StopSignal, i as CommandResult, n as CommandOptions, o as HostPorts, t as ChildHandle, u as SpawnRequest } from "./ports-CZLzYK5d.js";
4
6
  //#region src/fakes.d.ts
5
7
  /** A fake clock moves only when a test tells it to. */
6
8
  interface FakeClock extends Clock {
@@ -154,6 +156,85 @@ interface ConformanceOptions {
154
156
  */
155
157
  export declare const transportConformance: (make: SubjectFactory, options?: ConformanceOptions) => ContractCase[];
156
158
  //#endregion
159
+ //#region src/host/fakes.d.ts
160
+ /** A fake child is a child process of a fake host. A test ends it, or a stop ends it. */
161
+ interface FakeChild extends ChildHandle {
162
+ readonly request: SpawnRequest;
163
+ /** These are the messages that went on its IPC channel. */
164
+ readonly sent: readonly unknown[];
165
+ /** This flag tells if the child ended. */
166
+ readonly ended: boolean;
167
+ /** This method ends the child with a code, or with a signal and a null code. A second use does nothing. */
168
+ exit(code: number | null, signal?: string | null): void;
169
+ /** This method sends data on the output of the child. */
170
+ output(stream: "stdout" | "stderr", chunk: string | Uint8Array): void;
171
+ }
172
+ /** A recorded command is one command that went through the fake command port. */
173
+ interface RecordedCommand {
174
+ readonly file: string;
175
+ readonly args: readonly string[];
176
+ readonly options: CommandOptions | undefined;
177
+ }
178
+ /** A recorded signal is one signal that went through the fake process port. */
179
+ interface RecordedSignal {
180
+ readonly pid: number;
181
+ readonly signal: StopSignal;
182
+ readonly group: boolean;
183
+ }
184
+ /** These options go with a fake host. */
185
+ interface FakeHostOptions {
186
+ /** This text is the platform. The default is `linux`. */
187
+ readonly platform?: string | undefined;
188
+ readonly env?: Readonly<Record<string, string | undefined>> | undefined;
189
+ /** The default is `/home/test`. */
190
+ readonly homeDir?: string | undefined;
191
+ /** The default is `test`. */
192
+ readonly user?: string | undefined;
193
+ /** This record names the host process. The default is the ID 100, which started at the wall time 0. */
194
+ readonly self?: ProcessMark | undefined;
195
+ /** This time is the wall time at the clock time 0, in milliseconds after the epoch. The default is 1 000 000 000 000. */
196
+ readonly wallStart?: number | undefined;
197
+ /** These files are in the fake file system at the start. */
198
+ readonly files?: Readonly<Record<string, string | Uint8Array>> | undefined;
199
+ /**
200
+ * This function gives the result of a command. When it gives undefined, the fake answers. `taskkill`
201
+ * with `/F` ends the process and gives 0. `taskkill` without `/F` gives 1, or ends a polite child. Each other command gives 0.
202
+ */
203
+ readonly answer?: ((command: RecordedCommand) => CommandResult | undefined) | undefined;
204
+ readonly logger?: Logger | undefined;
205
+ }
206
+ /**
207
+ * A fake host is the host ports of a test, and the state behind them. It starts no process, writes no
208
+ * file and installs no task. Each effect is a record or a change of its state.
209
+ */
210
+ interface FakeHost {
211
+ readonly ports: HostPorts;
212
+ readonly clock: FakeClock;
213
+ /** These are the files of the fake file system. */
214
+ readonly files: Map<string, string | Uint8Array>;
215
+ readonly commands: RecordedCommand[];
216
+ readonly signals: RecordedSignal[];
217
+ readonly children: FakeChild[];
218
+ /** This table holds each live process: its ID, and its start time or null. */
219
+ readonly processes: Map<number, number | null>;
220
+ /** This map gives the HTTP status of each address. An address that it does not have gives no answer. */
221
+ readonly http: Map<string, number | null>;
222
+ /** This set holds each `host:port` that takes a TCP connection. */
223
+ readonly tcp: Set<string>;
224
+ /** True makes each child end with the code 0 at a staged stop: SIGTERM, SIGINT, an IPC message or `taskkill` without `/F`. */
225
+ polite: boolean;
226
+ /** This function makes a file operation fail. It gets the name of the operation and the path. */
227
+ failFiles: ((operation: string, path: string) => boolean) | null;
228
+ /** This function makes a spawn fail, thus the child has no ID and ends. */
229
+ failSpawn: ((request: SpawnRequest) => boolean) | null;
230
+ /** This method gives the text of a file, or null. */
231
+ text(path: string): string | null;
232
+ /** This method lets the promises that are ready continue, without a move of the clock. */
233
+ settle(): Promise<void>;
234
+ }
235
+ /** This function makes a fake host. Give its `ports` to the host functions in a test. */
236
+ export declare const fakeHost: (options?: FakeHostOptions) => FakeHost;
237
+ //#endregion
157
238
  //#region src/testing.d.ts
158
239
  /**
159
240
  * A behavior is what a scripted check does when the runtime starts it:
@@ -206,5 +287,5 @@ export interface QuietServer {
206
287
  */
207
288
  export declare const quietServer: () => Promise<QuietServer>;
208
289
  //#endregion
209
- export type { ConformanceOptions, ConformanceRecord, ContractCase, ContractOptions, FakeClock, FakeProcess, FakeProcessOptions, HeldWork, SubjectFactory, TransportSubject };
290
+ export type { ConformanceOptions, ConformanceRecord, ContractCase, ContractOptions, FakeChild, FakeClock, FakeHost, FakeHostOptions, FakeProcess, FakeProcessOptions, HeldWork, RecordedCommand, RecordedSignal, SubjectFactory, TransportSubject };
210
291
  //# sourceMappingURL=testing.d.ts.map
package/build/testing.js CHANGED
@@ -598,6 +598,231 @@ const transportConformance = (make, options = {}) => {
598
598
  ];
599
599
  };
600
600
  //#endregion
601
+ //#region src/host/fakes.ts
602
+ const encoder = new TextEncoder();
603
+ const decoder = new TextDecoder();
604
+ const bytesOf = (data) => typeof data === "string" ? encoder.encode(data) : data;
605
+ /** This function makes a fake host. Give its `ports` to the host functions in a test. */
606
+ const fakeHost = (options = {}) => {
607
+ const clock = fakeClock();
608
+ const wallStart = options.wallStart ?? 0xe8d4a51000;
609
+ const wall = () => wallStart + clock.now();
610
+ const self = options.self ?? {
611
+ pid: 100,
612
+ startedAt: wallStart
613
+ };
614
+ const files = new Map(Object.entries(options.files ?? {}));
615
+ const commands = [];
616
+ const signals = [];
617
+ const children = [];
618
+ const processes = /* @__PURE__ */ new Map([[self.pid, self.startedAt]]);
619
+ const live = /* @__PURE__ */ new Map();
620
+ let nextPid = 1e3;
621
+ const check = (operation, path) => {
622
+ if (host.failFiles?.(operation, path) === true) throw new Error(`the fake ${operation} of ${path} failed`);
623
+ };
624
+ const politeStop = (pid) => {
625
+ const child = live.get(pid);
626
+ if (host.polite && child !== void 0) queueMicrotask(() => child.exit(0));
627
+ };
628
+ const hardStop = (pid, signal) => {
629
+ const child = live.get(pid);
630
+ if (child !== void 0) queueMicrotask(() => child.exit(null, signal));
631
+ else processes.delete(pid);
632
+ };
633
+ const spawn = (request) => {
634
+ const pid = host.failSpawn?.(request) === true ? null : nextPid++;
635
+ const outputs = [];
636
+ const exits = [];
637
+ const sent = [];
638
+ let end = null;
639
+ const child = {
640
+ request,
641
+ pid,
642
+ ipc: request.ipc,
643
+ sent,
644
+ get ended() {
645
+ return end !== null;
646
+ },
647
+ onOutput(handler) {
648
+ outputs.push(handler);
649
+ },
650
+ onExit(handler) {
651
+ exits.push(handler);
652
+ if (end !== null) handler(end.code, end.signal);
653
+ },
654
+ send(message) {
655
+ if (!request.ipc || end !== null) return false;
656
+ sent.push(message);
657
+ if (pid !== null) politeStop(pid);
658
+ return true;
659
+ },
660
+ exit(code, signal = null) {
661
+ if (end !== null) return;
662
+ end = {
663
+ code,
664
+ signal
665
+ };
666
+ if (pid !== null) {
667
+ processes.delete(pid);
668
+ live.delete(pid);
669
+ }
670
+ for (const handler of exits) handler(code, signal);
671
+ },
672
+ output(stream, chunk) {
673
+ for (const handler of outputs) handler(stream, chunk);
674
+ }
675
+ };
676
+ children.push(child);
677
+ if (pid === null) queueMicrotask(() => child.exit(null));
678
+ else {
679
+ processes.set(pid, wall());
680
+ live.set(pid, child);
681
+ }
682
+ return child;
683
+ };
684
+ const signal = (pid, sig, group) => {
685
+ if (!processes.has(pid)) return false;
686
+ signals.push({
687
+ pid,
688
+ signal: sig,
689
+ group
690
+ });
691
+ if (sig === "SIGKILL") hardStop(pid, "SIGKILL");
692
+ else politeStop(pid);
693
+ return true;
694
+ };
695
+ const defaultAnswer = (command) => {
696
+ if (command.file !== "taskkill") return {
697
+ code: 0,
698
+ out: ""
699
+ };
700
+ const at = command.args.indexOf("/PID");
701
+ const pid = Number(command.args[at + 1]);
702
+ if (at < 0 || !processes.has(pid)) return {
703
+ code: 128,
704
+ out: `ERROR: The process "${command.args[at + 1] ?? ""}" not found.`
705
+ };
706
+ if (command.args.includes("/F")) {
707
+ hardStop(pid, null);
708
+ return {
709
+ code: 0,
710
+ out: `SUCCESS: The process with PID ${pid} has been terminated.`
711
+ };
712
+ }
713
+ if (host.polite && live.has(pid)) {
714
+ politeStop(pid);
715
+ return {
716
+ code: 0,
717
+ out: `SUCCESS: Sent termination signal to the process with PID ${pid}.`
718
+ };
719
+ }
720
+ return {
721
+ code: 1,
722
+ out: `ERROR: The process with PID ${pid} could not be terminated.`
723
+ };
724
+ };
725
+ const ports = {
726
+ platform: options.platform ?? "linux",
727
+ commands: { async run(file, args, commandOptions) {
728
+ const command = {
729
+ file,
730
+ args: [...args],
731
+ options: commandOptions
732
+ };
733
+ commands.push(command);
734
+ return options.answer?.(command) ?? defaultAnswer(command);
735
+ } },
736
+ files: {
737
+ async read(path) {
738
+ check("read", path);
739
+ const data = files.get(path);
740
+ return data === void 0 ? null : typeof data === "string" ? data : decoder.decode(data);
741
+ },
742
+ async write(path, data) {
743
+ check("write", path);
744
+ files.set(path, data);
745
+ },
746
+ async create(path, data) {
747
+ check("create", path);
748
+ if (files.has(path)) return false;
749
+ files.set(path, data);
750
+ return true;
751
+ },
752
+ async append(path, data) {
753
+ check("append", path);
754
+ const before = files.get(path);
755
+ if (before === void 0) files.set(path, data);
756
+ else if (typeof before === "string" && typeof data === "string") files.set(path, before + data);
757
+ else {
758
+ const head = bytesOf(before);
759
+ const tail = bytesOf(data);
760
+ const joined = new Uint8Array(head.length + tail.length);
761
+ joined.set(head, 0);
762
+ joined.set(tail, head.length);
763
+ files.set(path, joined);
764
+ }
765
+ },
766
+ async size(path) {
767
+ check("size", path);
768
+ const data = files.get(path);
769
+ return data === void 0 ? null : bytesOf(data).length;
770
+ },
771
+ async rename(from, to) {
772
+ check("rename", from);
773
+ const data = files.get(from);
774
+ if (data === void 0) throw new Error(`the fake file ${from} does not exist`);
775
+ files.delete(from);
776
+ files.set(to, data);
777
+ },
778
+ async remove(path) {
779
+ check("remove", path);
780
+ files.delete(path);
781
+ }
782
+ },
783
+ processes: {
784
+ alive: (pid) => processes.has(pid),
785
+ startOf: async (pid) => processes.get(pid) ?? null,
786
+ signal: (pid, sig) => signal(pid, sig, false),
787
+ signalGroup: (pid, sig) => ports.platform !== "win32" && live.has(pid) && signal(pid, sig, true),
788
+ spawn
789
+ },
790
+ net: {
791
+ httpStatus: async (url) => host.http.get(url) ?? null,
792
+ tcpConnect: async (hostName, port) => host.tcp.has(`${hostName}:${port}`)
793
+ },
794
+ clock,
795
+ wall,
796
+ self,
797
+ env: options.env ?? {},
798
+ homeDir: options.homeDir ?? "/home/test",
799
+ user: () => options.user ?? "test",
800
+ ...options.logger === void 0 ? {} : { logger: options.logger }
801
+ };
802
+ const host = {
803
+ ports,
804
+ clock,
805
+ files,
806
+ commands,
807
+ signals,
808
+ children,
809
+ processes,
810
+ http: /* @__PURE__ */ new Map(),
811
+ tcp: /* @__PURE__ */ new Set(),
812
+ polite: false,
813
+ failFiles: null,
814
+ failSpawn: null,
815
+ text(path) {
816
+ const data = files.get(path);
817
+ return data === void 0 ? null : typeof data === "string" ? data : decoder.decode(data);
818
+ },
819
+ async settle() {
820
+ for (let turn = 0; turn < 2e3; turn += 1) await Promise.resolve();
821
+ }
822
+ };
823
+ return host;
824
+ };
825
+ //#endregion
601
826
  //#region src/testing.ts
602
827
  /** This function makes a scripted check with a behavior at the start. */
603
828
  const scriptedCheck = (behavior = "ok") => {
@@ -687,6 +912,6 @@ const quietServer = async () => {
687
912
  };
688
913
  };
689
914
  //#endregion
690
- export { contractCases, detachedLifecycle, fakeClock, fakeProcess, quietServer, scriptedCheck, seeded, testLogger, transportConformance };
915
+ export { contractCases, detachedLifecycle, fakeClock, fakeHost, fakeProcess, quietServer, scriptedCheck, seeded, testLogger, transportConformance };
691
916
 
692
917
  //# sourceMappingURL=testing.js.map