@mark1russell7/service 0.6.3 → 0.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -3
- package/build/grpc.js +1 -1
- package/build/host.js +1 -1
- package/build/http-client.js +1 -1
- package/build/index.d.ts +26 -1
- package/build/index.js +4 -582
- package/build/index.js.map +1 -1
- package/build/{machine-DKWLZOqu.js → machine-p4lENJ86.js} +2 -2
- package/build/{machine-DKWLZOqu.js.map → machine-p4lENJ86.js.map} +1 -1
- package/build/mongodb.js +1 -1
- package/build/pg.js +1 -1
- package/build/rabbitmq.js +1 -1
- package/build/redis.js +1 -1
- package/build/requests-BIq9Tr4P.js +586 -0
- package/build/requests-BIq9Tr4P.js.map +1 -0
- package/build/retrier-Nt6r4r6R.js +92 -0
- package/build/retrier-Nt6r4r6R.js.map +1 -0
- package/build/testing.d.ts +54 -3
- package/build/testing.js +259 -12
- package/build/testing.js.map +1 -1
- package/build/websocket.js +1 -1
- package/package.json +5 -4
- package/build/retrier-Bzkme_yM.js +0 -51
- package/build/retrier-Bzkme_yM.js.map +0 -1
|
@@ -0,0 +1,92 @@
|
|
|
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
|
+
/**
|
|
49
|
+
* This function gives the wait of a `Retry-After` header (RFC 9110) in milliseconds: a count of seconds,
|
|
50
|
+
* or an HTTP date after `now`. It gives null for a header with no valid value. A date before `now` gives 0.
|
|
51
|
+
*/
|
|
52
|
+
const retryAfterDelay = (header, now) => {
|
|
53
|
+
const text = header?.trim() ?? "";
|
|
54
|
+
if (text === "") return null;
|
|
55
|
+
if (/^\d+$/.test(text)) return Number(text) * 1e3;
|
|
56
|
+
const at = /[A-Za-z]/.test(text) ? Date.parse(text) : NaN;
|
|
57
|
+
return Number.isNaN(at) ? null : Math.max(0, at - now);
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* This function starts `run`, and starts it again after an error, to the count of `tries`. The delay
|
|
61
|
+
* before try n + 1 is `delayOf(error, n)`, else the `backoffDelay` of try n, on the clock. The call gives
|
|
62
|
+
* the value of the first try that succeeds. After the last try, an error that is not retryable, or the
|
|
63
|
+
* abort of the signal, it throws the last error. It refuses a policy with a problem of `backoffProblems`.
|
|
64
|
+
*/
|
|
65
|
+
const retry = async (run, options) => {
|
|
66
|
+
const { tries, retryable = () => true, delayOf, clock = realClock, random = Math.random, signal, ...backoff } = options;
|
|
67
|
+
if (!Number.isInteger(tries) || tries < 1) throw new Error(`retry needs a whole number of tries of 1 or more, not ${tries}`);
|
|
68
|
+
const problems = backoffProblems(backoff);
|
|
69
|
+
if (problems.length > 0) throw new Error(`the retry has a bad backoff: ${problems.join("; ")}`);
|
|
70
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
71
|
+
return await run(attempt);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (attempt >= tries || signal?.aborted === true || !retryable(error)) throw error;
|
|
74
|
+
const own = delayOf?.(error, attempt);
|
|
75
|
+
const delay = Math.round(typeof own === "number" && Number.isFinite(own) && own >= 0 ? own : backoffDelay(backoff, attempt, random));
|
|
76
|
+
await new Promise((resume, stop) => {
|
|
77
|
+
const abort = () => {
|
|
78
|
+
cancel();
|
|
79
|
+
stop(error);
|
|
80
|
+
};
|
|
81
|
+
const cancel = clock.after(delay, () => {
|
|
82
|
+
signal?.removeEventListener("abort", abort);
|
|
83
|
+
resume();
|
|
84
|
+
});
|
|
85
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
//#endregion
|
|
90
|
+
export { retryAfterDelay as i, retrierOn as n, retry as r, retrier as t };
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=retrier-Nt6r4r6R.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retrier-Nt6r4r6R.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\n/** These options make one call with retries: the most tries, the errors to retry, and the policy of a retrier. */\nexport interface RetryOptions extends RetrierOptions {\n /** This number is the most tries of the call, the first try included. It is 1 or more. */\n readonly tries: number;\n /** This function tells if a try starts again after this error. The default retries each error. */\n readonly retryable?: ((error: unknown) => boolean) | undefined;\n /**\n * This function gives the delay in milliseconds before the next try, in place of the backoff. An example\n * is the `Retry-After` header of an HTTP 429. Null, undefined, NaN, an infinite or a negative number keeps\n * the backoff delay. The retry puts no cap on this delay, so the caller caps it, for example at 60 s.\n */\n readonly delayOf?: ((error: unknown, attempt: number) => number | null | undefined) | undefined;\n}\n\n/**\n * This function gives the wait of a `Retry-After` header (RFC 9110) in milliseconds: a count of seconds,\n * or an HTTP date after `now`. It gives null for a header with no valid value. A date before `now` gives 0.\n */\nexport const retryAfterDelay = (header: string | null | undefined, now: number): number | null => {\n const text = header?.trim() ?? \"\";\n if (text === \"\") return null;\n if (/^\\d+$/.test(text)) return Number(text) * 1000;\n // An HTTP date has the name of its day and month. Without a letter, Date.parse reads \"-3\" as a year.\n const at = /[A-Za-z]/.test(text) ? Date.parse(text) : Number.NaN;\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n};\n\n/**\n * This function starts `run`, and starts it again after an error, to the count of `tries`. The delay\n * before try n + 1 is `delayOf(error, n)`, else the `backoffDelay` of try n, on the clock. The call gives\n * the value of the first try that succeeds. After the last try, an error that is not retryable, or the\n * abort of the signal, it throws the last error. It refuses a policy with a problem of `backoffProblems`.\n */\nexport const retry = async <T>(run: (attempt: number) => Promise<T>, options: RetryOptions): Promise<T> => {\n const { tries, retryable = () => true, delayOf, clock = realClock, random = Math.random, signal, ...backoff } = options;\n if (!Number.isInteger(tries) || tries < 1) throw new Error(`retry needs a whole number of tries of 1 or more, not ${tries}`);\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retry has a bad backoff: ${problems.join(\"; \")}`);\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await run(attempt);\n } catch (error) {\n if (attempt >= tries || signal?.aborted === true || !retryable(error)) throw error;\n const own = delayOf?.(error, attempt);\n // A bad delay (NaN, an infinite or a negative number) gets the backoff, so that it cannot start the tries at once.\n const valid = typeof own === \"number\" && Number.isFinite(own) && own >= 0;\n const delay = Math.round(valid ? own : backoffDelay(backoff, attempt, random));\n await new Promise<void>((resume, stop) => {\n const abort = (): void => {\n cancel();\n stop(error);\n };\n const cancel = clock.after(delay, () => {\n signal?.removeEventListener(\"abort\", abort);\n resume();\n });\n signal?.addEventListener(\"abort\", abort, { once: true });\n });\n }\n }\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;;;;;AAoBA,MAAa,mBAAmB,QAAmC,QAA+B;CAChG,MAAM,OAAO,QAAQ,KAAK,KAAK;CAC/B,IAAI,SAAS,IAAI,OAAO;CACxB,IAAI,QAAQ,KAAK,IAAI,GAAG,OAAO,OAAO,IAAI,IAAI;CAE9C,MAAM,KAAK,WAAW,KAAK,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI;CACtD,OAAO,OAAO,MAAM,EAAE,IAAI,OAAO,KAAK,IAAI,GAAG,KAAK,GAAG;AACvD;;;;;;;AAQA,MAAa,QAAQ,OAAU,KAAsC,YAAsC;CACzG,MAAM,EAAE,OAAO,kBAAkB,MAAM,SAAS,QAAQ,WAAW,SAAS,KAAK,QAAQ,QAAQ,GAAG,YAAY;CAChH,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,MAAM,IAAI,MAAM,yDAAyD,OAAO;CAC3H,MAAM,WAAW,gBAAgB,OAAO;CACxC,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,gCAAgC,SAAS,KAAK,IAAI,GAAG;CAC9F,KAAK,IAAI,UAAU,IAAK,WAAW,GACjC,IAAI;EACF,OAAO,MAAM,IAAI,OAAO;CAC1B,SAAS,OAAO;EACd,IAAI,WAAW,SAAS,QAAQ,YAAY,QAAQ,CAAC,UAAU,KAAK,GAAG,MAAM;EAC7E,MAAM,MAAM,UAAU,OAAO,OAAO;EAGpC,MAAM,QAAQ,KAAK,MADL,OAAO,QAAQ,YAAY,OAAO,SAAS,GAAG,KAAK,OAAO,IACvC,MAAM,aAAa,SAAS,SAAS,MAAM,CAAC;EAC7E,MAAM,IAAI,SAAe,QAAQ,SAAS;GACxC,MAAM,cAAoB;IACxB,OAAO;IACP,KAAK,KAAK;GACZ;GACA,MAAM,SAAS,MAAM,MAAM,aAAa;IACtC,QAAQ,oBAAoB,SAAS,KAAK;IAC1C,OAAO;GACT,CAAC;GACD,QAAQ,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;EACzD,CAAC;CACH;AAEJ"}
|
package/build/testing.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as Clock } from "./clock-mVqhXD0b.js";
|
|
2
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";
|
|
3
|
+
import { D as CheckFn, F as Outcome, _ as RequestFn, d as TransportImpl, h as RequestEnd, r as Lifecycle } from "./lifecycle-Ks9Yd5CM.js";
|
|
4
4
|
import { n as ServiceBuilder } from "./builder-bXJqMe2p.js";
|
|
5
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";
|
|
6
6
|
//#region src/fakes.d.ts
|
|
@@ -52,7 +52,10 @@ interface FakeProcessOptions {
|
|
|
52
52
|
}
|
|
53
53
|
/** This function makes a fake process. */
|
|
54
54
|
export declare const fakeProcess: (options?: FakeProcessOptions) => FakeProcess;
|
|
55
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is
|
|
57
|
+
* `mulberry32` of @mark1russell7/rigor-generators.
|
|
58
|
+
*/
|
|
56
59
|
export declare const seeded: (seed: number) => (() => number);
|
|
57
60
|
//#endregion
|
|
58
61
|
//#region src/contract.d.ts
|
|
@@ -104,9 +107,42 @@ interface TransportSubject {
|
|
|
104
107
|
offer(): Promise<boolean>;
|
|
105
108
|
/** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */
|
|
106
109
|
hold(): Promise<HeldWork>;
|
|
110
|
+
/**
|
|
111
|
+
* This method sends one call through the transport, for the stream cases (option `streams`). The
|
|
112
|
+
* handler of the call gives `call.work` to `life.request(call.controller, call.route, ...)` of the
|
|
113
|
+
* lifecycle of the start, and writes its stream to the caller. It gives what the caller sees.
|
|
114
|
+
*/
|
|
115
|
+
call?(call: StreamCall): CallerView | Promise<CallerView>;
|
|
107
116
|
/** This method frees what the subject holds outside the transport: its clients and their sockets. */
|
|
108
117
|
dispose?(): Promise<void> | void;
|
|
109
118
|
}
|
|
119
|
+
/** A stream call is one request of the stream cases. The kit gives its work, and the subject sends it. */
|
|
120
|
+
interface StreamCall {
|
|
121
|
+
/** This name is the controller of the request in the lifecycle of the kit. */
|
|
122
|
+
readonly controller: string;
|
|
123
|
+
/** This name is the route of the request in the lifecycle of the kit. */
|
|
124
|
+
readonly route: string;
|
|
125
|
+
/** This function is the work of the request: one value, or a stream of values. */
|
|
126
|
+
readonly work: RequestFn<unknown>;
|
|
127
|
+
/** True tells that the answer is a stream of items. False tells that the answer is unary: one status and one value. */
|
|
128
|
+
readonly stream: boolean;
|
|
129
|
+
}
|
|
130
|
+
/** A seen end is the end of a call, as its caller read it. */
|
|
131
|
+
interface SeenEnd {
|
|
132
|
+
readonly kind: RequestEnd["kind"];
|
|
133
|
+
/**
|
|
134
|
+
* True tells that the end came in the body of the answer, after its status, for example as the
|
|
135
|
+
* last line of a stream. False tells that the end came as the status of the answer.
|
|
136
|
+
*/
|
|
137
|
+
readonly inBand: boolean;
|
|
138
|
+
}
|
|
139
|
+
/** A caller view is what the caller of a call has read so far. The kit reads it again until it changes. */
|
|
140
|
+
interface CallerView {
|
|
141
|
+
/** These values are the items that the caller read, in their sequence. */
|
|
142
|
+
readonly items: readonly unknown[];
|
|
143
|
+
/** This end is the end that the caller read, or null while the call is open. */
|
|
144
|
+
readonly end: SeenEnd | null;
|
|
145
|
+
}
|
|
110
146
|
/**
|
|
111
147
|
* This function gives a detached lifecycle: a lifecycle with no service, for the start of a
|
|
112
148
|
* transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request
|
|
@@ -140,6 +176,11 @@ interface ConformanceOptions {
|
|
|
140
176
|
readonly cooperative?: boolean | undefined;
|
|
141
177
|
/** This count is the number of works that the count case holds. The default is 3. */
|
|
142
178
|
readonly holds?: number | undefined;
|
|
179
|
+
/**
|
|
180
|
+
* True adds the stream cases (S6 D4). Then the subject gives `call`, and the kit gives the
|
|
181
|
+
* transport a lifecycle with request tracking. The default is false.
|
|
182
|
+
*/
|
|
183
|
+
readonly streams?: boolean | undefined;
|
|
143
184
|
/** This function receives each measurement, for the raw records of a run. */
|
|
144
185
|
readonly record?: ((record: ConformanceRecord) => void) | undefined;
|
|
145
186
|
}
|
|
@@ -153,6 +194,16 @@ interface ConformanceOptions {
|
|
|
153
194
|
* past it. It gives the cooperative abort to the work, and it does not throw.
|
|
154
195
|
* - `close` ends the work in flight in its bound, and a second close has no effect.
|
|
155
196
|
* - The stages in their sequence, as the lifecycle does them.
|
|
197
|
+
*
|
|
198
|
+
* The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a
|
|
199
|
+
* unary call is a stream of one item. The kit gives the transport a lifecycle with request
|
|
200
|
+
* tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.
|
|
201
|
+
* - A unary call gives one value, and its end comes as the status of the answer.
|
|
202
|
+
* - A stream stays in flight until its end, not until its first item.
|
|
203
|
+
* - A failure after the first item ends the stream with an error line in the body, not a status.
|
|
204
|
+
* A failure before the first item gets a status.
|
|
205
|
+
* - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.
|
|
206
|
+
* - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.
|
|
156
207
|
*/
|
|
157
208
|
export declare const transportConformance: (make: SubjectFactory, options?: ConformanceOptions) => ContractCase[];
|
|
158
209
|
//#endregion
|
|
@@ -287,5 +338,5 @@ export interface QuietServer {
|
|
|
287
338
|
*/
|
|
288
339
|
export declare const quietServer: () => Promise<QuietServer>;
|
|
289
340
|
//#endregion
|
|
290
|
-
export type { ConformanceOptions, ConformanceRecord, ContractCase, ContractOptions, FakeChild, FakeClock, FakeHost, FakeHostOptions, FakeProcess, FakeProcessOptions, HeldWork, RecordedCommand, RecordedSignal, SubjectFactory, TransportSubject };
|
|
341
|
+
export type { CallerView, ConformanceOptions, ConformanceRecord, ContractCase, ContractOptions, FakeChild, FakeClock, FakeHost, FakeHostOptions, FakeProcess, FakeProcessOptions, HeldWork, RecordedCommand, RecordedSignal, SeenEnd, StreamCall, SubjectFactory, TransportSubject };
|
|
291
342
|
//# sourceMappingURL=testing.d.ts.map
|
package/build/testing.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { realClock } from "./clock.js";
|
|
2
2
|
import { a as recoverSpan, r as failSpan } from "./timing-DGRi3XCI.js";
|
|
3
|
+
import { s as ownStream } from "./knobs-D2ClI68I.js";
|
|
4
|
+
import { t as tracker } from "./requests-BIq9Tr4P.js";
|
|
3
5
|
import { valueIn } from "@mark1russell7/quantity";
|
|
4
6
|
import { createServer } from "node:net";
|
|
7
|
+
import { mulberry32 } from "@mark1russell7/rigor-generators";
|
|
8
|
+
import "node:events";
|
|
5
9
|
//#region src/fakes.ts
|
|
6
10
|
/** This function lets the promises that are ready continue, before the clock moves again. */
|
|
7
11
|
const settle = async () => {
|
|
@@ -136,17 +140,11 @@ const fakeProcess = (options = {}) => {
|
|
|
136
140
|
}
|
|
137
141
|
};
|
|
138
142
|
};
|
|
139
|
-
/**
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
let t = state;
|
|
145
|
-
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
146
|
-
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
147
|
-
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
148
|
-
};
|
|
149
|
-
};
|
|
143
|
+
/**
|
|
144
|
+
* This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is
|
|
145
|
+
* `mulberry32` of @mark1russell7/rigor-generators.
|
|
146
|
+
*/
|
|
147
|
+
const seeded = (seed) => mulberry32(seed);
|
|
150
148
|
//#endregion
|
|
151
149
|
//#region src/contract.ts
|
|
152
150
|
const ms = (amount) => valueIn(amount, "ms");
|
|
@@ -327,6 +325,64 @@ const contractCases = (declare, options = {}) => {
|
|
|
327
325
|
return cases;
|
|
328
326
|
};
|
|
329
327
|
//#endregion
|
|
328
|
+
//#region src/http/fake-server.ts
|
|
329
|
+
/** This function makes a pushed source, a stream of a work for the tests of a stream. */
|
|
330
|
+
const pushedSource = () => {
|
|
331
|
+
const queue = [];
|
|
332
|
+
let wake = null;
|
|
333
|
+
let failure = null;
|
|
334
|
+
let returned = false;
|
|
335
|
+
const poke = () => {
|
|
336
|
+
wake?.();
|
|
337
|
+
wake = null;
|
|
338
|
+
};
|
|
339
|
+
return {
|
|
340
|
+
iterable: { [Symbol.asyncIterator]: () => ({
|
|
341
|
+
async next() {
|
|
342
|
+
for (;;) {
|
|
343
|
+
if (failure !== null) throw failure;
|
|
344
|
+
if (returned) return {
|
|
345
|
+
value: void 0,
|
|
346
|
+
done: true
|
|
347
|
+
};
|
|
348
|
+
const step = queue.shift();
|
|
349
|
+
if (step !== void 0) return step;
|
|
350
|
+
await new Promise((resolve) => wake = resolve);
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
async return() {
|
|
354
|
+
returned = true;
|
|
355
|
+
poke();
|
|
356
|
+
return {
|
|
357
|
+
value: void 0,
|
|
358
|
+
done: true
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
}) },
|
|
362
|
+
push: (value) => {
|
|
363
|
+
queue.push({
|
|
364
|
+
value,
|
|
365
|
+
done: false
|
|
366
|
+
});
|
|
367
|
+
poke();
|
|
368
|
+
},
|
|
369
|
+
finish: () => {
|
|
370
|
+
queue.push({
|
|
371
|
+
value: void 0,
|
|
372
|
+
done: true
|
|
373
|
+
});
|
|
374
|
+
poke();
|
|
375
|
+
},
|
|
376
|
+
fail: (error) => {
|
|
377
|
+
failure = error;
|
|
378
|
+
poke();
|
|
379
|
+
},
|
|
380
|
+
get returned() {
|
|
381
|
+
return returned;
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
};
|
|
385
|
+
//#endregion
|
|
330
386
|
//#region src/conformance.ts
|
|
331
387
|
/**
|
|
332
388
|
* This function gives a detached lifecycle: a lifecycle with no service, for the start of a
|
|
@@ -359,6 +415,32 @@ const detachedLifecycle = () => {
|
|
|
359
415
|
keepAlive: () => true
|
|
360
416
|
};
|
|
361
417
|
};
|
|
418
|
+
/** These names are the controller and the route of each call of the stream cases. */
|
|
419
|
+
const CALLS = {
|
|
420
|
+
controller: "conformance",
|
|
421
|
+
route: "call"
|
|
422
|
+
};
|
|
423
|
+
/**
|
|
424
|
+
* This function gives a lifecycle with request tracking for the stream cases, and its tracker. The
|
|
425
|
+
* kit uses the tracker for the stages of the shutdown, as the lifecycle of a service does. Its
|
|
426
|
+
* requests are not idempotent, and it admits each request until the stop of its intake.
|
|
427
|
+
*/
|
|
428
|
+
const trackedLifecycle = (clock) => {
|
|
429
|
+
const requests = tracker([{
|
|
430
|
+
name: CALLS.controller,
|
|
431
|
+
requires: [],
|
|
432
|
+
routes: { [CALLS.route]: { idempotent: false } }
|
|
433
|
+
}], clock, () => null);
|
|
434
|
+
const life = {
|
|
435
|
+
...detachedLifecycle(),
|
|
436
|
+
request: (controller, route, work, options) => ownStream(requests.request(controller, route, work, options), life),
|
|
437
|
+
inFlight: (controller) => requests.inFlight(controller)
|
|
438
|
+
};
|
|
439
|
+
return {
|
|
440
|
+
life,
|
|
441
|
+
requests
|
|
442
|
+
};
|
|
443
|
+
};
|
|
362
444
|
const realNow = () => performance.now();
|
|
363
445
|
const turn = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
364
446
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -408,6 +490,16 @@ const track = (promise) => {
|
|
|
408
490
|
* past it. It gives the cooperative abort to the work, and it does not throw.
|
|
409
491
|
* - `close` ends the work in flight in its bound, and a second close has no effect.
|
|
410
492
|
* - The stages in their sequence, as the lifecycle does them.
|
|
493
|
+
*
|
|
494
|
+
* The option `streams` adds the cases of the streams (S6 D4). Each request is a stream, and a
|
|
495
|
+
* unary call is a stream of one item. The kit gives the transport a lifecycle with request
|
|
496
|
+
* tracking. It also does the stages of the shutdown on the tracker, as the lifecycle does them.
|
|
497
|
+
* - A unary call gives one value, and its end comes as the status of the answer.
|
|
498
|
+
* - A stream stays in flight until its end, not until its first item.
|
|
499
|
+
* - A failure after the first item ends the stream with an error line in the body, not a status.
|
|
500
|
+
* A failure before the first item gets a status.
|
|
501
|
+
* - `drain` waits for an open stream. The cooperative abort ends the stream, and its caller gets the end.
|
|
502
|
+
* - At the deadline of the drain, the cut ends an open stream, and its caller gets the end.
|
|
411
503
|
*/
|
|
412
504
|
const transportConformance = (make, options = {}) => {
|
|
413
505
|
const name = options.name ?? "transport";
|
|
@@ -463,7 +555,7 @@ const transportConformance = (make, options = {}) => {
|
|
|
463
555
|
check(inBound, `close did not end in its bound of ${closeBound} ms`);
|
|
464
556
|
check(!closed.failed, `close threw: ${String(closed.error)}`);
|
|
465
557
|
};
|
|
466
|
-
|
|
558
|
+
const cases = [
|
|
467
559
|
each("nothing is in flight after the start, and it takes new work", async (subject) => {
|
|
468
560
|
check(subject.impl.inFlight() === 0, `inFlight() gives ${subject.impl.inFlight()} after the start, not 0`);
|
|
469
561
|
check(await subject.offer(), "the transport refused new work after its start");
|
|
@@ -596,6 +688,161 @@ const transportConformance = (make, options = {}) => {
|
|
|
596
688
|
await count(subject, 0, "close left work in flight");
|
|
597
689
|
})
|
|
598
690
|
];
|
|
691
|
+
if (!(options.streams ?? false)) return cases;
|
|
692
|
+
const eachStream = (title, body) => ({
|
|
693
|
+
name: `${name}: ${title}`,
|
|
694
|
+
async run() {
|
|
695
|
+
const time = timeOf();
|
|
696
|
+
const subject = await make(time.clock);
|
|
697
|
+
const { life, requests } = trackedLifecycle(time.clock);
|
|
698
|
+
try {
|
|
699
|
+
await subject.impl.start(new AbortController().signal, life);
|
|
700
|
+
check(subject.call !== void 0, "the option streams needs a subject that gives call()");
|
|
701
|
+
await body(subject, time, requests);
|
|
702
|
+
} finally {
|
|
703
|
+
requests.stopIntake();
|
|
704
|
+
requests.cooperativeAbort();
|
|
705
|
+
try {
|
|
706
|
+
await subject.impl.close();
|
|
707
|
+
} finally {
|
|
708
|
+
await subject.dispose?.();
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
});
|
|
713
|
+
const call = (subject, given) => Promise.resolve(subject.call(given));
|
|
714
|
+
const openStream = async (subject) => {
|
|
715
|
+
const source = pushedSource();
|
|
716
|
+
let started = false;
|
|
717
|
+
let signal = null;
|
|
718
|
+
const view = await call(subject, {
|
|
719
|
+
...CALLS,
|
|
720
|
+
stream: true,
|
|
721
|
+
work: (given) => {
|
|
722
|
+
started = true;
|
|
723
|
+
signal = given;
|
|
724
|
+
return source.iterable;
|
|
725
|
+
}
|
|
726
|
+
});
|
|
727
|
+
check(await within(slack, () => started), "the work of a stream call did not start");
|
|
728
|
+
return {
|
|
729
|
+
view,
|
|
730
|
+
push: (value) => source.push(value),
|
|
731
|
+
finish: () => source.finish(),
|
|
732
|
+
fail: (error) => source.fail(error),
|
|
733
|
+
get aborted() {
|
|
734
|
+
return signal?.aborted === true;
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
};
|
|
738
|
+
const pushes = async (fed, value, what) => {
|
|
739
|
+
const before = fed.view.items.length;
|
|
740
|
+
fed.push(value);
|
|
741
|
+
check(await within(slack, () => fed.view.items.length > before), `${what}: the caller did not get the item ${value}`);
|
|
742
|
+
};
|
|
743
|
+
const ends = async (view, kind, inBand, what) => {
|
|
744
|
+
check(await within(slack, () => view.end !== null), `${what}: the caller got no end`);
|
|
745
|
+
const end = view.end;
|
|
746
|
+
const where = (body) => body ? "in the body" : "as a status";
|
|
747
|
+
check(end.kind === kind && end.inBand === inBand, `${what}: the caller got the end ${end.kind} ${where(end.inBand)}, not ${kind} ${where(inBand)}`);
|
|
748
|
+
};
|
|
749
|
+
/** This function stops the intake of the tracker and of the transport, as the stage `stop intake` does. */
|
|
750
|
+
const stopBoth = async (subject, requests) => {
|
|
751
|
+
requests.stopIntake();
|
|
752
|
+
await subject.impl.stopIntake();
|
|
753
|
+
};
|
|
754
|
+
/**
|
|
755
|
+
* This function starts the drain of the transport and of the tracker, as the stage `drain` does.
|
|
756
|
+
* The abort of `signal` is also the cooperative abort of the tracker. It tracks the drain of the transport.
|
|
757
|
+
*/
|
|
758
|
+
const drainBoth = (subject, requests, deadline, signal) => {
|
|
759
|
+
if (signal.aborted) requests.cooperativeAbort();
|
|
760
|
+
else signal.addEventListener("abort", () => requests.cooperativeAbort(), { once: true });
|
|
761
|
+
requests.drain(deadline);
|
|
762
|
+
return track(attempt(() => subject.impl.drain(deadline, signal)));
|
|
763
|
+
};
|
|
764
|
+
const failure = () => /* @__PURE__ */ new Error("the failure of the conformance kit");
|
|
765
|
+
const streamCases = [
|
|
766
|
+
eachStream("a unary call is a stream of one item: one value, and its end as the status", async (subject) => {
|
|
767
|
+
let started = false;
|
|
768
|
+
let give = () => {};
|
|
769
|
+
const view = await call(subject, {
|
|
770
|
+
...CALLS,
|
|
771
|
+
stream: false,
|
|
772
|
+
work: () => {
|
|
773
|
+
started = true;
|
|
774
|
+
return new Promise((resolve) => {
|
|
775
|
+
give = resolve;
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
});
|
|
779
|
+
check(await within(slack, () => started), "the work of a unary call did not start");
|
|
780
|
+
await count(subject, 1, "a unary call is in flight");
|
|
781
|
+
give(7);
|
|
782
|
+
await ends(view, "done", false, "a unary call");
|
|
783
|
+
check(view.items.length === 1 && view.items[0] === 7, `a unary call gave the items ${JSON.stringify(view.items)}, not [7]`);
|
|
784
|
+
await count(subject, 0, "a unary call ended");
|
|
785
|
+
}),
|
|
786
|
+
eachStream("a stream stays in flight until its end, not until its first item", async (subject) => {
|
|
787
|
+
const fed = await openStream(subject);
|
|
788
|
+
await count(subject, 1, "a stream is open");
|
|
789
|
+
for (const value of [1, 2]) {
|
|
790
|
+
await pushes(fed, value, "an open stream");
|
|
791
|
+
await count(subject, 1, `a stream is open after its item ${value}`);
|
|
792
|
+
}
|
|
793
|
+
check(fed.view.end === null, "the caller got an end before the end of the stream");
|
|
794
|
+
fed.finish();
|
|
795
|
+
await ends(fed.view, "done", true, "a stream that ended");
|
|
796
|
+
check(JSON.stringify(fed.view.items) === "[1,2]", `a stream gave the items ${JSON.stringify(fed.view.items)}, not [1,2]`);
|
|
797
|
+
await count(subject, 0, "a stream ended");
|
|
798
|
+
}),
|
|
799
|
+
eachStream("a failure after the first item ends the stream with an error line, not a status", async (subject) => {
|
|
800
|
+
const fed = await openStream(subject);
|
|
801
|
+
await pushes(fed, 1, "a stream before its failure");
|
|
802
|
+
fed.fail(failure());
|
|
803
|
+
await ends(fed.view, "failed", true, "a stream that failed after its first item");
|
|
804
|
+
await count(subject, 0, "a stream failed");
|
|
805
|
+
}),
|
|
806
|
+
eachStream("a failure before the first item gets a status, not an error line", async (subject) => {
|
|
807
|
+
const fed = await openStream(subject);
|
|
808
|
+
fed.fail(failure());
|
|
809
|
+
await ends(fed.view, "failed", false, "a stream that failed before its first item");
|
|
810
|
+
check(fed.view.items.length === 0, `a stream that failed before its first item gave ${fed.view.items.length} items`);
|
|
811
|
+
await count(subject, 0, "a stream failed");
|
|
812
|
+
}),
|
|
813
|
+
eachStream("drain waits for an open stream, and the cooperative abort ends the stream with its end", async (subject, time, requests) => {
|
|
814
|
+
const fed = await openStream(subject);
|
|
815
|
+
await pushes(fed, 1, "a stream before the drain");
|
|
816
|
+
await stopBoth(subject, requests);
|
|
817
|
+
const abort = new AbortController();
|
|
818
|
+
const deadline = time.clock.now() + cap;
|
|
819
|
+
const drained = drainBoth(subject, requests, deadline, abort.signal);
|
|
820
|
+
await time.pass(cap / 4);
|
|
821
|
+
await quiet();
|
|
822
|
+
check(!drained.settled, "drain ended while a stream was open, before its deadline");
|
|
823
|
+
check(fed.view.end === null, "the caller got an end before the cooperative abort");
|
|
824
|
+
await count(subject, 1, "a stream is open in the drain");
|
|
825
|
+
abort.abort(/* @__PURE__ */ new Error("the cooperative abort of the conformance kit"));
|
|
826
|
+
check(await within(slack, () => fed.aborted), "the work of the stream did not get the cooperative abort");
|
|
827
|
+
await ends(fed.view, "cut", true, "a stream after the cooperative abort");
|
|
828
|
+
check(await within(slack, () => drained.settled), "drain did not end when the stream ended");
|
|
829
|
+
check(!drained.failed, `drain threw: ${String(drained.error)}`);
|
|
830
|
+
check(time.clock.now() < deadline, "drain waited until its deadline after the stream ended");
|
|
831
|
+
await count(subject, 0, "the cooperative abort left a stream in flight");
|
|
832
|
+
}),
|
|
833
|
+
eachStream("drain cuts an open stream at its deadline, and the caller gets the end of the cut", async (subject, time, requests) => {
|
|
834
|
+
const fed = await openStream(subject);
|
|
835
|
+
await pushes(fed, 1, "a stream before the drain");
|
|
836
|
+
await stopBoth(subject, requests);
|
|
837
|
+
const drained = drainBoth(subject, requests, time.clock.now() + cap, new AbortController().signal);
|
|
838
|
+
await time.pass(cap);
|
|
839
|
+
await ends(fed.view, "cut", true, "a stream at the deadline of the drain");
|
|
840
|
+
check(await within(slack, () => drained.settled), "drain did not end after the cut of the stream");
|
|
841
|
+
check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);
|
|
842
|
+
await count(subject, 0, "the cut left a stream in flight");
|
|
843
|
+
})
|
|
844
|
+
];
|
|
845
|
+
return [...cases, ...streamCases];
|
|
599
846
|
};
|
|
600
847
|
//#endregion
|
|
601
848
|
//#region src/host/fakes.ts
|