@mark1russell7/harness 0.11.16 → 0.11.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/schema.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Y as Subject, i as ClientImage, r as Client, v as ImageSource } from "./cell-B6YHtKFb.js";
1
+ import { Q as Subject, i as ClientImage, r as Client, x as ImageSource } from "./cell-CcigQdUN.js";
2
2
  import { z } from "zod";
3
3
  //#region src/schema.d.ts
4
4
  /**
package/build/schema.js CHANGED
@@ -1,4 +1,4 @@
1
- import { S as subjectProblems, a as SHIPPED_NAMES, d as imageProblems, t as CLIENT_NAMES } from "./image-RM60Paqe.js";
1
+ import { a as SHIPPED_NAMES, p as imageProblems, t as CLIENT_NAMES, w as subjectProblems } from "./image-CNZbZPrd.js";
2
2
  import { z } from "zod";
3
3
  //#region src/schema.ts
4
4
  /** This function adds each problem that a check finds as an issue of a schema. */
@@ -1,6 +1,6 @@
1
1
  # The harness's RabbitMQ client: amqplib 2.2.0 on Node 24.21.0. It runs as a container in the client's
2
2
  # network namespace, as the harness's own TCP client does, and prints the same JSON lines, with the
3
- # events of the connection beside them.
3
+ # events of the connection beside them. The client of a cluster cell and the admin of its lab are here too.
4
4
  # lab.ts stages the build context: this folder, under harness/image/amqp. The lockfile is
5
5
  # npm-lock.json here, because npm leaves each package-lock.json out of a published tarball.
6
6
  FROM node:24.21.0-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1
@@ -8,4 +8,4 @@ WORKDIR /opt/harness/amqp
8
8
  COPY harness/image/amqp/package.json ./
9
9
  COPY harness/image/amqp/npm-lock.json ./package-lock.json
10
10
  RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund
11
- COPY harness/image/amqp/client-amqp.mjs ./
11
+ COPY harness/image/amqp/client-amqp.mjs harness/image/amqp/client-cluster.mjs harness/image/amqp/admin-cluster.mjs ./
@@ -0,0 +1,38 @@
1
+ // admin-cluster HOST:PORT declare|holds QUEUE
2
+ //
3
+ // The admin of the lab of a cluster cell of RabbitMQ: amqplib 2.2.0, as the user guest. It prints one
4
+ // JSON line with its result.
5
+ // - declare: declares the quorum queue on the node HOST, durable. Its leader locator is client-local,
6
+ // thus the member on HOST is the first leader. It prints { ok: true }.
7
+ // - holds: takes each message of the queue, and prints { held: [n, ...] }: the sequence numbers that
8
+ // the queue holds, in their order. The queue is empty after it.
9
+
10
+ const [at, command, queue] = process.argv.slice(2);
11
+ const print = (value) => process.stdout.write(`${JSON.stringify(value)}\n`);
12
+ if (at === undefined || queue === undefined || !["declare", "holds"].includes(command)) {
13
+ print({ ok: false, why: "admin-cluster HOST:PORT declare|holds QUEUE" });
14
+ process.exit(1);
15
+ }
16
+
17
+ const { default: amqp } = await import("amqplib");
18
+ const connection = await amqp.connect(`amqp://guest:guest@${at}/`);
19
+ const channel = await connection.createChannel();
20
+ try {
21
+ if (command === "declare") {
22
+ await channel.assertQueue(queue, { durable: true, arguments: { "x-queue-type": "quorum", "x-queue-leader-locator": "client-local" } });
23
+ print({ ok: true });
24
+ } else {
25
+ const held = [];
26
+ for (;;) {
27
+ const message = await channel.get(queue, { noAck: true });
28
+ if (message === false) break;
29
+ held.push(Number(message.content.toString()));
30
+ }
31
+ print({ held });
32
+ }
33
+ } catch (error) {
34
+ print({ ok: false, why: error.message });
35
+ process.exitCode = 1;
36
+ } finally {
37
+ await connection.close().catch(() => undefined);
38
+ }
@@ -0,0 +1,188 @@
1
+ // client-cluster HOSTS --queue NAME [--interval-ms N] [--max-s N] [--reconnect-ms N] [--options JSON]
2
+ //
3
+ // The client of a cluster cell of RabbitMQ: amqplib 2.2.0 on Node 24.21.0, as an application publishes
4
+ // with it. It publishes a stream of sequence numbers to one quorum queue on a confirm channel, one at
5
+ // a time, --interval-ms after the confirm of the one before. Each event is a JSON line with `ev` and
6
+ // `t`, the time on CLOCK_MONOTONIC in nanoseconds (process.hrtime, which libuv reads from it). The
7
+ // prober stamps the records of the kernel on the same clock, and the injector stamps each fault on it.
8
+ //
9
+ // HOSTS is host:port,host:port,... in the sequence of the connects: the first is the node of the
10
+ // client. amqplib connects to one node and does not connect again by itself. When the connection ends,
11
+ // this client connects to the next node of the list after --reconnect-ms (1000 ms), as an application
12
+ // does. Then it publishes again the sequence number that has no confirm.
13
+ //
14
+ // The options (--options JSON): `heartbeat` in seconds goes in the URL. Without it, amqplib takes the
15
+ // heartbeat that the broker proposes. `user` and `password` are the user of the broker: guest, as
16
+ // amqplib gives it, when the options name none.
17
+ //
18
+ // The lines:
19
+ // - start: the versions of amqplib and Node, the hosts and the options. clocks: the wall clock.
20
+ // - connecting: each connect, with its node. socket, socket-end, socket-error: the socket of each
21
+ // connection, with its local address and its node. connected: that socket.
22
+ // - connection, channel: each event of the connection (error, close, blocked, unblocked) and of the
23
+ // channel (error, close), with the error as data.
24
+ // - ready: the first channel is open, and the stream starts.
25
+ // - sent, ack, fail: each publish by its sequence number and the node that it went through. An ack is
26
+ // the confirm (basic.ack). A fail is a nack, or a channel that closed before the confirm.
27
+ // - done, deadline: the end of the client.
28
+
29
+ import { readFileSync } from "node:fs";
30
+
31
+ const now = () => process.hrtime.bigint();
32
+ const emit = (ev, fields = {}, at = now()) => process.stdout.write(`${JSON.stringify({ ev, t: Number(at), ...fields })}\n`);
33
+
34
+ const argv = process.argv.slice(2);
35
+ const flag = (name) => {
36
+ const at = argv.indexOf(name);
37
+ return at === -1 ? undefined : argv[at + 1];
38
+ };
39
+ const hosts = (argv[0] ?? "").split(",").filter((each) => each !== "");
40
+ const queue = flag("--queue");
41
+ if (hosts.length === 0 || queue === undefined) {
42
+ emit("fail", { why: "client-cluster HOST:PORT,... --queue NAME" });
43
+ process.exit(1);
44
+ }
45
+ const interval = Number(flag("--interval-ms") ?? 50);
46
+ const max = Number(flag("--max-s") ?? 120) * 1000;
47
+ const reconnect = Number(flag("--reconnect-ms") ?? 1000);
48
+ const options = JSON.parse(flag("--options") ?? "{}");
49
+ const { heartbeat, user = "guest", password = "guest" } = options;
50
+
51
+ const { default: amqp } = await import("amqplib");
52
+ const versionOf = (name) => JSON.parse(readFileSync(new URL(`./node_modules/${name}/package.json`, import.meta.url), "utf8")).version;
53
+ const bootId = () => {
54
+ try {
55
+ return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
56
+ } catch {
57
+ return null;
58
+ }
59
+ };
60
+ emit("start", { boot_id: bootId(), client: "amqp-cluster", driver: versionOf("amqplib"), node: process.versions.node, hosts, queue, options });
61
+ // the wall clock beside the monotonic one: the run puts the log lines of the nodes on the monotonic clock
62
+ const clocks = () => emit("clocks", { real: Date.now() });
63
+ clocks();
64
+ setInterval(clocks, 1000).unref();
65
+
66
+ const urlOf = (at) => `amqp://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${at}/${heartbeat === undefined ? "" : `?heartbeat=${heartbeat}`}`;
67
+ const failure = (error) => (error === undefined || error === null ? null : { name: error.name, code: error.code ?? null, message: error.message });
68
+ const errnoOf = (error) => error?.code ?? error?.message ?? null;
69
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
70
+
71
+ let stopped = false;
72
+ let connection = null;
73
+ let channel = null;
74
+ // the node of the connection that is open now, and the place of the next connect in the list
75
+ let at = null;
76
+ let next = 0;
77
+ // this promise ends when the connection that is open now ends
78
+ let ended = null;
79
+
80
+ /** This function connects to the next node of the list and opens a confirm channel. It gives false when the connect fails. */
81
+ const open = async () => {
82
+ const node = hosts[next % hosts.length];
83
+ next += 1;
84
+ emit("connecting", { at: node });
85
+ try {
86
+ connection = await amqp.connect(urlOf(node));
87
+ } catch (error) {
88
+ emit("connection", { event: "connect-failed", at: node, errno: errnoOf(error), failure: failure(error) });
89
+ return false;
90
+ }
91
+ const socket = connection.connection.stream;
92
+ const local = `${socket.localAddress}:${socket.localPort}`;
93
+ emit("socket", { role: "connection", local, server: node });
94
+ emit("connected", { local, at: node });
95
+ socket.once("close", (hadError) => emit("socket-end", { role: "connection", local, server: node, error: hadError }));
96
+ socket.once("error", (error) => emit("socket-error", { role: "connection", local, server: node, errno: errnoOf(error), message: error.message }));
97
+ let finish;
98
+ ended = new Promise((resolve) => (finish = resolve));
99
+ // amqplib emits each error once, then its close. Without a listener, Node throws the error
100
+ connection.on("error", (error) => emit("connection", { event: "error", at: node, failure: failure(error) }));
101
+ // a close of the broker with 320 (CONNECTION_FORCED) is not an error for amqplib: only its close tells
102
+ connection.on("close", (error) => {
103
+ emit("connection", { event: "close", at: node, failure: failure(error) });
104
+ finish();
105
+ });
106
+ connection.on("blocked", (reason) => emit("connection", { event: "blocked", at: node, reason }));
107
+ connection.on("unblocked", () => emit("connection", { event: "unblocked", at: node }));
108
+ try {
109
+ channel = await connection.createConfirmChannel();
110
+ } catch (error) {
111
+ emit("channel", { event: "open-failed", at: node, failure: failure(error) });
112
+ return false;
113
+ }
114
+ channel.on("error", (error) => emit("channel", { event: "error", at: node, failure: failure(error) }));
115
+ channel.on("close", () => emit("channel", { event: "close", at: node }));
116
+ at = node;
117
+ return true;
118
+ };
119
+
120
+ /** This function publishes n and waits for its confirm. It gives null for a confirm, or the error. */
121
+ const publish = (n) =>
122
+ new Promise((resolve) => {
123
+ const through = at;
124
+ emit("sent", { n, at: through });
125
+ try {
126
+ channel.sendToQueue(queue, Buffer.from(String(n)), { persistent: true }, (error) => {
127
+ if (error === null || error === undefined) {
128
+ emit("ack", { n, at: through });
129
+ resolve(null);
130
+ } else {
131
+ emit("fail", { n, at: through, ...failure(error) });
132
+ resolve(error);
133
+ }
134
+ });
135
+ } catch (error) {
136
+ emit("fail", { n, at: through, ...failure(error) });
137
+ resolve(error);
138
+ }
139
+ });
140
+
141
+ const stop = (code = 0) => {
142
+ if (stopped) return;
143
+ stopped = true;
144
+ emit("done");
145
+ const closing = connection === null ? Promise.resolve() : connection.close().catch(() => undefined);
146
+ // a dead connection does not answer its close: the client does not wait for it
147
+ Promise.race([closing, new Promise((resolve) => setTimeout(resolve, 1000))]).finally(() => setTimeout(() => process.exit(code), 50));
148
+ };
149
+ process.on("SIGTERM", () => stop(0));
150
+ setTimeout(() => {
151
+ emit("deadline");
152
+ stop(0);
153
+ }, max);
154
+
155
+ let ready = false;
156
+ let n = 1;
157
+ while (!stopped) {
158
+ if (channel === null) {
159
+ if (!(await open())) {
160
+ channel = null;
161
+ await sleep(reconnect);
162
+ continue;
163
+ }
164
+ if (!ready) {
165
+ ready = true;
166
+ emit("ready", { at });
167
+ }
168
+ }
169
+ // a publish ends at its confirm, at a nack, or at the close of its channel
170
+ const failed = await publish(n);
171
+ if (failed === null) {
172
+ n += 1;
173
+ await sleep(interval);
174
+ continue;
175
+ }
176
+ // the same sequence number goes again: on the same channel after a nack, or on the next node after an end
177
+ if (failed.message === "message nacked") {
178
+ await sleep(interval);
179
+ continue;
180
+ }
181
+ // the channel closed: its connection ends with it, or after one more wait the client ends the connection
182
+ const closing = connection;
183
+ await Promise.race([ended, sleep(reconnect)]);
184
+ closing?.close().catch(() => undefined);
185
+ channel = null;
186
+ connection = null;
187
+ if (!stopped) await sleep(reconnect);
188
+ }
@@ -0,0 +1,9 @@
1
+ # The etcd target of the harness: etcd v3.6.15 from its image, pinned by digest, on Alpine. The image of
2
+ # etcd is distroless: it has no shell. A cell holds the server as the child of a shell, thus a `fin`
3
+ # can stop it with SIGKILL while the container stays up, and a sidecar can freeze it by its name.
4
+ # The binaries are the ones of the image of etcd, unchanged.
5
+ # lab.ts stages the build context: this folder, under harness/image/etcd.
6
+ FROM quay.io/coreos/etcd:v3.6.15@sha256:7cf6622cb09b111289eed8a0cce3478e4f01d5048b0e0a1ed208299f3419334d AS etcd
7
+
8
+ FROM alpine:3.22@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8
9
+ COPY --from=etcd /usr/local/bin/etcd /usr/local/bin/etcdctl /usr/local/bin/
@@ -0,0 +1,11 @@
1
+ # The harness's gRPC client: grpc-js 1.14.6 on Node 24.21.0. It runs as a container in the client's
2
+ # network namespace, as the harness's own TCP client does, and prints the same JSON lines, with the
3
+ # sockets and the connectivity states of the channel beside them.
4
+ # lab.ts stages the build context: this folder, under harness/image/grpc. The lockfile is
5
+ # npm-lock.json here, because npm leaves each package-lock.json out of a published tarball.
6
+ FROM node:24.21.0-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1
7
+ WORKDIR /opt/harness/grpc
8
+ COPY harness/image/grpc/package.json ./
9
+ COPY harness/image/grpc/npm-lock.json ./package-lock.json
10
+ RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund
11
+ COPY harness/image/grpc/client-grpc.mjs ./
@@ -0,0 +1,257 @@
1
+ // client-grpc HOST PORT --mode idle|inflight|stream [--interval-ms N] [--max-s N] [--go PATH] [--before]
2
+ // [--options JSON] [--hold-ms N] [--op check|watch]
3
+ //
4
+ // The client of a gRPC cell: grpc-js 1.14.6 on Node 24.21.0, with one channel to one server and no TLS.
5
+ // Each event is a JSON line with `ev` and `t`, the time on CLOCK_MONOTONIC in nanoseconds
6
+ // (process.hrtime, which libuv reads from it). The prober stamps the records of the kernel on the
7
+ // same clock, and the injector stamps each fault on it.
8
+ //
9
+ // Each operation is a unary call of grpc.health.v1.Health/Check, with no deadline and no
10
+ // waitForReady at the defaults: the health service of grpc-go and of etcd answers at once with
11
+ // SERVING. The messages are encoded here: a HealthCheckRequest has one string (field 1), and a
12
+ // HealthCheckResponse has one enum (field 1). Operation 1 makes the connection: the channel connects
13
+ // at its first call. With --hold-ms, the call in flight asks for the service `hold:<ms>`, and the
14
+ // server of the harness holds its reply for that time. Another server answers NOT_FOUND to it.
15
+ // With --op watch, the operation in flight is a stream of grpc.health.v1.Health/Watch. The server sends
16
+ // SERVING, and the stream stays open: a stream for the policy of a server for the PINGs of a client.
17
+ //
18
+ // The options (--options JSON): each name that starts with `grpc.` is a channel option of grpc-js,
19
+ // for example grpc.keepalive_time_ms. `deadline_ms` is the deadline of each call.
20
+ //
21
+ // The lines:
22
+ // - start: the versions of grpc-js and Node, the mode and the options.
23
+ // - connecting: the start of operation 1. Its stamp is the stamp of the first sent line.
24
+ // - socket, socket-eof, socket-end, socket-error: each TCP socket of the channel, with its local
25
+ // address. connect-error: a connect that failed, with its error.
26
+ // - connected: the first of them. The TCP client of the harness names its own socket so.
27
+ // - state: each change of the connectivity state of the channel.
28
+ // - log: a line that grpc-js logs, for example the refusal of its PINGs by the server. That refusal
29
+ // (a GOAWAY with too_many_pings) is the cause of the end of the connection: its errno is too_many_pings.
30
+ // - watch-data: each message of the stream of a Watch.
31
+ // - ready: the reply to operation 1: the channel is idle (idle, inflight), or the stream starts.
32
+ // - sent, ack, fail: each operation by its sequence number, with its status.
33
+ // - data, error: the end of the operation in flight, as the TCP client of the harness tells it. In
34
+ // idle mode, the first end of the connected socket is an error line too. The errno of an error
35
+ // line is the error of the socket when it has one (ECONNRESET), EOF for an end of the socket by
36
+ // the server, or the status of the call (UNAVAILABLE).
37
+ // - done, deadline: the end of the client.
38
+ //
39
+ // The modes: idle does operation 1, then holds until --max-s. inflight does operation 1, waits for
40
+ // the file --go, does one more operation into the fault, and holds after its end. stream does an
41
+ // operation each --interval-ms after the end of the one before, until --max-s or SIGTERM: grpc-js
42
+ // connects again by itself, thus the stream goes on after a failed call. --before starts the client
43
+ // into a fault that holds already: its connect meets it.
44
+
45
+ import { existsSync, readFileSync } from "node:fs";
46
+ import net from "node:net";
47
+
48
+ const now = () => process.hrtime.bigint();
49
+ const emit = (ev, fields = {}, at = now()) => process.stdout.write(`${JSON.stringify({ ev, t: Number(at), ...fields })}\n`);
50
+
51
+ const argv = process.argv.slice(2);
52
+ const flag = (name) => {
53
+ const at = argv.indexOf(name);
54
+ return at === -1 ? undefined : argv[at + 1];
55
+ };
56
+ const [host, port] = argv;
57
+ const mode = flag("--mode");
58
+ if (host === undefined || port === undefined || !["idle", "inflight", "stream"].includes(mode)) {
59
+ emit("fail", { why: "client-grpc HOST PORT --mode idle|inflight|stream" });
60
+ process.exit(1);
61
+ }
62
+ const interval = Number(flag("--interval-ms") ?? 50);
63
+ const max = Number(flag("--max-s") ?? 120) * 1000;
64
+ const go = flag("--go") ?? "/tmp/go";
65
+ const before = argv.includes("--before");
66
+ const hold = flag("--hold-ms");
67
+ const op = flag("--op") ?? "check";
68
+ if (op !== "check" && op !== "watch") {
69
+ emit("fail", { why: "--op check|watch" });
70
+ process.exit(1);
71
+ }
72
+ // the options of the channel. A cell gives each option that it changes, and grpc-js gives the others
73
+ const options = JSON.parse(flag("--options") ?? "{}");
74
+ const { deadline_ms: deadlineMs, ...channelOptions } = options;
75
+ const unknown = Object.keys(channelOptions).filter((name) => !name.startsWith("grpc.") && !name.startsWith("grpc-node."));
76
+ if (unknown.length > 0) {
77
+ emit("fail", { why: `options that are not channel options of grpc-js: ${unknown.join(", ")}` });
78
+ process.exit(1);
79
+ }
80
+
81
+ // ---- each TCP socket of the channel: grpc-js connects with net.connect (transport.ts:830), on the
82
+ // module object that this patch changes. It loads after the patch
83
+ let connected = null;
84
+ // the first end of the connected socket: the cause of the end of the call in flight
85
+ let cause = null;
86
+ const connect = net.connect;
87
+ net.connect = function (...args) {
88
+ const socket = connect.apply(this, args);
89
+ let established = false;
90
+ socket.once("connect", () => {
91
+ established = true;
92
+ const local = `${socket.localAddress}:${socket.localPort}`;
93
+ emit("socket", { role: "connection", local });
94
+ const first = connected === null;
95
+ if (first) {
96
+ connected = local;
97
+ emit("connected", { local });
98
+ }
99
+ let failed = null;
100
+ socket.once("error", (error) => {
101
+ failed = error.code ?? error.errno ?? error.message;
102
+ emit("socket-error", { role: "connection", local, errno: failed, message: error.message });
103
+ });
104
+ socket.once("end", () => emit("socket-eof", { role: "connection", local }));
105
+ socket.once("close", (hadError) => {
106
+ emit("socket-end", { role: "connection", local, error: hadError });
107
+ if (!first || cause !== null || stopped) return;
108
+ // the end of the connected socket: an error of its own, the end by the server, or the end by grpc-js
109
+ cause = { errno: failed ?? (socket.readableEnded ? "EOF" : "CLOSED") };
110
+ if (mode === "idle") emit("error", { errno: cause.errno });
111
+ });
112
+ });
113
+ // a connect that fails: the reset of the SYN, or a give-up of the kernel. The socket has no
114
+ // connection, thus its line is not a socket line
115
+ socket.once("error", (error) => {
116
+ if (!established) emit("connect-error", { errno: error.code ?? error.errno ?? null, message: error.message });
117
+ });
118
+ return socket;
119
+ };
120
+
121
+ const grpc = await import("@grpc/grpc-js");
122
+ const version = JSON.parse(readFileSync(new URL("./node_modules/@grpc/grpc-js/package.json", import.meta.url), "utf8")).version;
123
+ // each line that grpc-js logs, with no trace: an error of a subchannel, or the doubled keepalive after
124
+ // too_many_pings. grpc-js logs that refusal when the GOAWAY comes, before the end of the socket (subchannel.ts:280-289)
125
+ grpc.setLogger({
126
+ error: (...parts) => {
127
+ const text = parts.map(String).join(" ");
128
+ emit("log", { text });
129
+ if (/excess pings/.test(text) && cause === null && !stopped) {
130
+ cause = { errno: "too_many_pings" };
131
+ if (mode === "idle") emit("error", { errno: cause.errno });
132
+ }
133
+ },
134
+ });
135
+ grpc.setLogVerbosity(grpc.logVerbosity.ERROR);
136
+
137
+ const bootId = () => {
138
+ try {
139
+ return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
140
+ } catch {
141
+ return null;
142
+ }
143
+ };
144
+ emit("start", { boot_id: bootId(), client: "grpc", driver: version, node: process.versions.node, mode, op, options, hold: hold === undefined ? null : Number(hold) });
145
+
146
+ // ---- the messages of grpc.health.v1, encoded by hand
147
+ const encodeRequest = (service) => {
148
+ const bytes = Buffer.from(service, "utf8");
149
+ if (bytes.length > 127) throw new Error("a service name of more than 127 bytes");
150
+ return bytes.length === 0 ? Buffer.alloc(0) : Buffer.concat([Buffer.from([0x0a, bytes.length]), bytes]);
151
+ };
152
+ const SERVING = ["UNKNOWN", "SERVING", "NOT_SERVING", "SERVICE_UNKNOWN"];
153
+ const decodeResponse = (buffer) => ({ status: buffer.length >= 2 && buffer[0] === 0x08 ? (SERVING[buffer[1]] ?? buffer[1]) : "UNKNOWN" });
154
+
155
+ const client = new grpc.Client(`${host}:${port}`, grpc.credentials.createInsecure(), channelOptions);
156
+ const channel = client.getChannel();
157
+ const STATES = ["IDLE", "CONNECTING", "READY", "TRANSIENT_FAILURE", "SHUTDOWN"];
158
+ const watch = (state) =>
159
+ channel.watchConnectivityState(state, Infinity, () => {
160
+ const next = channel.getConnectivityState(false);
161
+ emit("state", { from: STATES[state], to: STATES[next] });
162
+ if (next !== grpc.connectivityState.SHUTDOWN) watch(next);
163
+ });
164
+ watch(channel.getConnectivityState(false));
165
+
166
+ /** This function gives the status of a failed call as data: its code, its name and its details. */
167
+ const failure = (error) => ({ code: error.code ?? null, name: grpc.status[error.code] ?? null, details: error.details ?? error.message });
168
+
169
+ // ---- the end of the client
170
+ let stopped = false;
171
+ const stop = (code = 0) => {
172
+ if (stopped) return;
173
+ stopped = true;
174
+ emit("done");
175
+ client.close();
176
+ setTimeout(() => process.exit(code), 50);
177
+ };
178
+ process.on("SIGTERM", () => stop(0));
179
+ setTimeout(() => {
180
+ emit("deadline");
181
+ stop(0);
182
+ }, max);
183
+
184
+ /** This function does operation n. Its stamp is before the call. It gives null for a reply, or the error. */
185
+ const operate = (n, service = "") =>
186
+ new Promise((resolve) => {
187
+ const at = now();
188
+ // a band of a cell that starts into a fault counts from the start of the connect
189
+ if (n === 1) emit("connecting", { at: `${host}:${port}` }, at);
190
+ emit("sent", { n, service }, at);
191
+ const callOptions = deadlineMs === undefined ? {} : { deadline: Date.now() + deadlineMs };
192
+ client.makeUnaryRequest("/grpc.health.v1.Health/Check", encodeRequest, decodeResponse, service, new grpc.Metadata(), callOptions, (error, reply) => {
193
+ if (error === null || error === undefined) {
194
+ emit("ack", { n, status: reply.status });
195
+ resolve(null);
196
+ } else {
197
+ emit("fail", { n, ...failure(error) });
198
+ resolve(error);
199
+ }
200
+ });
201
+ });
202
+
203
+ /** This function opens the stream of a Watch as operation n. It gives null when the server ends the stream, or the error. */
204
+ const watchOf = (n) =>
205
+ new Promise((resolve) => {
206
+ emit("sent", { n, op: "watch" });
207
+ const stream = client.makeServerStreamRequest("/grpc.health.v1.Health/Watch", encodeRequest, decodeResponse, "", new grpc.Metadata(), {});
208
+ stream.on("data", (reply) => emit("watch-data", { n, status: reply.status }));
209
+ stream.on("error", (error) => {
210
+ emit("fail", { n, ...failure(error) });
211
+ resolve(error);
212
+ });
213
+ stream.on("end", () => {
214
+ emit("ack", { n });
215
+ resolve(null);
216
+ });
217
+ });
218
+
219
+ /** This function gives the errno of the end of a call: the end of its socket when it has one, else its status. */
220
+ const errnoOf = (error) => cause?.errno ?? grpc.status[error.code] ?? error.message;
221
+
222
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
223
+
224
+ if (mode === "stream") {
225
+ const failed = await operate(1);
226
+ if (failed === null) {
227
+ emit("ready", { at: `${host}:${port}` });
228
+ for (let n = 2; !stopped; n += 1) {
229
+ await operate(n);
230
+ await sleep(interval);
231
+ }
232
+ } else {
233
+ emit("error", { errno: errnoOf(failed), message: failed.details ?? failed.message });
234
+ stop(1);
235
+ }
236
+ } else {
237
+ // operation 1 makes the connection. Its reply is the last data before the fault
238
+ const failed = await operate(1);
239
+ if (failed !== null) {
240
+ emit("error", { errno: errnoOf(failed), message: failed.details ?? failed.message });
241
+ stop(before ? 0 : 1);
242
+ } else {
243
+ emit("ready", { reply: "ack" });
244
+ if (mode === "inflight") {
245
+ await new Promise((resolve) => {
246
+ const wait = setInterval(() => {
247
+ if (!existsSync(go)) return;
248
+ clearInterval(wait);
249
+ resolve();
250
+ }, 2);
251
+ });
252
+ const error = op === "watch" ? await watchOf(2) : await operate(2, hold === undefined ? "" : `hold:${hold}`);
253
+ if (error === null) emit("data", { n: 2 });
254
+ else emit("error", { errno: errnoOf(error), message: error.details ?? error.message });
255
+ }
256
+ }
257
+ }