@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.
- package/README.md +114 -5
- package/build/{builder-BNAkpeTT.d.ts → builder-bXJqMe2p.d.ts} +3 -2
- package/build/{core-CWsGgr9J.d.ts → core-B1zbS4WY.d.ts} +4 -3
- package/build/{dial-JEJavY0U.d.ts → dial-CSGKVlZe.d.ts} +2 -2
- package/build/grpc.d.ts +3 -3
- package/build/grpc.js +1 -1
- package/build/host.d.ts +556 -0
- package/build/host.js +1738 -0
- package/build/host.js.map +1 -0
- package/build/http-client.d.ts +3 -3
- package/build/http-client.js +1 -1
- package/build/http.d.ts +17 -3
- package/build/http.js +53 -10
- package/build/http.js.map +1 -1
- package/build/index.d.ts +44 -6
- package/build/index.js +78 -158
- package/build/index.js.map +1 -1
- package/build/lifecycle-Ks9Yd5CM.d.ts +387 -0
- package/build/{limiter-B0849Vhp.d.ts → limiter-BoZkXIxk.d.ts} +2 -2
- package/build/{limiter-pkBZUp-t.js → limiter-CmC4vCjk.js} +21 -13
- package/build/limiter-CmC4vCjk.js.map +1 -0
- package/build/limiter.d.ts +3 -3
- package/build/limiter.js +1 -1
- package/build/{lifecycle-CCDLvXLF.d.ts → logger-DhFgh48y.d.ts} +25 -367
- package/build/{machine-DZMb_QEU.js → machine-DKWLZOqu.js} +7 -19
- package/build/machine-DKWLZOqu.js.map +1 -0
- package/build/mongodb.d.ts +3 -3
- package/build/mongodb.js +1 -1
- package/build/pg.d.ts +2 -2
- package/build/pg.js +1 -1
- package/build/ports-CZLzYK5d.d.ts +125 -0
- package/build/process-DG_im2zc.js +171 -0
- package/build/process-DG_im2zc.js.map +1 -0
- package/build/{queue-eLs5IruM.d.ts → queue-BjiGodqh.d.ts} +3 -2
- package/build/rabbitmq.d.ts +4 -4
- package/build/rabbitmq.js +1 -1
- package/build/redis.d.ts +3 -3
- package/build/redis.js +1 -1
- package/build/retrier-Bzkme_yM.js +51 -0
- package/build/retrier-Bzkme_yM.js.map +1 -0
- package/build/{store-D5HLgBnW.d.ts → store-Cwuepb-z.d.ts} +14 -3
- package/build/testing.d.ts +86 -3
- package/build/testing.js +238 -2
- package/build/testing.js.map +1 -1
- package/build/websocket.d.ts +3 -3
- package/build/websocket.js +1 -1
- package/package.json +6 -2
- package/build/limiter-pkBZUp-t.js.map +0 -1
- package/build/machine-DZMb_QEU.js.map +0 -1
package/build/testing.js
CHANGED
|
@@ -57,6 +57,7 @@ const fakeClock = (start = 0) => {
|
|
|
57
57
|
/** This function makes a fake process. */
|
|
58
58
|
const fakeProcess = (options = {}) => {
|
|
59
59
|
const handlers = /* @__PURE__ */ new Map();
|
|
60
|
+
const uncaughtHandlers = /* @__PURE__ */ new Set();
|
|
60
61
|
const exits = [];
|
|
61
62
|
const log = [];
|
|
62
63
|
let flushes = 0;
|
|
@@ -77,6 +78,13 @@ const fakeProcess = (options = {}) => {
|
|
|
77
78
|
set.delete(handler);
|
|
78
79
|
};
|
|
79
80
|
},
|
|
81
|
+
onUncaught(handler) {
|
|
82
|
+
const own = (error, origin) => handler(error, origin);
|
|
83
|
+
uncaughtHandlers.add(own);
|
|
84
|
+
return () => {
|
|
85
|
+
uncaughtHandlers.delete(own);
|
|
86
|
+
};
|
|
87
|
+
},
|
|
80
88
|
async flush() {
|
|
81
89
|
stamp("flush");
|
|
82
90
|
await options.flush?.();
|
|
@@ -100,11 +108,14 @@ const fakeProcess = (options = {}) => {
|
|
|
100
108
|
signal: (name) => send(name),
|
|
101
109
|
trigger: (name) => send(name),
|
|
102
110
|
message: (value) => send("ipc-message", value),
|
|
111
|
+
uncaught: (error, origin = "uncaughtException") => {
|
|
112
|
+
for (const handler of [...uncaughtHandlers]) handler(error, origin);
|
|
113
|
+
},
|
|
103
114
|
get exits() {
|
|
104
115
|
return [...exits];
|
|
105
116
|
},
|
|
106
117
|
get handlers() {
|
|
107
|
-
let count =
|
|
118
|
+
let count = uncaughtHandlers.size;
|
|
108
119
|
for (const set of handlers.values()) count += set.size;
|
|
109
120
|
return count;
|
|
110
121
|
},
|
|
@@ -587,6 +598,231 @@ const transportConformance = (make, options = {}) => {
|
|
|
587
598
|
];
|
|
588
599
|
};
|
|
589
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
|
|
590
826
|
//#region src/testing.ts
|
|
591
827
|
/** This function makes a scripted check with a behavior at the start. */
|
|
592
828
|
const scriptedCheck = (behavior = "ok") => {
|
|
@@ -676,6 +912,6 @@ const quietServer = async () => {
|
|
|
676
912
|
};
|
|
677
913
|
};
|
|
678
914
|
//#endregion
|
|
679
|
-
export { contractCases, detachedLifecycle, fakeClock, fakeProcess, quietServer, scriptedCheck, seeded, testLogger, transportConformance };
|
|
915
|
+
export { contractCases, detachedLifecycle, fakeClock, fakeHost, fakeProcess, quietServer, scriptedCheck, seeded, testLogger, transportConformance };
|
|
680
916
|
|
|
681
917
|
//# sourceMappingURL=testing.js.map
|
package/build/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../src/fakes.ts","../src/contract.ts","../src/conformance.ts","../src/testing.ts"],"sourcesContent":["// The fakes of the runtime for tests: a fake clock gives exact, repeatable timing, a seeded random\n// gives the same jitter on each run, and a fake process takes signals and keeps the exit codes.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { ExitSignal, ExitTrigger, ProcessPort } from \"./process.ts\";\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n\n/** A fake process receives triggers from a test, and keeps each exit code in place of an exit. */\nexport interface FakeProcess extends ProcessPort {\n /** This method sends a signal to each handler of it. */\n signal(name: ExitSignal): void;\n /** This method sends a trigger to each handler of it: a signal, or a process trigger, for example `stdin-close`. */\n trigger(name: ExitTrigger): void;\n /** This method sends a message of the IPC channel to each handler of the trigger `ipc-message`. */\n message(value: unknown): void;\n /** These are the exit codes, in sequence. A correct runtime exits one time. */\n readonly exits: readonly number[];\n /** This count is the number of handlers that are registered. */\n readonly handlers: number;\n /** These are the triggers that have a handler, in the sequence of their first handler. */\n readonly triggers: readonly ExitTrigger[];\n /** These are the times of the clock of the options at each flush and each exit, when the options give a clock. */\n readonly log: readonly string[];\n /** This count is the number of flushes of the output. */\n readonly flushes: number;\n /** This count is the number of holds of the process that are not released. */\n readonly holds: number;\n /** These counts are the holds that were not released at each exit, in sequence. */\n readonly heldAtExit: readonly number[];\n}\n\n/** These options shape a fake process. */\nexport interface FakeProcessOptions {\n /** This function is the flush of the output, for example a wait on a fake clock. Without it, a flush ends at once. */\n readonly flush?: (() => Promise<void> | void) | undefined;\n /** This clock stamps each line of the log. */\n readonly clock?: Clock | undefined;\n}\n\n/** This function makes a fake process. */\nexport const fakeProcess = (options: FakeProcessOptions = {}): FakeProcess => {\n const handlers = new Map<ExitTrigger, Set<(message?: unknown) => void>>();\n const exits: number[] = [];\n const log: string[] = [];\n let flushes = 0;\n let holds = 0;\n const heldAtExit: number[] = [];\n const stamp = (what: string): void => {\n log.push(options.clock === undefined ? what : `${options.clock.now()} ${what}`);\n };\n const send = (name: ExitTrigger, message?: unknown): void => {\n for (const handler of [...(handlers.get(name) ?? [])]) handler(message);\n };\n return {\n on(trigger, handler) {\n const set = handlers.get(trigger) ?? new Set();\n set.add(handler);\n handlers.set(trigger, set);\n return () => {\n set.delete(handler);\n };\n },\n async flush() {\n stamp(\"flush\");\n await options.flush?.();\n flushes += 1;\n stamp(\"flushed\");\n },\n hold() {\n holds += 1;\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n holds -= 1;\n };\n },\n exit(code) {\n stamp(`exit ${code}`);\n heldAtExit.push(holds);\n exits.push(code);\n },\n signal: (name) => send(name),\n trigger: (name) => send(name),\n message: (value) => send(\"ipc-message\", value),\n get exits() {\n return [...exits];\n },\n get handlers() {\n let count = 0;\n for (const set of handlers.values()) count += set.size;\n return count;\n },\n get triggers() {\n return [...handlers.keys()];\n },\n get log() {\n return [...log];\n },\n get flushes() {\n return flushes;\n },\n get holds() {\n return holds;\n },\n get heldAtExit() {\n return [...heldAtExit];\n },\n };\n};\n\n/** This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). */\nexport const seeded = (seed: number): (() => number) => {\n let state = seed >>> 0;\n return () => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n","import { valueIn } from \"@mark1russell7/quantity\";\nimport type { ServiceBuilder } from \"./builder.ts\";\nimport type { Check, ServiceDescription } from \"./description.ts\";\nimport type { FakeClock } from \"./fakes.ts\";\nimport { fakeClock, seeded } from \"./fakes.ts\";\nimport type { Health, HealthVerdict, StartOptions } from \"./health.ts\";\nimport { failSpan, recoverSpan } from \"./timing.ts\";\n\n/** A contract case is one generated case of the contract test of a declaration. It throws on a failure. */\nexport interface ContractCase {\n readonly name: string;\n run(): Promise<void>;\n}\n\n/** These options tune the contract test. */\nexport interface ContractOptions {\n /** This number is the latency that a degraded dependency adds to each check, in milliseconds. The default of the contract is 100. */\n readonly degradeBy?: number | undefined;\n /** This number is the seed of the jitter. */\n readonly seed?: number | undefined;\n}\n\nconst ms = (amount: { readonly value: number; readonly unit: string }): number => valueIn(amount, \"ms\");\n\n/** The part of a verdict that the contract compares: what a caller and the platform see. */\nconst visible = (verdict: HealthVerdict) => ({\n ready: verdict.ready,\n alive: verdict.alive,\n controllers: verdict.controllers,\n dependencies: verdict.dependencies,\n});\n\nconst same = (expected: unknown, actual: unknown): boolean => JSON.stringify(expected) === JSON.stringify(actual);\n\nconst failure = (what: string, expected: unknown, actual: unknown): Error =>\n new Error(`${what}: expected ${JSON.stringify(expected)}, but the verdict was ${JSON.stringify(actual)}`);\n\n/**\n * This function generates the contract test of a declaration. `declare` gives a new builder with\n * the declaration and the function of each check, each time. The checks must pass at rest. The\n * cases are:\n * - The service at rest: each controller and each dependency is ready, and the service is alive.\n * - Each dependency unavailable: its polls fail at once (the force-fail list). The dependency and\n * each controller that needs it become not ready, and the other controllers stay ready. Liveness\n * stays, unless a liveness check exercises the dependency.\n * - Each dependency degraded: each call of its checks takes the latency longer. Nothing can fail.\n * - Each dependency recovers: after it is unavailable, the service is again at rest.\n * - A negative control: a client that the declaration does not name fails, and nothing changes.\n *\n * A dependency that no check exercises is a finding: the service cannot see it fail.\n */\nexport const contractCases = (declare: () => ServiceBuilder, options: ContractOptions = {}): ContractCase[] => {\n const degradeBy = options.degradeBy ?? 100;\n const seed = options.seed ?? 1;\n const description: ServiceDescription = declare().describe();\n const service = description.name;\n const gating = description.checks.filter((check) => check.gates !== null);\n const timingOf = (check: Check) => description.policies[check.gates!];\n const failMax = (check: Check): number => ms(failSpan(timingOf(check), check.poll, \"error\").max);\n const recoverMax = (check: Check): number => ms(recoverSpan(timingOf(check), check.poll).max);\n const most = (values: readonly number[]): number => values.reduce((a, b) => Math.max(a, b), 0);\n const settleTime = most(gating.filter((check) => check.gates === \"readiness\").map(recoverMax)) + 1;\n const quietTime = most(gating.map(failMax)) + 1;\n\n /** This function starts the declaration on a fake clock, and moves it to rest. */\n const boot = async (\n extra: (clock: FakeClock) => Partial<StartOptions> = () => ({}),\n ): Promise<{ health: Health; clock: FakeClock; rest: ReturnType<typeof visible> }> => {\n const clock = fakeClock();\n // the warm-up sweep can wait on the clock (a degraded check), thus the clock moves while it starts\n const starting = declare().start({ clock, random: seeded(seed), ...extra(clock) });\n let started = false;\n void starting.then(\n () => (started = true),\n () => (started = true),\n );\n for (let step = 0; step < 1000 && !started; step += 1) await clock.advance(10);\n const health = await starting;\n await clock.advance(settleTime);\n return { health, clock, rest: visible(health.verdict()) };\n };\n const stop = (health: Health): void => health.stop();\n\n const cases: ContractCase[] = [\n {\n name: `${service}: at rest, each controller and each dependency is ready, and the service is alive`,\n async run() {\n const { health, rest } = await boot();\n try {\n const expected = {\n ready: true,\n alive: true,\n controllers: Object.fromEntries(description.controllers.map((each) => [each.name, true])),\n dependencies: Object.fromEntries(description.dependencies.map((each) => [each.name, true])),\n };\n if (!same(expected, rest)) throw failure(\"at rest\", expected, rest);\n } finally {\n stop(health);\n }\n },\n },\n ];\n\n for (const dependency of description.dependencies) {\n const on = gating.filter((check) => check.dependency === dependency.name);\n const readiness = on.filter((check) => check.gates === \"readiness\");\n const liveness = on.filter((check) => check.gates === \"liveness\");\n const unavailable = (rest: ReturnType<typeof visible>) => ({\n ready: readiness.length === 0 ? rest.ready : false,\n alive: liveness.length === 0 ? rest.alive : false,\n controllers: Object.fromEntries(\n description.controllers.map((each) => [\n each.name,\n each.requires.includes(dependency.name) && readiness.length > 0 ? false : rest.controllers[each.name],\n ]),\n ),\n dependencies: { ...rest.dependencies, [dependency.name]: readiness.length === 0 },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} unavailable`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it fail`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n const now = visible(health.verdict());\n const expected = unavailable(rest);\n if (!same(expected, now)) throw failure(`${dependency.name} unavailable`, expected, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} degraded by ${degradeBy} ms, and nothing fails`,\n async run() {\n const tight = on.filter((check) => ms(check.poll.timeout) <= degradeBy);\n if (tight.length > 0)\n throw new Error(\n `${tight.map((check) => `${check.name} times out in ${ms(check.poll.timeout)} ms`).join(\", \")}: a latency of ${degradeBy} ms fails it`,\n );\n const { health, clock, rest } = await boot((at) => ({\n wrapCheck: (check, run) =>\n check.dependency !== dependency.name\n ? run\n : (signal) => new Promise((resolve) => at.after(degradeBy, () => resolve(run(signal)))),\n }));\n try {\n await clock.advance(quietTime + most(on.map((check) => ms(check.poll.interval))));\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} degraded`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} recovers`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it recover`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n health.forceFail(dependency.name, false);\n await clock.advance(most(on.map(recoverMax)) + 1);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} recovered`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n }\n\n const never = `${service}.client-never-registered`;\n cases.push({\n name: `${service}: a client never registered fails, and nothing changes (the negative control)`,\n async run() {\n if (description.dependencies.some((each) => each.name === never))\n throw new Error(`the declaration has a dependency named ${never}`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(never, true);\n await clock.advance(quietTime);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(\"the negative control\", rest, now);\n } finally {\n stop(health);\n }\n // and a check on a client never registered is refused before the start\n let refused = false;\n try {\n declare()\n .check({\n name: `${never}.check`,\n dependency: never,\n step: \"round-trip\",\n ownConnection: true,\n gates: null,\n poll: gating[0]?.poll ?? { interval: { value: 1, unit: \"s\" }, jitter: 0, timeout: { value: 0.5, unit: \"s\" } },\n })\n .describe();\n } catch {\n refused = true;\n }\n if (!refused) throw new Error(`the declaration accepted a check on ${never}, which is not a dependency`);\n },\n });\n\n return cases;\n};\n","import type { Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.ts\";\n\n/** A held work is one unit of work that stays in flight until the test releases it. */\nexport interface HeldWork {\n /** This method lets the work end. Its promise ends when the caller of the work has its answer, or its error. */\n release(): Promise<void>;\n /** This flag tells if the work got the cooperative abort of the drain. */\n readonly aborted: boolean;\n}\n\n/**\n * A transport subject is a transport and the client side of its work. The kit offers work through\n * it, holds work in flight through it, and reads the count of the transport.\n */\nexport interface TransportSubject {\n readonly impl: TransportImpl;\n /** This lifecycle goes to `start()`. Without it, the kit gives a detached lifecycle. */\n readonly life?: Lifecycle | undefined;\n /** This method offers one unit of new work. It gives true when the transport took it, and false when it refused it. */\n offer(): Promise<boolean>;\n /** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */\n hold(): Promise<HeldWork>;\n /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\n}\n\n/**\n * This function gives a detached lifecycle: a lifecycle with no service, for the start of a\n * transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request\n * and each use of its health throws, because no service declares a route.\n */\nexport const detachedLifecycle = (): Lifecycle => {\n const none = (): never => {\n throw new Error(\"a detached lifecycle has no service: give the transport the lifecycle of a service\");\n };\n const health = { verdict: none, probe: none, metrics: none, subscribe: none, forceFail: none, drain: none, stop: none } as Health;\n return {\n health,\n state: \"running\",\n exitCode: null,\n errors: [],\n started: Promise.resolve(),\n done: new Promise<number>(() => {}),\n signal: new AbortController().signal,\n shutdown: none,\n request: none,\n inFlight: () => 0,\n keepAlive: () => true,\n };\n};\n\n/** A subject factory makes a new subject for each case, on the clock of the case. */\nexport type SubjectFactory = (clock: Clock) => TransportSubject | Promise<TransportSubject>;\n\n/** A conformance record is one measurement of a case, for the raw records of a run in CI. */\nexport interface ConformanceRecord {\n readonly case: string;\n readonly what: string;\n /** This time is the limit of the contract, in milliseconds. */\n readonly expected: number;\n /** This time is what the case measured, in milliseconds of the real clock. */\n readonly measured: number;\n}\n\n/** These options tune the conformance kit. */\nexport interface ConformanceOptions {\n /** This name goes before the name of each case. */\n readonly name?: string | undefined;\n /** This clock moves the cases: `fake` gives exact and fast cases, and `real` measures the timing. The default is `fake`. */\n readonly clock?: \"fake\" | \"real\" | undefined;\n /** This time is the cap of each drain of the cases, in milliseconds. The default is 1000. */\n readonly cap?: number | undefined;\n /** This time is the most that a close can take, in milliseconds of the real clock. The default is 1000. */\n readonly closeBound?: number | undefined;\n /** This time is the most that an event can take to reach the transport, in real milliseconds. The default is 100. */\n readonly slack?: number | undefined;\n /** False tells that the work of the transport cannot see the cooperative abort. The default is true. */\n readonly cooperative?: boolean | undefined;\n /** This count is the number of works that the count case holds. The default is 3. */\n readonly holds?: number | undefined;\n /** This function receives each measurement, for the raw records of a run. */\n readonly record?: ((record: ConformanceRecord) => void) | undefined;\n}\n\ninterface Time {\n readonly clock: Clock;\n pass(ms: number): Promise<void>;\n}\n\ninterface Tracked {\n readonly settled: boolean;\n readonly error: unknown;\n readonly failed: boolean;\n}\n\nconst realNow = (): number => performance.now();\nconst turn = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** This function waits on the real clock, until the test is true or the bound ends. It gives the test at the end. */\nconst within = async (bound: number, test: () => boolean): Promise<boolean> => {\n const end = realNow() + bound;\n for (;;) {\n if (test()) return true;\n if (realNow() > end) return test();\n await turn();\n }\n};\n\n/** This function lets the events that are ready reach the transport, with no move of the clock of the case. */\nconst quiet = async (): Promise<void> => {\n for (let at = 0; at < 8; at += 1) await turn();\n};\n\n/** This function uses a method of the transport, and gives a throw of the method as a rejection. */\nconst attempt = (call: () => Promise<void> | void): Promise<void> => {\n try {\n return Promise.resolve(call());\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nconst track = (promise: Promise<unknown>): Tracked => {\n const state = { settled: false, error: undefined as unknown, failed: false };\n promise.then(\n () => {\n state.settled = true;\n },\n (error: unknown) => {\n state.settled = true;\n state.failed = true;\n state.error = error;\n },\n );\n return state;\n};\n\n/**\n * This function generates the conformance cases of a transport (S6 A9). `make` gives a new subject\n * for each case. Each case throws on a failure, and its message names the part of the contract.\n * - The start: nothing is in flight, and the transport takes work.\n * - The count: it follows each work from its events, with no move of the clock.\n * - `stopIntake` refuses new work, keeps the work in flight, and a second stop has no effect.\n * - `drain` ends at once with no work, ends with the last work, and holds to its deadline and not\n * past it. It gives the cooperative abort to the work, and it does not throw.\n * - `close` ends the work in flight in its bound, and a second close has no effect.\n * - The stages in their sequence, as the lifecycle does them.\n */\nexport const transportConformance = (make: SubjectFactory, options: ConformanceOptions = {}): ContractCase[] => {\n const name = options.name ?? \"transport\";\n const fake = (options.clock ?? \"fake\") === \"fake\";\n const cap = options.cap ?? 1000;\n const closeBound = options.closeBound ?? 1000;\n const slack = options.slack ?? 100;\n const cooperative = options.cooperative ?? true;\n const holds = options.holds ?? 3;\n\n const timeOf = (): Time => {\n if (!fake) return { clock: realClock, pass: sleep };\n const clock = fakeClock();\n return { clock, pass: (ms) => clock.advance(ms) };\n };\n\n const check = (ok: boolean, what: string): void => {\n if (!ok) throw new Error(`${name}: ${what}`);\n };\n\n const each = (title: string, body: (subject: TransportSubject, time: Time, title: string) => Promise<void>): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, subject.life ?? detachedLifecycle());\n await body(subject, time, title);\n } finally {\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const count = (subject: TransportSubject, expected: number, what: string): Promise<void> =>\n within(slack, () => subject.impl.inFlight() === expected).then((ok) =>\n check(ok, `${what}: inFlight() gives ${subject.impl.inFlight()}, not ${expected}`),\n );\n\n const closes = async (subject: TransportSubject, title: string): Promise<void> => {\n const began = realNow();\n const closed = track(attempt(() => subject.impl.close()));\n const inBound = await within(closeBound, () => closed.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"close\", expected: closeBound, measured: took });\n check(inBound, `close did not end in its bound of ${closeBound} ms`);\n check(!closed.failed, `close threw: ${String(closed.error)}`);\n };\n\n const cases: ContractCase[] = [\n each(\"nothing is in flight after the start, and it takes new work\", async (subject) => {\n check(subject.impl.inFlight() === 0, `inFlight() gives ${subject.impl.inFlight()} after the start, not 0`);\n check(await subject.offer(), \"the transport refused new work after its start\");\n await count(subject, 0, \"the work ended\");\n }),\n\n each(\"the count follows each work in flight from its events, with no move of the clock\", async (subject) => {\n const held: HeldWork[] = [];\n for (let at = 1; at <= holds; at += 1) {\n held.push(await subject.hold());\n await count(subject, at, `${at} works are in flight`);\n }\n for (let at = holds - 1; at >= 0; at -= 1) {\n await held[at]!.release();\n await count(subject, at, `${at} works are in flight after a release`);\n }\n }),\n\n each(\"stopIntake refuses new work, keeps the work in flight, and a second stop has no effect\", async (subject) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n await count(subject, 1, \"stopIntake cut the work in flight\");\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after a second stopIntake\");\n await work.release();\n await count(subject, 0, \"the work in flight ended after stopIntake\");\n }),\n\n each(\"drain ends at once when nothing is in flight\", async (subject, time) => {\n await subject.impl.stopIntake();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, new AbortController().signal)));\n check(await within(slack, () => drained.settled), \"drain did not end with nothing in flight\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n }),\n\n each(\"drain ends when the last work ends, before its deadline\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while work was in flight, before its deadline\");\n await work.release();\n check(await within(slack, () => drained.settled), \"drain did not end when the last work ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the last work ended\");\n }),\n\n each(\"drain holds to its deadline and not past it, and does not throw\", async (subject, time, title) => {\n await subject.hold();\n await subject.impl.stopIntake();\n const began = realNow();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n if (fake) {\n await time.pass(cap - 1);\n await quiet();\n check(!drained.settled, \"drain ended before its deadline, with work in flight\");\n await time.pass(1);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n } else {\n const ended = await within(cap + slack, () => drained.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"drain to its deadline\", expected: cap, measured: took });\n check(ended, `drain did not end in ${cap + slack} ms, with a deadline at ${cap} ms`);\n check(took >= cap - slack, `drain ended after ${Math.round(took)} ms, before its deadline at ${cap} ms`);\n }\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n }),\n\n ...(cooperative\n ? [\n each(\"drain gives the cooperative abort to the work in flight\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await time.pass(cap / 2);\n await quiet();\n check(!work.aborted, \"the work got an abort before the signal of the drain aborted\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => work.aborted), \"the work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline after the cooperative abort\");\n check(!drained.failed, `drain threw after the cooperative abort: ${String(drained.error)}`);\n }),\n ]\n : []),\n\n each(\"drain with an aborted signal and a deadline in the past ends at once\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() - 1, abort.signal)));\n check(await within(slack, () => drained.settled), \"drain did not end at once with its deadline in the past\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n if (cooperative) check(await within(slack, () => work.aborted), \"the work did not get an abort that came before the drain\");\n }),\n\n each(\"close ends the work in flight, in its bound\", async (subject, _time, title) => {\n for (let at = 0; at < holds; at += 1) await subject.hold();\n await count(subject, holds, \"the works are in flight before the close\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n\n each(\"close is idempotent: a second close has no effect\", async (subject, _time, title) => {\n await subject.hold();\n const first = track(attempt(() => subject.impl.close()));\n const second = track(attempt(() => subject.impl.close()));\n check(await within(closeBound, () => first.settled && second.settled), \"two closes did not end in the bound\");\n check(!first.failed && !second.failed, `a close threw: ${String(first.error ?? second.error)}`);\n await closes(subject, title);\n await count(subject, 0, \"the closes left work in flight\");\n }),\n\n each(\"close right after the start ends in its bound\", async (subject, _time, title) => {\n await closes(subject, title);\n check(subject.impl.inFlight() === 0, \"inFlight() is not 0 after a close with no work\");\n }),\n\n each(\"the stages in their sequence: stop intake, drain with its cooperative abort, close\", async (subject, time, title) => {\n const short = await subject.hold();\n const long = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await short.release();\n await count(subject, 1, \"one work ended in the drain\");\n await time.pass(cap / 2);\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n if (cooperative) check(await within(slack, () => long.aborted), \"the long work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n ];\n return cases;\n};\n","// @mark1russell7/service/testing: the seams of the runtime for tests. A fake clock gives exact,\n// repeatable timing. A seeded random gives the same jitter on each run. A fake process takes\n// signals and keeps the exit codes. A quiet server answers until it goes quiet, and then it holds\n// its connections open without an answer. A test logger keeps each log entry. `contractCases` generates the contract test of a\n// declaration, and `transportConformance` generates the conformance test of a transport.\n\nimport type { AddressInfo, Server, Socket } from \"node:net\";\nimport { createServer } from \"node:net\";\nimport type { Outcome } from \"./latch.ts\";\nimport type { LogEntry, LogLevel, Logger } from \"./logger.ts\";\nimport type { CheckFn } from \"./poller.ts\";\n\nexport type { FakeClock, FakeProcess, FakeProcessOptions } from \"./fakes.ts\";\nexport { fakeClock, fakeProcess, seeded } from \"./fakes.ts\";\nexport type { ContractCase, ContractOptions } from \"./contract.ts\";\nexport { contractCases } from \"./contract.ts\";\nexport type {\n ConformanceOptions,\n ConformanceRecord,\n HeldWork,\n SubjectFactory,\n TransportSubject,\n} from \"./conformance.ts\";\nexport { detachedLifecycle, transportConformance } from \"./conformance.ts\";\n\n/**\n * A behavior is what a scripted check does when the runtime starts it:\n * - `\"ok\"`, `\"error\"` and `\"indeterminate\"` give that outcome at once.\n * - `\"throw\"` throws at once.\n * - `\"timeout\"` gives no answer until the runtime aborts the use at the timeout of the poll.\n * - `\"hang\"` gives no answer, and it ignores the abort, until `heal()`.\n */\nexport type Behavior = Outcome | \"throw\" | \"timeout\" | \"hang\";\n\n/** A scripted check is a check function whose behavior a test sets. */\nexport interface ScriptedCheck {\n readonly run: CheckFn;\n /** This behavior applies to each later call. */\n behavior: Behavior;\n /** This count is the number of calls of the check. */\n readonly calls: number;\n /** This count is the number of calls that are pending. */\n readonly hung: number;\n /** This method ends each hung call with a pass, as when a driver gets its answer late. */\n heal(): void;\n}\n\n/** This function makes a scripted check with a behavior at the start. */\nexport const scriptedCheck = (behavior: Behavior = \"ok\"): ScriptedCheck => {\n let calls = 0;\n const hung = new Set<() => void>();\n const script: ScriptedCheck = {\n behavior,\n get calls() {\n return calls;\n },\n get hung() {\n return hung.size;\n },\n heal() {\n for (const end of [...hung]) end();\n },\n run: (signal) => {\n calls += 1;\n const now = script.behavior;\n if (now === \"throw\") throw new Error(\"the scripted check threw\");\n if (now === \"timeout\")\n return new Promise<Outcome>((_, reject) =>\n signal.addEventListener(\"abort\", () => reject(new Error(\"aborted at the timeout\"))),\n );\n if (now === \"hang\")\n return new Promise<Outcome>((resolve) => {\n const end = (): void => {\n hung.delete(end);\n resolve(\"ok\");\n };\n hung.add(end);\n });\n return now;\n },\n };\n return script;\n};\n\n/** A test logger is a logger that keeps each entry, thus a test can examine the log of the runtime. */\nexport interface TestLogger extends Logger {\n /** These are the entries, in the sequence of their calls. */\n readonly entries: readonly LogEntry[];\n /** This method gives the message of each entry, or of each entry at one level. */\n messages(level?: LogLevel): string[];\n /** This method removes each entry. */\n clear(): void;\n}\n\n/** This function makes a test logger with no entries. */\nexport const testLogger = (): TestLogger => {\n const entries: LogEntry[] = [];\n return {\n entries,\n log(level, message, fields) {\n entries.push({ level, message, fields });\n },\n messages: (level) => entries.filter((entry) => level === undefined || entry.level === level).map((entry) => entry.message),\n clear() {\n entries.length = 0;\n },\n };\n};\n\n/** A quiet server is a TCP echo server that can stop its answers and keep its connections open. */\nexport interface QuietServer {\n readonly port: number;\n /** This method stops the answers. The connections stay open, and the server reads and discards the data. */\n quiet(): void;\n /** This method starts the answers again. */\n speak(): void;\n /** This count is the number of open connections. */\n readonly connections: number;\n close(): Promise<void>;\n}\n\n/**\n * This function starts a quiet server on the loopback address. A check against it passes while it\n * answers. When it goes quiet, the check sees a connection that is open but silent. A frozen peer\n * and a black hole that keeps the connection look the same.\n */\nexport const quietServer = async (): Promise<QuietServer> => {\n let silent = false;\n const sockets = new Set<Socket>();\n const server: Server = createServer((socket) => {\n sockets.add(socket);\n socket.on(\"close\", () => sockets.delete(socket));\n socket.on(\"error\", () => sockets.delete(socket));\n socket.on(\"data\", (chunk) => {\n if (!silent) socket.write(chunk);\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n return {\n port: (server.address() as AddressInfo).port,\n quiet: () => {\n silent = true;\n },\n speak: () => {\n silent = false;\n },\n get connections() {\n return sockets.size;\n },\n close: () =>\n new Promise<void>((resolve) => {\n for (const socket of sockets) socket.destroy();\n server.close(() => resolve());\n }),\n };\n};\n"],"mappings":";;;;;;AAoBA,MAAM,SAAS,YAA2B;CACxC,KAAK,IAAI,OAAO,GAAG,OAAO,IAAI,QAAQ,GAAG,MAAM,QAAQ,QAAQ;AACjE;;AAGA,MAAa,aAAa,QAAQ,MAAiB;CACjD,IAAI,MAAM;CACV,IAAI,WAAW;CACf,MAAM,SAA+E,CAAC;CACtF,MAAM,OAAO,QAAgB;EAC3B,IAAI;EACJ,KAAK,MAAM,SAAS,QAClB,IAAI,MAAM,QAAQ,MAAM,MAAM,QAAQ,SAAS,KAAA,KAAa,MAAM,KAAK,KAAK,MAAO,MAAM,OAAO,KAAK,MAAM,MAAM,QAAQ,KAAK,QAC5H,OAAO;EACX,OAAO;CACT;CACA,OAAO;EACL,WAAW;EACX,MAAM,IAAI,KAAa;GACrB,MAAM,QAAQ;IAAE,IAAI,MAAM,KAAK,IAAI,GAAG,EAAE;IAAG,OAAO;IAAY;IAAK,MAAM;GAAK;GAC9E,OAAO,KAAK,KAAK;GACjB,aAAa;IACX,MAAM,OAAO;GACf;EACF;EACA,MAAM,QAAQ,IAAI;GAEhB,MAAM,MAAM,MAAM,KAAK,IAAI,GAAG,EAAE;GAChC,MAAM,OAAO;GACb,SAAS;IACP,MAAM,QAAQ,IAAI,GAAG;IACrB,IAAI,UAAU,KAAA,GAAW;IACzB,MAAM,OAAO;IAEb,MAAM,KAAK,IAAI,KAAK,MAAM,EAAE;IAC5B,MAAM,IAAI;IACV,MAAM,OAAO;GACf;GACA,MAAM,KAAK,IAAI,KAAK,GAAG;GACvB,KAAK,IAAI,KAAK,OAAO,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC,OAAO,GAAG,CAAE,MAAM,OAA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SAAS,OAAO,QAAQ;GAC7C,OAAO,YAAY,QAAQ,CAAC;EAC9B,CAAC;CACL;AACF"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../src/fakes.ts","../src/contract.ts","../src/conformance.ts","../src/host/fakes.ts","../src/testing.ts"],"sourcesContent":["// The fakes of the runtime for tests: a fake clock gives exact, repeatable timing, a seeded random\n// gives the same jitter on each run, and a fake process takes signals and keeps the exit codes.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { ExitSignal, ExitTrigger, ProcessPort, UncaughtOrigin } from \"./process.ts\";\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n\n/** A fake process receives triggers from a test, and keeps each exit code in place of an exit. */\nexport interface FakeProcess extends ProcessPort {\n /** This method sends a signal to each handler of it. */\n signal(name: ExitSignal): void;\n /** This method sends a trigger to each handler of it: a signal, or a process trigger, for example `stdin-close`. */\n trigger(name: ExitTrigger): void;\n /** This method sends a message of the IPC channel to each handler of the trigger `ipc-message`. */\n message(value: unknown): void;\n /** This method sends an error that no code caught to each handler of `onUncaught`. The default origin is `uncaughtException`. */\n uncaught(error: unknown, origin?: UncaughtOrigin): void;\n /** These are the exit codes, in sequence. A correct runtime exits one time. */\n readonly exits: readonly number[];\n /** This count is the number of handlers that are registered. */\n readonly handlers: number;\n /** These are the triggers that have a handler, in the sequence of their first handler. */\n readonly triggers: readonly ExitTrigger[];\n /** These are the times of the clock of the options at each flush and each exit, when the options give a clock. */\n readonly log: readonly string[];\n /** This count is the number of flushes of the output. */\n readonly flushes: number;\n /** This count is the number of holds of the process that are not released. */\n readonly holds: number;\n /** These counts are the holds that were not released at each exit, in sequence. */\n readonly heldAtExit: readonly number[];\n}\n\n/** These options shape a fake process. */\nexport interface FakeProcessOptions {\n /** This function is the flush of the output, for example a wait on a fake clock. Without it, a flush ends at once. */\n readonly flush?: (() => Promise<void> | void) | undefined;\n /** This clock stamps each line of the log. */\n readonly clock?: Clock | undefined;\n}\n\n/** This function makes a fake process. */\nexport const fakeProcess = (options: FakeProcessOptions = {}): FakeProcess => {\n const handlers = new Map<ExitTrigger, Set<(message?: unknown) => void>>();\n const uncaughtHandlers = new Set<(error: unknown, origin: UncaughtOrigin) => void>();\n const exits: number[] = [];\n const log: string[] = [];\n let flushes = 0;\n let holds = 0;\n const heldAtExit: number[] = [];\n const stamp = (what: string): void => {\n log.push(options.clock === undefined ? what : `${options.clock.now()} ${what}`);\n };\n const send = (name: ExitTrigger, message?: unknown): void => {\n for (const handler of [...(handlers.get(name) ?? [])]) handler(message);\n };\n return {\n on(trigger, handler) {\n const set = handlers.get(trigger) ?? new Set();\n set.add(handler);\n handlers.set(trigger, set);\n return () => {\n set.delete(handler);\n };\n },\n onUncaught(handler) {\n // each registration is a handler of its own, as with `on`\n const own = (error: unknown, origin: UncaughtOrigin): void => handler(error, origin);\n uncaughtHandlers.add(own);\n return () => {\n uncaughtHandlers.delete(own);\n };\n },\n async flush() {\n stamp(\"flush\");\n await options.flush?.();\n flushes += 1;\n stamp(\"flushed\");\n },\n hold() {\n holds += 1;\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n holds -= 1;\n };\n },\n exit(code) {\n stamp(`exit ${code}`);\n heldAtExit.push(holds);\n exits.push(code);\n },\n signal: (name) => send(name),\n trigger: (name) => send(name),\n message: (value) => send(\"ipc-message\", value),\n uncaught: (error, origin = \"uncaughtException\") => {\n for (const handler of [...uncaughtHandlers]) handler(error, origin);\n },\n get exits() {\n return [...exits];\n },\n get handlers() {\n let count = uncaughtHandlers.size;\n for (const set of handlers.values()) count += set.size;\n return count;\n },\n get triggers() {\n return [...handlers.keys()];\n },\n get log() {\n return [...log];\n },\n get flushes() {\n return flushes;\n },\n get holds() {\n return holds;\n },\n get heldAtExit() {\n return [...heldAtExit];\n },\n };\n};\n\n/** This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). */\nexport const seeded = (seed: number): (() => number) => {\n let state = seed >>> 0;\n return () => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n","import { valueIn } from \"@mark1russell7/quantity\";\nimport type { ServiceBuilder } from \"./builder.ts\";\nimport type { Check, ServiceDescription } from \"./description.ts\";\nimport type { FakeClock } from \"./fakes.ts\";\nimport { fakeClock, seeded } from \"./fakes.ts\";\nimport type { Health, HealthVerdict, StartOptions } from \"./health.ts\";\nimport { failSpan, recoverSpan } from \"./timing.ts\";\n\n/** A contract case is one generated case of the contract test of a declaration. It throws on a failure. */\nexport interface ContractCase {\n readonly name: string;\n run(): Promise<void>;\n}\n\n/** These options tune the contract test. */\nexport interface ContractOptions {\n /** This number is the latency that a degraded dependency adds to each check, in milliseconds. The default of the contract is 100. */\n readonly degradeBy?: number | undefined;\n /** This number is the seed of the jitter. */\n readonly seed?: number | undefined;\n}\n\nconst ms = (amount: { readonly value: number; readonly unit: string }): number => valueIn(amount, \"ms\");\n\n/** The part of a verdict that the contract compares: what a caller and the platform see. */\nconst visible = (verdict: HealthVerdict) => ({\n ready: verdict.ready,\n alive: verdict.alive,\n controllers: verdict.controllers,\n dependencies: verdict.dependencies,\n});\n\nconst same = (expected: unknown, actual: unknown): boolean => JSON.stringify(expected) === JSON.stringify(actual);\n\nconst failure = (what: string, expected: unknown, actual: unknown): Error =>\n new Error(`${what}: expected ${JSON.stringify(expected)}, but the verdict was ${JSON.stringify(actual)}`);\n\n/**\n * This function generates the contract test of a declaration. `declare` gives a new builder with\n * the declaration and the function of each check, each time. The checks must pass at rest. The\n * cases are:\n * - The service at rest: each controller and each dependency is ready, and the service is alive.\n * - Each dependency unavailable: its polls fail at once (the force-fail list). The dependency and\n * each controller that needs it become not ready, and the other controllers stay ready. Liveness\n * stays, unless a liveness check exercises the dependency.\n * - Each dependency degraded: each call of its checks takes the latency longer. Nothing can fail.\n * - Each dependency recovers: after it is unavailable, the service is again at rest.\n * - A negative control: a client that the declaration does not name fails, and nothing changes.\n *\n * A dependency that no check exercises is a finding: the service cannot see it fail.\n */\nexport const contractCases = (declare: () => ServiceBuilder, options: ContractOptions = {}): ContractCase[] => {\n const degradeBy = options.degradeBy ?? 100;\n const seed = options.seed ?? 1;\n const description: ServiceDescription = declare().describe();\n const service = description.name;\n const gating = description.checks.filter((check) => check.gates !== null);\n const timingOf = (check: Check) => description.policies[check.gates!];\n const failMax = (check: Check): number => ms(failSpan(timingOf(check), check.poll, \"error\").max);\n const recoverMax = (check: Check): number => ms(recoverSpan(timingOf(check), check.poll).max);\n const most = (values: readonly number[]): number => values.reduce((a, b) => Math.max(a, b), 0);\n const settleTime = most(gating.filter((check) => check.gates === \"readiness\").map(recoverMax)) + 1;\n const quietTime = most(gating.map(failMax)) + 1;\n\n /** This function starts the declaration on a fake clock, and moves it to rest. */\n const boot = async (\n extra: (clock: FakeClock) => Partial<StartOptions> = () => ({}),\n ): Promise<{ health: Health; clock: FakeClock; rest: ReturnType<typeof visible> }> => {\n const clock = fakeClock();\n // the warm-up sweep can wait on the clock (a degraded check), thus the clock moves while it starts\n const starting = declare().start({ clock, random: seeded(seed), ...extra(clock) });\n let started = false;\n void starting.then(\n () => (started = true),\n () => (started = true),\n );\n for (let step = 0; step < 1000 && !started; step += 1) await clock.advance(10);\n const health = await starting;\n await clock.advance(settleTime);\n return { health, clock, rest: visible(health.verdict()) };\n };\n const stop = (health: Health): void => health.stop();\n\n const cases: ContractCase[] = [\n {\n name: `${service}: at rest, each controller and each dependency is ready, and the service is alive`,\n async run() {\n const { health, rest } = await boot();\n try {\n const expected = {\n ready: true,\n alive: true,\n controllers: Object.fromEntries(description.controllers.map((each) => [each.name, true])),\n dependencies: Object.fromEntries(description.dependencies.map((each) => [each.name, true])),\n };\n if (!same(expected, rest)) throw failure(\"at rest\", expected, rest);\n } finally {\n stop(health);\n }\n },\n },\n ];\n\n for (const dependency of description.dependencies) {\n const on = gating.filter((check) => check.dependency === dependency.name);\n const readiness = on.filter((check) => check.gates === \"readiness\");\n const liveness = on.filter((check) => check.gates === \"liveness\");\n const unavailable = (rest: ReturnType<typeof visible>) => ({\n ready: readiness.length === 0 ? rest.ready : false,\n alive: liveness.length === 0 ? rest.alive : false,\n controllers: Object.fromEntries(\n description.controllers.map((each) => [\n each.name,\n each.requires.includes(dependency.name) && readiness.length > 0 ? false : rest.controllers[each.name],\n ]),\n ),\n dependencies: { ...rest.dependencies, [dependency.name]: readiness.length === 0 },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} unavailable`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it fail`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n const now = visible(health.verdict());\n const expected = unavailable(rest);\n if (!same(expected, now)) throw failure(`${dependency.name} unavailable`, expected, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} degraded by ${degradeBy} ms, and nothing fails`,\n async run() {\n const tight = on.filter((check) => ms(check.poll.timeout) <= degradeBy);\n if (tight.length > 0)\n throw new Error(\n `${tight.map((check) => `${check.name} times out in ${ms(check.poll.timeout)} ms`).join(\", \")}: a latency of ${degradeBy} ms fails it`,\n );\n const { health, clock, rest } = await boot((at) => ({\n wrapCheck: (check, run) =>\n check.dependency !== dependency.name\n ? run\n : (signal) => new Promise((resolve) => at.after(degradeBy, () => resolve(run(signal)))),\n }));\n try {\n await clock.advance(quietTime + most(on.map((check) => ms(check.poll.interval))));\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} degraded`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} recovers`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it recover`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n health.forceFail(dependency.name, false);\n await clock.advance(most(on.map(recoverMax)) + 1);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} recovered`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n }\n\n const never = `${service}.client-never-registered`;\n cases.push({\n name: `${service}: a client never registered fails, and nothing changes (the negative control)`,\n async run() {\n if (description.dependencies.some((each) => each.name === never))\n throw new Error(`the declaration has a dependency named ${never}`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(never, true);\n await clock.advance(quietTime);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(\"the negative control\", rest, now);\n } finally {\n stop(health);\n }\n // and a check on a client never registered is refused before the start\n let refused = false;\n try {\n declare()\n .check({\n name: `${never}.check`,\n dependency: never,\n step: \"round-trip\",\n ownConnection: true,\n gates: null,\n poll: gating[0]?.poll ?? { interval: { value: 1, unit: \"s\" }, jitter: 0, timeout: { value: 0.5, unit: \"s\" } },\n })\n .describe();\n } catch {\n refused = true;\n }\n if (!refused) throw new Error(`the declaration accepted a check on ${never}, which is not a dependency`);\n },\n });\n\n return cases;\n};\n","import type { Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { ContractCase } from \"./contract.ts\";\nimport { fakeClock } from \"./fakes.ts\";\nimport type { Health } from \"./health.ts\";\nimport type { Lifecycle, TransportImpl } from \"./lifecycle.ts\";\n\n/** A held work is one unit of work that stays in flight until the test releases it. */\nexport interface HeldWork {\n /** This method lets the work end. Its promise ends when the caller of the work has its answer, or its error. */\n release(): Promise<void>;\n /** This flag tells if the work got the cooperative abort of the drain. */\n readonly aborted: boolean;\n}\n\n/**\n * A transport subject is a transport and the client side of its work. The kit offers work through\n * it, holds work in flight through it, and reads the count of the transport.\n */\nexport interface TransportSubject {\n readonly impl: TransportImpl;\n /** This lifecycle goes to `start()`. Without it, the kit gives a detached lifecycle. */\n readonly life?: Lifecycle | undefined;\n /** This method offers one unit of new work. It gives true when the transport took it, and false when it refused it. */\n offer(): Promise<boolean>;\n /** This method starts one unit of work that stays in flight until its release. The promise ends when the transport has it. */\n hold(): Promise<HeldWork>;\n /** This method frees what the subject holds outside the transport: its clients and their sockets. */\n dispose?(): Promise<void> | void;\n}\n\n/**\n * This function gives a detached lifecycle: a lifecycle with no service, for the start of a\n * transport in a test. Its state is `running`, it keeps each connection, and nothing is in flight. Each request\n * and each use of its health throws, because no service declares a route.\n */\nexport const detachedLifecycle = (): Lifecycle => {\n const none = (): never => {\n throw new Error(\"a detached lifecycle has no service: give the transport the lifecycle of a service\");\n };\n const health = { verdict: none, probe: none, metrics: none, subscribe: none, forceFail: none, drain: none, stop: none } as Health;\n return {\n health,\n state: \"running\",\n exitCode: null,\n errors: [],\n started: Promise.resolve(),\n done: new Promise<number>(() => {}),\n signal: new AbortController().signal,\n shutdown: none,\n request: none,\n inFlight: () => 0,\n keepAlive: () => true,\n };\n};\n\n/** A subject factory makes a new subject for each case, on the clock of the case. */\nexport type SubjectFactory = (clock: Clock) => TransportSubject | Promise<TransportSubject>;\n\n/** A conformance record is one measurement of a case, for the raw records of a run in CI. */\nexport interface ConformanceRecord {\n readonly case: string;\n readonly what: string;\n /** This time is the limit of the contract, in milliseconds. */\n readonly expected: number;\n /** This time is what the case measured, in milliseconds of the real clock. */\n readonly measured: number;\n}\n\n/** These options tune the conformance kit. */\nexport interface ConformanceOptions {\n /** This name goes before the name of each case. */\n readonly name?: string | undefined;\n /** This clock moves the cases: `fake` gives exact and fast cases, and `real` measures the timing. The default is `fake`. */\n readonly clock?: \"fake\" | \"real\" | undefined;\n /** This time is the cap of each drain of the cases, in milliseconds. The default is 1000. */\n readonly cap?: number | undefined;\n /** This time is the most that a close can take, in milliseconds of the real clock. The default is 1000. */\n readonly closeBound?: number | undefined;\n /** This time is the most that an event can take to reach the transport, in real milliseconds. The default is 100. */\n readonly slack?: number | undefined;\n /** False tells that the work of the transport cannot see the cooperative abort. The default is true. */\n readonly cooperative?: boolean | undefined;\n /** This count is the number of works that the count case holds. The default is 3. */\n readonly holds?: number | undefined;\n /** This function receives each measurement, for the raw records of a run. */\n readonly record?: ((record: ConformanceRecord) => void) | undefined;\n}\n\ninterface Time {\n readonly clock: Clock;\n pass(ms: number): Promise<void>;\n}\n\ninterface Tracked {\n readonly settled: boolean;\n readonly error: unknown;\n readonly failed: boolean;\n}\n\nconst realNow = (): number => performance.now();\nconst turn = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** This function waits on the real clock, until the test is true or the bound ends. It gives the test at the end. */\nconst within = async (bound: number, test: () => boolean): Promise<boolean> => {\n const end = realNow() + bound;\n for (;;) {\n if (test()) return true;\n if (realNow() > end) return test();\n await turn();\n }\n};\n\n/** This function lets the events that are ready reach the transport, with no move of the clock of the case. */\nconst quiet = async (): Promise<void> => {\n for (let at = 0; at < 8; at += 1) await turn();\n};\n\n/** This function uses a method of the transport, and gives a throw of the method as a rejection. */\nconst attempt = (call: () => Promise<void> | void): Promise<void> => {\n try {\n return Promise.resolve(call());\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nconst track = (promise: Promise<unknown>): Tracked => {\n const state = { settled: false, error: undefined as unknown, failed: false };\n promise.then(\n () => {\n state.settled = true;\n },\n (error: unknown) => {\n state.settled = true;\n state.failed = true;\n state.error = error;\n },\n );\n return state;\n};\n\n/**\n * This function generates the conformance cases of a transport (S6 A9). `make` gives a new subject\n * for each case. Each case throws on a failure, and its message names the part of the contract.\n * - The start: nothing is in flight, and the transport takes work.\n * - The count: it follows each work from its events, with no move of the clock.\n * - `stopIntake` refuses new work, keeps the work in flight, and a second stop has no effect.\n * - `drain` ends at once with no work, ends with the last work, and holds to its deadline and not\n * past it. It gives the cooperative abort to the work, and it does not throw.\n * - `close` ends the work in flight in its bound, and a second close has no effect.\n * - The stages in their sequence, as the lifecycle does them.\n */\nexport const transportConformance = (make: SubjectFactory, options: ConformanceOptions = {}): ContractCase[] => {\n const name = options.name ?? \"transport\";\n const fake = (options.clock ?? \"fake\") === \"fake\";\n const cap = options.cap ?? 1000;\n const closeBound = options.closeBound ?? 1000;\n const slack = options.slack ?? 100;\n const cooperative = options.cooperative ?? true;\n const holds = options.holds ?? 3;\n\n const timeOf = (): Time => {\n if (!fake) return { clock: realClock, pass: sleep };\n const clock = fakeClock();\n return { clock, pass: (ms) => clock.advance(ms) };\n };\n\n const check = (ok: boolean, what: string): void => {\n if (!ok) throw new Error(`${name}: ${what}`);\n };\n\n const each = (title: string, body: (subject: TransportSubject, time: Time, title: string) => Promise<void>): ContractCase => ({\n name: `${name}: ${title}`,\n async run() {\n const time = timeOf();\n const subject = await make(time.clock);\n try {\n await subject.impl.start(new AbortController().signal, subject.life ?? detachedLifecycle());\n await body(subject, time, title);\n } finally {\n try {\n await subject.impl.close();\n } finally {\n await subject.dispose?.();\n }\n }\n },\n });\n\n const count = (subject: TransportSubject, expected: number, what: string): Promise<void> =>\n within(slack, () => subject.impl.inFlight() === expected).then((ok) =>\n check(ok, `${what}: inFlight() gives ${subject.impl.inFlight()}, not ${expected}`),\n );\n\n const closes = async (subject: TransportSubject, title: string): Promise<void> => {\n const began = realNow();\n const closed = track(attempt(() => subject.impl.close()));\n const inBound = await within(closeBound, () => closed.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"close\", expected: closeBound, measured: took });\n check(inBound, `close did not end in its bound of ${closeBound} ms`);\n check(!closed.failed, `close threw: ${String(closed.error)}`);\n };\n\n const cases: ContractCase[] = [\n each(\"nothing is in flight after the start, and it takes new work\", async (subject) => {\n check(subject.impl.inFlight() === 0, `inFlight() gives ${subject.impl.inFlight()} after the start, not 0`);\n check(await subject.offer(), \"the transport refused new work after its start\");\n await count(subject, 0, \"the work ended\");\n }),\n\n each(\"the count follows each work in flight from its events, with no move of the clock\", async (subject) => {\n const held: HeldWork[] = [];\n for (let at = 1; at <= holds; at += 1) {\n held.push(await subject.hold());\n await count(subject, at, `${at} works are in flight`);\n }\n for (let at = holds - 1; at >= 0; at -= 1) {\n await held[at]!.release();\n await count(subject, at, `${at} works are in flight after a release`);\n }\n }),\n\n each(\"stopIntake refuses new work, keeps the work in flight, and a second stop has no effect\", async (subject) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n await count(subject, 1, \"stopIntake cut the work in flight\");\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after a second stopIntake\");\n await work.release();\n await count(subject, 0, \"the work in flight ended after stopIntake\");\n }),\n\n each(\"drain ends at once when nothing is in flight\", async (subject, time) => {\n await subject.impl.stopIntake();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, new AbortController().signal)));\n check(await within(slack, () => drained.settled), \"drain did not end with nothing in flight\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n }),\n\n each(\"drain ends when the last work ends, before its deadline\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n await time.pass(cap / 4);\n await quiet();\n check(!drained.settled, \"drain ended while work was in flight, before its deadline\");\n await work.release();\n check(await within(slack, () => drained.settled), \"drain did not end when the last work ended\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n check(time.clock.now() < deadline, \"drain waited until its deadline after the last work ended\");\n }),\n\n each(\"drain holds to its deadline and not past it, and does not throw\", async (subject, time, title) => {\n await subject.hold();\n await subject.impl.stopIntake();\n const began = realNow();\n const deadline = time.clock.now() + cap;\n const drained = track(attempt(() => subject.impl.drain(deadline, new AbortController().signal)));\n if (fake) {\n await time.pass(cap - 1);\n await quiet();\n check(!drained.settled, \"drain ended before its deadline, with work in flight\");\n await time.pass(1);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n } else {\n const ended = await within(cap + slack, () => drained.settled);\n const took = realNow() - began;\n options.record?.({ case: title, what: \"drain to its deadline\", expected: cap, measured: took });\n check(ended, `drain did not end in ${cap + slack} ms, with a deadline at ${cap} ms`);\n check(took >= cap - slack, `drain ended after ${Math.round(took)} ms, before its deadline at ${cap} ms`);\n }\n check(!drained.failed, `drain threw at its deadline: ${String(drained.error)}`);\n }),\n\n ...(cooperative\n ? [\n each(\"drain gives the cooperative abort to the work in flight\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await time.pass(cap / 2);\n await quiet();\n check(!work.aborted, \"the work got an abort before the signal of the drain aborted\");\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n check(await within(slack, () => work.aborted), \"the work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline after the cooperative abort\");\n check(!drained.failed, `drain threw after the cooperative abort: ${String(drained.error)}`);\n }),\n ]\n : []),\n\n each(\"drain with an aborted signal and a deadline in the past ends at once\", async (subject, time) => {\n const work = await subject.hold();\n await subject.impl.stopIntake();\n const abort = new AbortController();\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() - 1, abort.signal)));\n check(await within(slack, () => drained.settled), \"drain did not end at once with its deadline in the past\");\n check(!drained.failed, `drain threw: ${String(drained.error)}`);\n if (cooperative) check(await within(slack, () => work.aborted), \"the work did not get an abort that came before the drain\");\n }),\n\n each(\"close ends the work in flight, in its bound\", async (subject, _time, title) => {\n for (let at = 0; at < holds; at += 1) await subject.hold();\n await count(subject, holds, \"the works are in flight before the close\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n\n each(\"close is idempotent: a second close has no effect\", async (subject, _time, title) => {\n await subject.hold();\n const first = track(attempt(() => subject.impl.close()));\n const second = track(attempt(() => subject.impl.close()));\n check(await within(closeBound, () => first.settled && second.settled), \"two closes did not end in the bound\");\n check(!first.failed && !second.failed, `a close threw: ${String(first.error ?? second.error)}`);\n await closes(subject, title);\n await count(subject, 0, \"the closes left work in flight\");\n }),\n\n each(\"close right after the start ends in its bound\", async (subject, _time, title) => {\n await closes(subject, title);\n check(subject.impl.inFlight() === 0, \"inFlight() is not 0 after a close with no work\");\n }),\n\n each(\"the stages in their sequence: stop intake, drain with its cooperative abort, close\", async (subject, time, title) => {\n const short = await subject.hold();\n const long = await subject.hold();\n await subject.impl.stopIntake();\n check(!(await subject.offer()), \"the transport took new work after stopIntake\");\n const abort = new AbortController();\n const drained = track(attempt(() => subject.impl.drain(time.clock.now() + cap, abort.signal)));\n await short.release();\n await count(subject, 1, \"one work ended in the drain\");\n await time.pass(cap / 2);\n abort.abort(new Error(\"the cooperative abort of the conformance kit\"));\n if (cooperative) check(await within(slack, () => long.aborted), \"the long work did not get the cooperative abort\");\n await time.pass(cap / 2);\n check(await within(slack, () => drained.settled), \"drain did not end at its deadline\");\n await closes(subject, title);\n await count(subject, 0, \"close left work in flight\");\n }),\n ];\n return cases;\n};\n","import type { FakeClock } from \"../fakes.ts\";\nimport { fakeClock } from \"../fakes.ts\";\nimport type { Logger } from \"../logger.ts\";\nimport type { ChildHandle, CommandOptions, CommandResult, HostPorts, ProcessMark, SpawnRequest, StopSignal } from \"./ports.ts\";\n\n/** A fake child is a child process of a fake host. A test ends it, or a stop ends it. */\nexport interface FakeChild extends ChildHandle {\n readonly request: SpawnRequest;\n /** These are the messages that went on its IPC channel. */\n readonly sent: readonly unknown[];\n /** This flag tells if the child ended. */\n readonly ended: boolean;\n /** This method ends the child with a code, or with a signal and a null code. A second use does nothing. */\n exit(code: number | null, signal?: string | null): void;\n /** This method sends data on the output of the child. */\n output(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array): void;\n}\n\n/** A recorded command is one command that went through the fake command port. */\nexport interface RecordedCommand {\n readonly file: string;\n readonly args: readonly string[];\n readonly options: CommandOptions | undefined;\n}\n\n/** A recorded signal is one signal that went through the fake process port. */\nexport interface RecordedSignal {\n readonly pid: number;\n readonly signal: StopSignal;\n readonly group: boolean;\n}\n\n/** These options go with a fake host. */\nexport interface FakeHostOptions {\n /** This text is the platform. The default is `linux`. */\n readonly platform?: string | undefined;\n readonly env?: Readonly<Record<string, string | undefined>> | undefined;\n /** The default is `/home/test`. */\n readonly homeDir?: string | undefined;\n /** The default is `test`. */\n readonly user?: string | undefined;\n /** This record names the host process. The default is the ID 100, which started at the wall time 0. */\n readonly self?: ProcessMark | undefined;\n /** This time is the wall time at the clock time 0, in milliseconds after the epoch. The default is 1 000 000 000 000. */\n readonly wallStart?: number | undefined;\n /** These files are in the fake file system at the start. */\n readonly files?: Readonly<Record<string, string | Uint8Array>> | undefined;\n /**\n * This function gives the result of a command. When it gives undefined, the fake answers. `taskkill`\n * with `/F` ends the process and gives 0. `taskkill` without `/F` gives 1, or ends a polite child. Each other command gives 0.\n */\n readonly answer?: ((command: RecordedCommand) => CommandResult | undefined) | undefined;\n readonly logger?: Logger | undefined;\n}\n\n/**\n * A fake host is the host ports of a test, and the state behind them. It starts no process, writes no\n * file and installs no task. Each effect is a record or a change of its state.\n */\nexport interface FakeHost {\n readonly ports: HostPorts;\n readonly clock: FakeClock;\n /** These are the files of the fake file system. */\n readonly files: Map<string, string | Uint8Array>;\n readonly commands: RecordedCommand[];\n readonly signals: RecordedSignal[];\n readonly children: FakeChild[];\n /** This table holds each live process: its ID, and its start time or null. */\n readonly processes: Map<number, number | null>;\n /** This map gives the HTTP status of each address. An address that it does not have gives no answer. */\n readonly http: Map<string, number | null>;\n /** This set holds each `host:port` that takes a TCP connection. */\n readonly tcp: Set<string>;\n /** True makes each child end with the code 0 at a staged stop: SIGTERM, SIGINT, an IPC message or `taskkill` without `/F`. */\n polite: boolean;\n /** This function makes a file operation fail. It gets the name of the operation and the path. */\n failFiles: ((operation: string, path: string) => boolean) | null;\n /** This function makes a spawn fail, thus the child has no ID and ends. */\n failSpawn: ((request: SpawnRequest) => boolean) | null;\n /** This method gives the text of a file, or null. */\n text(path: string): string | null;\n /** This method lets the promises that are ready continue, without a move of the clock. */\n settle(): Promise<void>;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst bytesOf = (data: string | Uint8Array): Uint8Array => (typeof data === \"string\" ? encoder.encode(data) : data);\n\n/** This function makes a fake host. Give its `ports` to the host functions in a test. */\nexport const fakeHost = (options: FakeHostOptions = {}): FakeHost => {\n const clock = fakeClock();\n const wallStart = options.wallStart ?? 1_000_000_000_000;\n const wall = (): number => wallStart + clock.now();\n const self = options.self ?? { pid: 100, startedAt: wallStart };\n const files = new Map<string, string | Uint8Array>(Object.entries(options.files ?? {}));\n const commands: RecordedCommand[] = [];\n const signals: RecordedSignal[] = [];\n const children: FakeChild[] = [];\n const processes = new Map<number, number | null>([[self.pid, self.startedAt]]);\n const live = new Map<number, FakeChild>();\n let nextPid = 1000;\n\n const check = (operation: string, path: string): void => {\n if (host.failFiles?.(operation, path) === true) throw new Error(`the fake ${operation} of ${path} failed`);\n };\n\n const politeStop = (pid: number): void => {\n const child = live.get(pid);\n if (host.polite && child !== undefined) queueMicrotask(() => child.exit(0));\n };\n const hardStop = (pid: number, signal: string | null): void => {\n const child = live.get(pid);\n if (child !== undefined) queueMicrotask(() => child.exit(null, signal));\n else processes.delete(pid);\n };\n\n const spawn = (request: SpawnRequest): FakeChild => {\n const failed = host.failSpawn?.(request) === true;\n const pid = failed ? null : nextPid++;\n const outputs: Array<(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void> = [];\n const exits: Array<(code: number | null, signal: string | null) => void> = [];\n const sent: unknown[] = [];\n let end: { code: number | null; signal: string | null } | null = null;\n const child: FakeChild = {\n request,\n pid,\n ipc: request.ipc,\n sent,\n get ended() {\n return end !== null;\n },\n onOutput(handler) {\n outputs.push(handler);\n },\n onExit(handler) {\n exits.push(handler);\n if (end !== null) handler(end.code, end.signal);\n },\n send(message) {\n if (!request.ipc || end !== null) return false;\n sent.push(message);\n if (pid !== null) politeStop(pid);\n return true;\n },\n exit(code, signal = null) {\n if (end !== null) return;\n end = { code, signal };\n if (pid !== null) {\n processes.delete(pid);\n live.delete(pid);\n }\n for (const handler of exits) handler(code, signal);\n },\n output(stream, chunk) {\n for (const handler of outputs) handler(stream, chunk);\n },\n };\n children.push(child);\n if (pid === null) queueMicrotask(() => child.exit(null));\n else {\n processes.set(pid, wall());\n live.set(pid, child);\n }\n return child;\n };\n\n const signal = (pid: number, sig: StopSignal, group: boolean): boolean => {\n if (!processes.has(pid)) return false;\n signals.push({ pid, signal: sig, group });\n if (sig === \"SIGKILL\") hardStop(pid, \"SIGKILL\");\n else politeStop(pid);\n return true;\n };\n\n const defaultAnswer = (command: RecordedCommand): CommandResult => {\n if (command.file !== \"taskkill\") return { code: 0, out: \"\" };\n const at = command.args.indexOf(\"/PID\");\n const pid = Number(command.args[at + 1]);\n if (at < 0 || !processes.has(pid)) return { code: 128, out: `ERROR: The process \"${command.args[at + 1] ?? \"\"}\" not found.` };\n if (command.args.includes(\"/F\")) {\n hardStop(pid, null);\n return { code: 0, out: `SUCCESS: The process with PID ${pid} has been terminated.` };\n }\n if (host.polite && live.has(pid)) {\n politeStop(pid);\n return { code: 0, out: `SUCCESS: Sent termination signal to the process with PID ${pid}.` };\n }\n return { code: 1, out: `ERROR: The process with PID ${pid} could not be terminated.` };\n };\n\n const ports: HostPorts = {\n platform: options.platform ?? \"linux\",\n commands: {\n async run(file, args, commandOptions) {\n const command: RecordedCommand = { file, args: [...args], options: commandOptions };\n commands.push(command);\n return options.answer?.(command) ?? defaultAnswer(command);\n },\n },\n files: {\n async read(path) {\n check(\"read\", path);\n const data = files.get(path);\n return data === undefined ? null : typeof data === \"string\" ? data : decoder.decode(data);\n },\n async write(path, data) {\n check(\"write\", path);\n files.set(path, data);\n },\n async create(path, data) {\n check(\"create\", path);\n if (files.has(path)) return false;\n files.set(path, data);\n return true;\n },\n async append(path, data) {\n check(\"append\", path);\n const before = files.get(path);\n if (before === undefined) files.set(path, data);\n else if (typeof before === \"string\" && typeof data === \"string\") files.set(path, before + data);\n else {\n const head = bytesOf(before);\n const tail = bytesOf(data);\n const joined = new Uint8Array(head.length + tail.length);\n joined.set(head, 0);\n joined.set(tail, head.length);\n files.set(path, joined);\n }\n },\n async size(path) {\n check(\"size\", path);\n const data = files.get(path);\n return data === undefined ? null : bytesOf(data).length;\n },\n async rename(from, to) {\n check(\"rename\", from);\n const data = files.get(from);\n if (data === undefined) throw new Error(`the fake file ${from} does not exist`);\n files.delete(from);\n files.set(to, data);\n },\n async remove(path) {\n check(\"remove\", path);\n files.delete(path);\n },\n },\n processes: {\n alive: (pid) => processes.has(pid),\n startOf: async (pid) => processes.get(pid) ?? null,\n signal: (pid, sig) => signal(pid, sig, false),\n signalGroup: (pid, sig) => ports.platform !== \"win32\" && live.has(pid) && signal(pid, sig, true),\n spawn,\n },\n net: {\n httpStatus: async (url) => host.http.get(url) ?? null,\n tcpConnect: async (hostName, port) => host.tcp.has(`${hostName}:${port}`),\n },\n clock,\n wall,\n self,\n env: options.env ?? {},\n homeDir: options.homeDir ?? \"/home/test\",\n user: () => options.user ?? \"test\",\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n\n const host: FakeHost = {\n ports,\n clock,\n files,\n commands,\n signals,\n children,\n processes,\n http: new Map(),\n tcp: new Set(),\n polite: false,\n failFiles: null,\n failSpawn: null,\n text(path) {\n const data = files.get(path);\n return data === undefined ? null : typeof data === \"string\" ? data : decoder.decode(data);\n },\n async settle() {\n for (let turn = 0; turn < 2000; turn += 1) await Promise.resolve();\n },\n };\n return host;\n};\n","// @mark1russell7/service/testing: the seams of the runtime for tests. A fake clock gives exact,\n// repeatable timing. A seeded random gives the same jitter on each run. A fake process takes\n// signals and keeps the exit codes. A quiet server answers until it goes quiet, and then it holds\n// its connections open without an answer. A test logger keeps each log entry. `contractCases` generates the contract test of a\n// declaration, and `transportConformance` generates the conformance test of a transport. A fake host\n// gives the ports of the host entry, thus a test installs no task and starts no process.\n\nimport type { AddressInfo, Server, Socket } from \"node:net\";\nimport { createServer } from \"node:net\";\nimport type { Outcome } from \"./latch.ts\";\nimport type { LogEntry, LogLevel, Logger } from \"./logger.ts\";\nimport type { CheckFn } from \"./poller.ts\";\n\nexport type { FakeClock, FakeProcess, FakeProcessOptions } from \"./fakes.ts\";\nexport { fakeClock, fakeProcess, seeded } from \"./fakes.ts\";\nexport type { ContractCase, ContractOptions } from \"./contract.ts\";\nexport { contractCases } from \"./contract.ts\";\nexport type {\n ConformanceOptions,\n ConformanceRecord,\n HeldWork,\n SubjectFactory,\n TransportSubject,\n} from \"./conformance.ts\";\nexport { detachedLifecycle, transportConformance } from \"./conformance.ts\";\nexport type { FakeChild, FakeHost, FakeHostOptions, RecordedCommand, RecordedSignal } from \"./host/fakes.ts\";\nexport { fakeHost } from \"./host/fakes.ts\";\n\n/**\n * A behavior is what a scripted check does when the runtime starts it:\n * - `\"ok\"`, `\"error\"` and `\"indeterminate\"` give that outcome at once.\n * - `\"throw\"` throws at once.\n * - `\"timeout\"` gives no answer until the runtime aborts the use at the timeout of the poll.\n * - `\"hang\"` gives no answer, and it ignores the abort, until `heal()`.\n */\nexport type Behavior = Outcome | \"throw\" | \"timeout\" | \"hang\";\n\n/** A scripted check is a check function whose behavior a test sets. */\nexport interface ScriptedCheck {\n readonly run: CheckFn;\n /** This behavior applies to each later call. */\n behavior: Behavior;\n /** This count is the number of calls of the check. */\n readonly calls: number;\n /** This count is the number of calls that are pending. */\n readonly hung: number;\n /** This method ends each hung call with a pass, as when a driver gets its answer late. */\n heal(): void;\n}\n\n/** This function makes a scripted check with a behavior at the start. */\nexport const scriptedCheck = (behavior: Behavior = \"ok\"): ScriptedCheck => {\n let calls = 0;\n const hung = new Set<() => void>();\n const script: ScriptedCheck = {\n behavior,\n get calls() {\n return calls;\n },\n get hung() {\n return hung.size;\n },\n heal() {\n for (const end of [...hung]) end();\n },\n run: (signal) => {\n calls += 1;\n const now = script.behavior;\n if (now === \"throw\") throw new Error(\"the scripted check threw\");\n if (now === \"timeout\")\n return new Promise<Outcome>((_, reject) =>\n signal.addEventListener(\"abort\", () => reject(new Error(\"aborted at the timeout\"))),\n );\n if (now === \"hang\")\n return new Promise<Outcome>((resolve) => {\n const end = (): void => {\n hung.delete(end);\n resolve(\"ok\");\n };\n hung.add(end);\n });\n return now;\n },\n };\n return script;\n};\n\n/** A test logger is a logger that keeps each entry, thus a test can examine the log of the runtime. */\nexport interface TestLogger extends Logger {\n /** These are the entries, in the sequence of their calls. */\n readonly entries: readonly LogEntry[];\n /** This method gives the message of each entry, or of each entry at one level. */\n messages(level?: LogLevel): string[];\n /** This method removes each entry. */\n clear(): void;\n}\n\n/** This function makes a test logger with no entries. */\nexport const testLogger = (): TestLogger => {\n const entries: LogEntry[] = [];\n return {\n entries,\n log(level, message, fields) {\n entries.push({ level, message, fields });\n },\n messages: (level) => entries.filter((entry) => level === undefined || entry.level === level).map((entry) => entry.message),\n clear() {\n entries.length = 0;\n },\n };\n};\n\n/** A quiet server is a TCP echo server that can stop its answers and keep its connections open. */\nexport interface QuietServer {\n readonly port: number;\n /** This method stops the answers. The connections stay open, and the server reads and discards the data. */\n quiet(): void;\n /** This method starts the answers again. */\n speak(): void;\n /** This count is the number of open connections. */\n readonly connections: number;\n close(): Promise<void>;\n}\n\n/**\n * This function starts a quiet server on the loopback address. A check against it passes while it\n * answers. When it goes quiet, the check sees a connection that is open but silent. A frozen peer\n * and a black hole that keeps the connection look the same.\n */\nexport const quietServer = async (): Promise<QuietServer> => {\n let silent = false;\n const sockets = new Set<Socket>();\n const server: Server = createServer((socket) => {\n sockets.add(socket);\n socket.on(\"close\", () => sockets.delete(socket));\n socket.on(\"error\", () => sockets.delete(socket));\n socket.on(\"data\", (chunk) => {\n if (!silent) socket.write(chunk);\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n return {\n port: (server.address() as AddressInfo).port,\n quiet: () => {\n silent = true;\n },\n speak: () => {\n silent = false;\n },\n get connections() {\n return sockets.size;\n },\n close: () =>\n new Promise<void>((resolve) => {\n for (const socket of sockets) socket.destroy();\n server.close(() => resolve());\n }),\n };\n};\n"],"mappings":";;;;;;AAoBA,MAAM,SAAS,YAA2B;CACxC,KAAK,IAAI,OAAO,GAAG,OAAO,IAAI,QAAQ,GAAG,MAAM,QAAQ,QAA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AU,IAAI,IAAY;CAChC,MAAM,SAAiB,cAAc,WAAW;EAC9C,QAAQ,IAAI,MAAM;EAClB,OAAO,GAAG,eAAe,QAAQ,OAAO,MAAM,CAAC;EAC/C,OAAO,GAAG,eAAe,QAAQ,OAAO,MAAM,CAAC;EAC/C,OAAO,GAAG,SAAS,UAAU;GAC3B,IAAI,CAAC,QAAQ,OAAO,MAAM,KAAK;EACjC,CAAC;CACH,CAAC;CACD,MAAM,IAAI,SAAe,SAAS,WAAW;EAC3C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,GAAG,mBAAmB,QAAQ,CAAC;CAC/C,CAAC;CACD,OAAO;EACL,MAAO,OAAO,QAAQ,CAAC,CAAiB;EACxC,aAAa;GACX,SAAS;EACX;EACA,aAAa;GACX,SAAS;EACX;EACA,IAAI,cAAc;GAChB,OAAO,QAAQ;EACjB;EACA,aACE,IAAI,SAAe,YAAY;GAC7B,KAAK,MAAM,UAAU,SAAS,OAAO,QAAQ;GAC7C,OAAO,YAAY,QAAQ,CAAC;EAC9B,CAAC;CACL;AACF"}
|
package/build/websocket.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, m as RetrySchedule, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, x as retrySchedule, y as retryBackoff } from "./core-
|
|
3
|
-
import { n as statusLineJudge, t as Judge } from "./dial-
|
|
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, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, m as RetrySchedule, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, x as retrySchedule, y as retryBackoff } from "./core-B1zbS4WY.js";
|
|
3
|
+
import { n as statusLineJudge, t as Judge } from "./dial-CSGKVlZe.js";
|
|
4
4
|
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
5
5
|
import { Machine } from "@mark1russell7/algebra";
|
|
6
6
|
//#region src/websocket/connection.d.ts
|
package/build/websocket.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { realClock } from "./clock.js";
|
|
2
2
|
import { heartbeat } from "./heartbeat.js";
|
|
3
3
|
import { i as heartbeatDetection } from "./timing-DGRi3XCI.js";
|
|
4
|
-
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, i as authority, j as roundTripCheck, k as retryProblems, l as attachClient, m as dialCheck, n as closeTimer, o as statusLineJudge, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, w as operationTable, x as missesProblems, y as localStateCheck, z as wrapperTimerProblems } from "./machine-
|
|
4
|
+
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, i as authority, j as roundTripCheck, k as retryProblems, l as attachClient, m as dialCheck, n as closeTimer, o as statusLineJudge, q as keepaliveReset, r as transition, s as STARTING_POLL, t as clientKnob, u as clientBounds, w as operationTable, x as missesProblems, y as localStateCheck, z as wrapperTimerProblems } from "./machine-DKWLZOqu.js";
|
|
5
5
|
//#region src/websocket/connection.ts
|
|
6
6
|
/** This function gives a message of ws as one buffer. At the default `binaryType` of ws, a message is a buffer already. */
|
|
7
7
|
const asBuffer = (data) => {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/service",
|
|
4
|
-
"version": "0.6.
|
|
4
|
+
"version": "0.6.3",
|
|
5
5
|
"description": "A service declared as data before it starts, and its runtime: checks on jittered loops, a latch for each policy, probes from the cache, the startup in its sequence, and a staged, capped drain. The timer-ordering law checks the declaration. Its clock, heartbeat and backoff also work alone, in a browser too.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"service",
|
|
@@ -90,6 +90,10 @@
|
|
|
90
90
|
"types": "./build/rules.d.ts",
|
|
91
91
|
"default": "./build/rules.js"
|
|
92
92
|
},
|
|
93
|
+
"./host": {
|
|
94
|
+
"types": "./build/host.d.ts",
|
|
95
|
+
"default": "./build/host.js"
|
|
96
|
+
},
|
|
93
97
|
"./package.json": "./package.json"
|
|
94
98
|
},
|
|
95
99
|
"files": [
|
|
@@ -139,7 +143,7 @@
|
|
|
139
143
|
"devDependencies": {
|
|
140
144
|
"@grpc/grpc-js": "1.14.6",
|
|
141
145
|
"@mark1russell7/cue": "github:mark1russell7/cue",
|
|
142
|
-
"@mark1russell7/harness": "^0.
|
|
146
|
+
"@mark1russell7/harness": "^0.13.0",
|
|
143
147
|
"@types/node": "^26.6.4",
|
|
144
148
|
"ioredis": "6.0.0",
|
|
145
149
|
"testcontainers": "12.2.0",
|