@mark1russell7/service 0.6.1 → 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 (49) hide show
  1. package/README.md +114 -5
  2. package/build/{builder-BNAkpeTT.d.ts → builder-bXJqMe2p.d.ts} +3 -2
  3. package/build/{core-CWsGgr9J.d.ts → core-B1zbS4WY.d.ts} +4 -3
  4. package/build/{dial-JEJavY0U.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 +17 -3
  13. package/build/http.js +53 -10
  14. package/build/http.js.map +1 -1
  15. package/build/index.d.ts +44 -6
  16. package/build/index.js +78 -158
  17. package/build/index.js.map +1 -1
  18. package/build/lifecycle-Ks9Yd5CM.d.ts +387 -0
  19. package/build/{limiter-B0849Vhp.d.ts → limiter-BoZkXIxk.d.ts} +2 -2
  20. package/build/{limiter-pkBZUp-t.js → limiter-CmC4vCjk.js} +21 -13
  21. package/build/limiter-CmC4vCjk.js.map +1 -0
  22. package/build/limiter.d.ts +3 -3
  23. package/build/limiter.js +1 -1
  24. package/build/{lifecycle-CCDLvXLF.d.ts → logger-DhFgh48y.d.ts} +25 -367
  25. package/build/{machine-DZMb_QEU.js → machine-DKWLZOqu.js} +7 -19
  26. package/build/machine-DKWLZOqu.js.map +1 -0
  27. package/build/mongodb.d.ts +3 -3
  28. package/build/mongodb.js +1 -1
  29. package/build/pg.d.ts +2 -2
  30. package/build/pg.js +1 -1
  31. package/build/ports-CZLzYK5d.d.ts +125 -0
  32. package/build/process-DG_im2zc.js +171 -0
  33. package/build/process-DG_im2zc.js.map +1 -0
  34. package/build/{queue-eLs5IruM.d.ts → queue-BjiGodqh.d.ts} +3 -2
  35. package/build/rabbitmq.d.ts +4 -4
  36. package/build/rabbitmq.js +1 -1
  37. package/build/redis.d.ts +3 -3
  38. package/build/redis.js +1 -1
  39. package/build/retrier-Bzkme_yM.js +51 -0
  40. package/build/retrier-Bzkme_yM.js.map +1 -0
  41. package/build/{store-D5HLgBnW.d.ts → store-Cwuepb-z.d.ts} +14 -3
  42. package/build/testing.d.ts +86 -3
  43. package/build/testing.js +238 -2
  44. package/build/testing.js.map +1 -1
  45. package/build/websocket.d.ts +3 -3
  46. package/build/websocket.js +1 -1
  47. package/package.json +6 -2
  48. package/build/limiter-pkBZUp-t.js.map +0 -1
  49. package/build/machine-DZMb_QEU.js.map +0 -1
package/build/mongodb.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { realClock } from "./clock.js";
2
- import { B as zeroProblems, C as notSent, E as poolProblems, F as timeProblems, G as immediate, J as keepaliveSilent, K as keepaliveAnswered, L as wholeProblems, M as sendWithReissue, P as stepChecks, R as withinBound, S as ms, T as orZero, 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, l as attachClient, m as dialCheck, n as closeTimer, p as deadlineProblem, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, v as keepaliveOnProblems, w as operationTable, y as localStateCheck } from "./machine-DZMb_QEU.js";
2
+ import { B as zeroProblems, C as notSent, E as poolProblems, F as timeProblems, G as immediate, J as keepaliveSilent, K as keepaliveAnswered, L as wholeProblems, M as sendWithReissue, P as stepChecks, R as withinBound, S as ms, T as orZero, 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, l as attachClient, m as dialCheck, n as closeTimer, p as deadlineProblem, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, v as keepaliveOnProblems, w as operationTable, y as localStateCheck } from "./machine-DKWLZOqu.js";
3
3
  import { quantity } from "@mark1russell7/quantity";
4
4
  //#region src/mongodb/connection.ts
5
5
  /**
package/build/pg.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { Vt as Operation, ft as Poll } from "./lifecycle-CCDLvXLF.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, c as ClientSpec, d as Factory, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation } from "./core-CWsGgr9J.js";
1
+ import { ct as Operation, 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, c as ClientSpec, d as Factory, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation } from "./core-B1zbS4WY.js";
3
3
  import { Extent, Quantity } from "@mark1russell7/quantity";
4
4
  import { Machine } from "@mark1russell7/algebra";
5
5
  //#region src/pg/connection.d.ts
package/build/pg.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { realClock } from "./clock.js";
2
- import { B as zeroProblems, C as notSent, E as poolProblems, F as timeProblems, G as immediate, J as keepaliveSilent, K as keepaliveAnswered, L as wholeProblems, M as sendWithReissue, N as socketEnds, P as stepChecks, R as withinBound, S as ms, T as orZero, 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, l as attachClient, m as dialCheck, n as closeTimer, p as deadlineProblem, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, w as operationTable, y as localStateCheck } from "./machine-DZMb_QEU.js";
2
+ import { B as zeroProblems, C as notSent, E as poolProblems, F as timeProblems, G as immediate, J as keepaliveSilent, K as keepaliveAnswered, L as wholeProblems, M as sendWithReissue, N as socketEnds, P as stepChecks, R as withinBound, S as ms, T as orZero, 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, l as attachClient, m as dialCheck, n as closeTimer, p as deadlineProblem, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, w as operationTable, y as localStateCheck } from "./machine-DKWLZOqu.js";
3
3
  //#region src/pg/connection.ts
4
4
  /**
5
5
  * This factory makes a `pg.Pool`. It loads pg only when a client connects, thus a service that does
@@ -0,0 +1,125 @@
1
+ import { n as Clock } from "./clock-mVqhXD0b.js";
2
+ import { c as Logger } from "./logger-DhFgh48y.js";
3
+ //#region src/host/ports.d.ts
4
+ /** These options go with one command: the folder that it runs in, and the most time that it can take. */
5
+ interface CommandOptions {
6
+ readonly cwd?: string | undefined;
7
+ /** This time is the most that the command can take, in milliseconds. After it, the command stops, and its code is 124. */
8
+ readonly timeout?: number | undefined;
9
+ }
10
+ /** A command result is the exit code of a command and the text that it wrote to its output and its error output. */
11
+ interface CommandResult {
12
+ /** This code is the exit code. A program that is not found gives 127, and a command at its timeout gives 124. */
13
+ readonly code: number;
14
+ readonly out: string;
15
+ }
16
+ /**
17
+ * A command port starts a program with a list of arguments and gives its result. It does not use a
18
+ * shell, thus no argument needs a quote. The host uses it for `schtasks`, `systemctl` and `taskkill`.
19
+ */
20
+ interface CommandPort {
21
+ run(file: string, args: readonly string[], options?: CommandOptions): Promise<CommandResult>;
22
+ }
23
+ /** A file port is the part of a file system that the host uses. Each path is a full path. */
24
+ interface FilePort {
25
+ /** This method gives the text of a file in UTF-8, or null when the file does not exist. */
26
+ read(path: string): Promise<string | null>;
27
+ /** This method writes a file. It makes the folders of the path, and it replaces the file in one step. */
28
+ write(path: string, data: string | Uint8Array): Promise<void>;
29
+ /** This method makes a file only when no file has the path, and tells if it made it. It makes the folders of the path. */
30
+ create(path: string, data: string): Promise<boolean>;
31
+ /** This method adds data at the end of a file. It makes the file and its folders when they do not exist. */
32
+ append(path: string, data: string | Uint8Array): Promise<void>;
33
+ /** This method gives the size of a file in bytes, or null when the file does not exist. */
34
+ size(path: string): Promise<number | null>;
35
+ /** This method gives a file a new path. It replaces a file at the new path. */
36
+ rename(from: string, to: string): Promise<void>;
37
+ /** This method removes a file. A file that does not exist is not an error. */
38
+ remove(path: string): Promise<void>;
39
+ }
40
+ /** These are the signals that the host sends to a process. */
41
+ type StopSignal = "SIGINT" | "SIGTERM" | "SIGKILL";
42
+ /** A spawn request tells the program that a child process runs, with its arguments, its folder and its environment. */
43
+ interface SpawnRequest {
44
+ readonly program: string;
45
+ readonly args: readonly string[];
46
+ readonly cwd?: string | undefined;
47
+ readonly env: Readonly<Record<string, string>>;
48
+ /** True gives the child an IPC channel. Only a child that is a Node program can use it. */
49
+ readonly ipc: boolean;
50
+ }
51
+ /** A child handle is a child process that the host started. */
52
+ interface ChildHandle {
53
+ /** This number is the process ID, or null when the program did not start. */
54
+ readonly pid: number | null;
55
+ /** This flag tells if the child has an IPC channel. */
56
+ readonly ipc: boolean;
57
+ /** This method adds a handler for each part of the output and of the error output of the child. */
58
+ onOutput(handler: (stream: "stdout" | "stderr", chunk: string | Uint8Array) => void): void;
59
+ /**
60
+ * This method adds a handler for the end of the child. The handler gets the exit code, or null after
61
+ * a signal, and the signal. A program that did not start also ends, with a null code.
62
+ */
63
+ onExit(handler: (code: number | null, signal: string | null) => void): void;
64
+ /** This method sends a message on the IPC channel, and tells if it went. */
65
+ send(message: unknown): boolean;
66
+ }
67
+ /**
68
+ * A process port is the part of the processes of the system that the host uses. It finds if a
69
+ * process is alive, it gives its start time, it sends signals and it starts a child.
70
+ */
71
+ interface ProcessesPort {
72
+ /** This method tells if a process with this ID is alive. A process of a different user is alive too. */
73
+ alive(pid: number): boolean;
74
+ /** This method gives the start time of a process, in milliseconds after the epoch, or null when the system does not tell. */
75
+ startOf(pid: number): Promise<number | null>;
76
+ /** This method sends a signal to one process, and tells if the signal went. */
77
+ signal(pid: number, signal: StopSignal): boolean;
78
+ /** This method sends a signal to the process group whose leader is `pid`, and tells if the signal went. Windows has no process groups. */
79
+ signalGroup(pid: number, signal: StopSignal): boolean;
80
+ /** This method starts a child process. On Linux, the child leads a new process group. */
81
+ spawn(request: SpawnRequest): ChildHandle;
82
+ }
83
+ /** A net port does the network part of a readiness probe. */
84
+ interface NetPort {
85
+ /** This method sends a GET request, and gives the status of the answer, or null when no answer came in the timeout. */
86
+ httpStatus(url: string, timeout: number): Promise<number | null>;
87
+ /** This method tells if a TCP connection to the host and the port opens in the timeout, in milliseconds. */
88
+ tcpConnect(host: string, port: number, timeout: number): Promise<boolean>;
89
+ }
90
+ /** This record names a process: its ID and its start time, in milliseconds after the epoch. */
91
+ interface ProcessMark {
92
+ readonly pid: number;
93
+ readonly startedAt: number;
94
+ }
95
+ /**
96
+ * The host ports are each effect of the system that the host uses. A test gives fakes (`fakeHost` of
97
+ * `./testing`), thus a test installs no task and starts no process. `nodeHostPorts()` gives the ports of Node.
98
+ */
99
+ interface HostPorts {
100
+ /** This text is the platform, as `process.platform` gives it, for example `win32` or `linux`. */
101
+ readonly platform: string;
102
+ readonly commands: CommandPort;
103
+ readonly files: FilePort;
104
+ readonly processes: ProcessesPort;
105
+ readonly net: NetPort;
106
+ /** This clock gives the monotonic time and the timers. */
107
+ readonly clock: Clock;
108
+ /** This function gives the wall time, in milliseconds after the epoch. */
109
+ readonly wall: () => number;
110
+ /** This record names the process of the host itself. */
111
+ readonly self: ProcessMark;
112
+ /** These are the environment variables of the host. */
113
+ readonly env: Readonly<Record<string, string | undefined>>;
114
+ /** This text is the home folder of the user. */
115
+ readonly homeDir: string;
116
+ /** This function gives the user that a Windows task runs as, for example `HOST\name`. */
117
+ readonly user: () => string;
118
+ /** This logger gets the log entries of the host. Without it, the host writes no log. */
119
+ readonly logger?: Logger | undefined;
120
+ }
121
+ /** This function joins the parts of a path with the separator of the platform. */
122
+ declare const joinPath: (platform: string, ...parts: readonly string[]) => string;
123
+ //#endregion
124
+ export { FilePort as a, ProcessMark as c, StopSignal as d, joinPath as f, CommandResult as i, ProcessesPort as l, CommandOptions as n, HostPorts as o, CommandPort as r, NetPort as s, ChildHandle as t, SpawnRequest as u };
125
+ //# sourceMappingURL=ports-CZLzYK5d.d.ts.map
@@ -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 { ct as ServiceDescription, d as TransportImpl, r as Lifecycle } from "./lifecycle-CCDLvXLF.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-eLs5IruM.d.ts.map
151
+ //# sourceMappingURL=queue-BjiGodqh.d.ts.map
@@ -1,7 +1,7 @@
1
- import { ft as Poll } from "./lifecycle-CCDLvXLF.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-CWsGgr9J.js";
3
- import { t as Judge } from "./dial-JEJavY0U.js";
4
- import { i as JobSettle } from "./queue-eLs5IruM.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-DZMb_QEU.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,7 +1,7 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { Vt as Operation, vt as heartbeatDetection } from "./lifecycle-CCDLvXLF.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-CWsGgr9J.js";
4
- import { n as LimiterStore } from "./store-D5HLgBnW.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
+ import { n as LimiterStore } from "./store-Cwuepb-z.js";
5
5
  import { Extent, Quantity } from "@mark1russell7/quantity";
6
6
  import { Machine } from "@mark1russell7/algebra";
7
7
  //#region src/redis/connection.d.ts
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-DZMb_QEU.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
@@ -0,0 +1,51 @@
1
+ import { realClock } from "./clock.js";
2
+ import { backoffDelay, backoffProblems } from "./backoff.js";
3
+ //#region src/retrier.ts
4
+ /** This function makes a retrier with no check of its policy. A client of the package uses it with its own knobs. */
5
+ const retrierOn = (clock, backoff, random, signal) => {
6
+ let tries = 0;
7
+ let timer = null;
8
+ const cancel = () => {
9
+ timer?.();
10
+ timer = null;
11
+ };
12
+ signal?.addEventListener("abort", cancel, { once: true });
13
+ return {
14
+ get attempts() {
15
+ return tries;
16
+ },
17
+ get pending() {
18
+ return timer !== null;
19
+ },
20
+ schedule(run) {
21
+ if (signal?.aborted === true) return null;
22
+ tries += 1;
23
+ const delay = Math.round(backoffDelay(backoff, tries, random));
24
+ timer?.();
25
+ timer = clock.after(delay, () => {
26
+ timer = null;
27
+ run();
28
+ });
29
+ return delay;
30
+ },
31
+ cancel,
32
+ reset() {
33
+ tries = 0;
34
+ }
35
+ };
36
+ };
37
+ /**
38
+ * This function makes a retrier over `backoffDelay`. The first try waits `base`, and each try after
39
+ * it waits `factor` times more, to the `cap`, with the jitter of the policy. It refuses a policy
40
+ * with a problem of `backoffProblems`.
41
+ */
42
+ const retrier = (options) => {
43
+ const { clock = realClock, random = Math.random, signal, ...backoff } = options;
44
+ const problems = backoffProblems(backoff);
45
+ if (problems.length > 0) throw new Error(`the retrier has a bad backoff: ${problems.join("; ")}`);
46
+ return retrierOn(clock, backoff, random, signal);
47
+ };
48
+ //#endregion
49
+ export { retrierOn as n, retrier as t };
50
+
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"}
@@ -56,6 +56,15 @@ interface KeyedLimiter {
56
56
  * fails, it gives the decision of `onStoreFailure`, with the failure as text.
57
57
  */
58
58
  take(key: string): Promise<Decision>;
59
+ /**
60
+ * This method takes one unit for a key, and gives the decision at once, with no promise. Only a
61
+ * local store whose take gives its decision at once permits it, for example `memoryStore`. A shared store throws.
62
+ */
63
+ tryTakeSync?(key: string): Decision;
64
+ }
65
+ /** A local limiter is a keyed limiter on a memory store: its take can give the decision at once. */
66
+ interface LocalLimiter extends KeyedLimiter {
67
+ tryTakeSync(key: string): Decision;
59
68
  }
60
69
  /**
61
70
  * This function makes the runtime of a limiter from its spec and its store. It refuses a spec with a
@@ -65,8 +74,10 @@ interface KeyedLimiter {
65
74
  * permitted with `remaining` 0. With `closed`, it is refused with the cause `store`.
66
75
  * - The `retryAfter` of the cause `store` is the longest `retryAfter` of the policy.
67
76
  * - A failure of a local store rejects the take, because a local store has no `onStoreFailure`.
77
+ * - `tryTakeSync` gives the decision at once. A shared store throws, and so does a local store that gives a promise.
68
78
  */
69
- declare const keyedLimiter: (name: string, spec: LimiterSpec, store: LimiterStore) => KeyedLimiter;
79
+ declare function keyedLimiter(name: string, spec: LimiterSpec, store: MemoryStore): LocalLimiter;
80
+ declare function keyedLimiter(name: string, spec: LimiterSpec, store: LimiterStore): KeyedLimiter;
70
81
  //#endregion
71
- export { keyedLimiter as a, TakeRequest as i, LimiterStore as n, memoryStore as o, MemoryStore as r, KeyedLimiter as t };
72
- //# sourceMappingURL=store-D5HLgBnW.d.ts.map
82
+ export { TakeRequest as a, MemoryStore as i, LimiterStore as n, keyedLimiter as o, LocalLimiter as r, memoryStore as s, KeyedLimiter as t };
83
+ //# sourceMappingURL=store-Cwuepb-z.d.ts.map
@@ -1,6 +1,8 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { B as Logger, E as CheckFn, Et as ExitTrigger, L as LogEntry, Tt as ExitSignal, W as Outcome, d as TransportImpl, jt as ProcessPort, r as Lifecycle, z as LogLevel } from "./lifecycle-CCDLvXLF.js";
3
- import { n as ServiceBuilder } from "./builder-BNAkpeTT.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 {
@@ -24,6 +26,8 @@ interface FakeProcess extends ProcessPort {
24
26
  trigger(name: ExitTrigger): void;
25
27
  /** This method sends a message of the IPC channel to each handler of the trigger `ipc-message`. */
26
28
  message(value: unknown): void;
29
+ /** This method sends an error that no code caught to each handler of `onUncaught`. The default origin is `uncaughtException`. */
30
+ uncaught(error: unknown, origin?: UncaughtOrigin): void;
27
31
  /** These are the exit codes, in sequence. A correct runtime exits one time. */
28
32
  readonly exits: readonly number[];
29
33
  /** This count is the number of handlers that are registered. */
@@ -152,6 +156,85 @@ interface ConformanceOptions {
152
156
  */
153
157
  export declare const transportConformance: (make: SubjectFactory, options?: ConformanceOptions) => ContractCase[];
154
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
155
238
  //#region src/testing.d.ts
156
239
  /**
157
240
  * A behavior is what a scripted check does when the runtime starts it:
@@ -204,5 +287,5 @@ export interface QuietServer {
204
287
  */
205
288
  export declare const quietServer: () => Promise<QuietServer>;
206
289
  //#endregion
207
- 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 };
208
291
  //# sourceMappingURL=testing.d.ts.map