@ricsam/r5d-worker 0.0.107 → 0.0.109

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.
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var recovery_store_exports = {};
30
+ __export(recovery_store_exports, {
31
+ WorkerRecoveryStore: () => WorkerRecoveryStore,
32
+ workerOperationDigest: () => workerOperationDigest
33
+ });
34
+ module.exports = __toCommonJS(recovery_store_exports);
35
+ var import_bun_sqlite = require("bun:sqlite");
36
+ var import_node_fs = __toESM(require("node:fs"), 1);
37
+ var import_node_path = __toESM(require("node:path"), 1);
38
+ var import_node_crypto = require("node:crypto");
39
+ function workerOperationDigest(message) {
40
+ const canonical = (value) => {
41
+ if (Array.isArray(value)) return value.map(canonical);
42
+ if (value && typeof value === "object")
43
+ return Object.fromEntries(
44
+ Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])
45
+ );
46
+ return value;
47
+ };
48
+ const { requestId: _requestId, ...identity } = message;
49
+ return (0, import_node_crypto.createHash)("sha256").update(JSON.stringify(canonical(identity))).digest("hex");
50
+ }
51
+ class WorkerRecoveryStore {
52
+ db;
53
+ ledgerId;
54
+ constructor(filename) {
55
+ import_node_fs.default.mkdirSync(import_node_path.default.dirname(filename), { recursive: true, mode: 448 });
56
+ this.db = new import_bun_sqlite.Database(filename, { create: true });
57
+ import_node_fs.default.chmodSync(filename, 384);
58
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
59
+ CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
60
+ CREATE TABLE IF NOT EXISTS operations (request_id TEXT PRIMARY KEY, run_id TEXT, session_id TEXT, request_type TEXT NOT NULL, digest TEXT NOT NULL, state TEXT NOT NULL, response TEXT);
61
+ CREATE UNIQUE INDEX IF NOT EXISTS operation_run_start ON operations(run_id) WHERE request_type='exec_start';
62
+ CREATE TABLE IF NOT EXISTS aliases (request_id TEXT PRIMARY KEY, operation_id TEXT NOT NULL);
63
+ CREATE TABLE IF NOT EXISTS streams (run_id TEXT NOT NULL, stream TEXT NOT NULL, bytes INTEGER NOT NULL DEFAULT 0, acknowledged INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(run_id, stream));
64
+ CREATE TABLE IF NOT EXISTS output (run_id TEXT NOT NULL, stream TEXT NOT NULL, offset INTEGER NOT NULL, bytes INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY(run_id, stream, offset));
65
+ CREATE TABLE IF NOT EXISTS terminals (run_id TEXT PRIMARY KEY, message TEXT NOT NULL);
66
+ CREATE TABLE IF NOT EXISTS cancelled_requests (request_id TEXT PRIMARY KEY);
67
+ `);
68
+ this.db.run("INSERT OR IGNORE INTO metadata(key,value) VALUES ('ledgerId',?)", [crypto.randomUUID()]);
69
+ this.ledgerId = this.db.query("SELECT value FROM metadata WHERE key='ledgerId'").get().value;
70
+ this.db.run("UPDATE operations SET state='unknown' WHERE state IN ('accepted','preparing','running')");
71
+ }
72
+ close() {
73
+ this.db.close();
74
+ }
75
+ row(requestId) {
76
+ return this.db.query("SELECT * FROM operations WHERE request_id=? OR request_id=(SELECT operation_id FROM aliases WHERE request_id=?)").get(requestId, requestId);
77
+ }
78
+ admit(message) {
79
+ const digest = workerOperationDigest(message);
80
+ let existing = this.row(message.requestId);
81
+ if (!existing && message.type === "exec_start" && typeof message.runId === "string")
82
+ existing = this.db.query("SELECT * FROM operations WHERE run_id=? AND request_type='exec_start'").get(message.runId);
83
+ if (existing) {
84
+ if (existing.digest !== digest) return "conflict";
85
+ this.db.run("INSERT OR IGNORE INTO aliases(request_id, operation_id) VALUES (?,?)", [message.requestId, existing.request_id]);
86
+ return existing.state === "unknown" ? "unknown" : "duplicate";
87
+ }
88
+ this.db.run("INSERT INTO operations(request_id, run_id, session_id, request_type, digest, state) VALUES (?,?,?,?,?,'accepted')", [
89
+ message.requestId,
90
+ typeof message.runId === "string" ? message.runId : null,
91
+ typeof message.sessionId === "string" ? message.sessionId : null,
92
+ message.type,
93
+ digest
94
+ ]);
95
+ return "new";
96
+ }
97
+ isUnknown(requestId) {
98
+ return this.row(requestId)?.state === "unknown";
99
+ }
100
+ unknown(requestId) {
101
+ const row = this.row(requestId);
102
+ if (row) this.db.run("UPDATE operations SET state='unknown' WHERE request_id=?", [row.request_id]);
103
+ }
104
+ unknownRun(runId) {
105
+ this.db.run("UPDATE operations SET state='unknown' WHERE run_id=? AND request_type IN ('exec_start','exec')", [runId]);
106
+ }
107
+ record(message) {
108
+ if (message.type === "exec_output" && typeof message.runId === "string" && (message.stream === "stdout" || message.stream === "stderr") && typeof message.data === "string") {
109
+ const runId = message.runId, stream = message.stream, data = message.data;
110
+ const offset = this.db.transaction(() => {
111
+ this.db.run("INSERT OR IGNORE INTO streams(run_id, stream) VALUES (?,?)", [runId, stream]);
112
+ const offset2 = this.db.query("SELECT bytes FROM streams WHERE run_id=? AND stream=?").get(runId, stream).bytes;
113
+ const bytes = Buffer.byteLength(data);
114
+ if (bytes) {
115
+ this.db.run("INSERT INTO output(run_id, stream, offset, bytes, data) VALUES (?,?,?,?,?)", [runId, stream, offset2, bytes, data]);
116
+ this.db.run("UPDATE streams SET bytes=bytes+? WHERE run_id=? AND stream=?", [bytes, runId, stream]);
117
+ }
118
+ return offset2;
119
+ })();
120
+ return { ...message, offset };
121
+ }
122
+ if ((message.type === "exec_exit" || message.type === "exec_error") && typeof message.runId === "string") {
123
+ const terminal = { ...message, ...this.lengths(message.runId) };
124
+ this.db.transaction(() => {
125
+ this.db.run("INSERT OR REPLACE INTO terminals(run_id,message) VALUES (?,?)", [message.runId, JSON.stringify(terminal)]);
126
+ this.db.run("UPDATE operations SET state='completed' WHERE run_id=? AND request_type='exec_start'", [message.runId]);
127
+ })();
128
+ return terminal;
129
+ }
130
+ if (typeof message.requestId === "string") {
131
+ const row = this.row(message.requestId);
132
+ if (row) {
133
+ const state = message.type === "exec_accepted" || message.type === "operation_queued" ? "preparing" : message.type === "exec_started" ? "running" : message.type === "operation_received" ? "accepted" : "completed";
134
+ if (message.type !== "operation_received")
135
+ this.db.run("UPDATE operations SET state=?, response=? WHERE request_id=?", [state, JSON.stringify(message), row.request_id]);
136
+ }
137
+ }
138
+ return message;
139
+ }
140
+ operations() {
141
+ return this.db.query(
142
+ "SELECT * FROM operations WHERE response IS NOT NULL OR state!='completed' UNION ALL SELECT aliases.request_id,operations.run_id,operations.session_id,operations.request_type,operations.digest,operations.state,operations.response FROM aliases JOIN operations ON operations.request_id=aliases.operation_id WHERE aliases.request_id!=operations.request_id AND (response IS NOT NULL OR state!='completed')"
143
+ ).all().map((row) => ({
144
+ requestId: row.request_id,
145
+ requestType: row.request_type,
146
+ state: row.state,
147
+ ...row.run_id ? { runId: row.run_id } : {},
148
+ ...row.session_id ? { sessionId: row.session_id } : {}
149
+ }));
150
+ }
151
+ response(requestId) {
152
+ const row = this.row(requestId);
153
+ return row?.response && row.state !== "unknown" ? { ...JSON.parse(row.response), requestId } : void 0;
154
+ }
155
+ responses(requestIds) {
156
+ const ids = /* @__PURE__ */ new Set([...requestIds, ...this.operations().map((operation) => operation.requestId)]);
157
+ return [...ids].flatMap((requestId) => {
158
+ const response = this.response(requestId);
159
+ return response ? [response] : [];
160
+ });
161
+ }
162
+ lengths(runId) {
163
+ const result = { stdoutBytes: 0, stderrBytes: 0 };
164
+ for (const row of this.db.query("SELECT stream,bytes FROM streams WHERE run_id=?").all(runId))
165
+ result[row.stream === "stdout" ? "stdoutBytes" : "stderrBytes"] = row.bytes;
166
+ return result;
167
+ }
168
+ outputCursors() {
169
+ const cursors = /* @__PURE__ */ new Map();
170
+ for (const stream of this.db.query("SELECT run_id,stream,acknowledged FROM streams").all()) {
171
+ const cursor = cursors.get(stream.run_id) ?? { runId: stream.run_id, stdoutBytes: 0, stderrBytes: 0 };
172
+ cursor[stream.stream === "stdout" ? "stdoutBytes" : "stderrBytes"] = stream.acknowledged;
173
+ cursors.set(stream.run_id, cursor);
174
+ }
175
+ return [...cursors.values()];
176
+ }
177
+ *output(offsets = []) {
178
+ const cursors = new Map(offsets.map((offset) => [offset.runId, offset]));
179
+ for (const stream of this.db.query("SELECT * FROM streams WHERE NOT EXISTS (SELECT 1 FROM operations WHERE operations.run_id=streams.run_id AND operations.state='unknown') ORDER BY rowid").all()) {
180
+ const supplied = cursors.get(stream.run_id);
181
+ const cursor = supplied ? stream.stream === "stdout" ? supplied.stdoutBytes : supplied.stderrBytes : stream.acknowledged;
182
+ if (cursor >= stream.bytes) continue;
183
+ const firstOffset = this.db.query("SELECT MAX(offset) AS offset FROM output WHERE run_id=? AND stream=? AND offset<=?").get(stream.run_id, stream.stream, cursor)?.offset ?? 0;
184
+ let nextChunk = firstOffset;
185
+ while (true) {
186
+ const row = this.db.query("SELECT offset,data FROM output WHERE run_id=? AND stream=? AND offset>=? AND offset<? AND offset+bytes>? ORDER BY offset LIMIT 1").get(stream.run_id, stream.stream, nextChunk, stream.bytes, cursor);
187
+ if (!row) break;
188
+ nextChunk = row.offset + 1;
189
+ yield { type: "exec_output", runId: stream.run_id, stream: stream.stream, offset: row.offset, data: row.data };
190
+ }
191
+ }
192
+ }
193
+ terminals() {
194
+ return this.db.query(
195
+ "SELECT message FROM terminals WHERE NOT EXISTS (SELECT 1 FROM operations WHERE operations.run_id=terminals.run_id AND operations.state='unknown')"
196
+ ).all().map((row) => JSON.parse(row.message));
197
+ }
198
+ acknowledgeOutput(runId, stream, offset) {
199
+ if (!Number.isSafeInteger(offset) || offset < 0) return;
200
+ this.db.run("UPDATE streams SET acknowledged=MAX(acknowledged,MIN(bytes,?)) WHERE run_id=? AND stream=?", [offset, runId, stream]);
201
+ }
202
+ acknowledgeResult(requestId) {
203
+ const row = this.row(requestId);
204
+ if (row && row.request_type !== "exec_start")
205
+ this.db.run("UPDATE operations SET response=NULL WHERE request_id=? AND state='completed'", [row.request_id]);
206
+ }
207
+ acknowledgeTerminal(runId) {
208
+ this.db.transaction(() => {
209
+ this.db.run("DELETE FROM terminals WHERE run_id=?", [runId]);
210
+ this.db.run("DELETE FROM output WHERE run_id=?", [runId]);
211
+ this.db.run("UPDATE streams SET acknowledged=bytes WHERE run_id=?", [runId]);
212
+ this.db.run("UPDATE operations SET response=NULL WHERE run_id=? AND request_type='exec_start' AND state='completed'", [runId]);
213
+ })();
214
+ }
215
+ cancelSession(sessionId) {
216
+ this.db.run("INSERT OR IGNORE INTO cancelled_requests SELECT request_id FROM operations WHERE session_id=? AND state!='completed'", [
217
+ sessionId
218
+ ]);
219
+ }
220
+ isRequestCancelled(requestId) {
221
+ const row = this.row(requestId);
222
+ return !!row && this.db.query("SELECT request_id FROM cancelled_requests WHERE request_id=?").get(row.request_id) !== null;
223
+ }
224
+ }
225
+ // Annotate the CommonJS export names for ESM import in node:
226
+ 0 && (module.exports = {
227
+ WorkerRecoveryStore,
228
+ workerOperationDigest
229
+ });
@@ -22,6 +22,7 @@ __export(supervisor_exports, {
22
22
  WORKER_RECONNECT_DELAY_MS: () => WORKER_RECONNECT_DELAY_MS,
23
23
  WORKER_RECONNECT_EXIT_CODE: () => WORKER_RECONNECT_EXIT_CODE,
24
24
  WORKER_RECONNECT_JITTER_MS: () => WORKER_RECONNECT_JITTER_MS,
25
+ WORKER_RECONNECT_MAX_DELAY_MS: () => WORKER_RECONNECT_MAX_DELAY_MS,
25
26
  WORKER_RELOAD_EXIT_CODE: () => WORKER_RELOAD_EXIT_CODE,
26
27
  WORKER_RUNTIME_ENV: () => WORKER_RUNTIME_ENV,
27
28
  isRetryableWorkerServerStatus: () => isRetryableWorkerServerStatus,
@@ -37,6 +38,7 @@ const WORKER_RECONNECT_EXIT_CODE = 76;
37
38
  const WORKER_CREDENTIAL_RESTART_EXIT_CODE = 77;
38
39
  const WORKER_RECONNECT_DELAY_MS = 2e3;
39
40
  const WORKER_RECONNECT_JITTER_MS = 3e3;
41
+ const WORKER_RECONNECT_MAX_DELAY_MS = 3e4;
40
42
  const SUPERVISOR_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
41
43
  function defaultRuntimeSpawner(argv, options) {
42
44
  return Bun.spawn(argv, options);
@@ -44,9 +46,12 @@ function defaultRuntimeSpawner(argv, options) {
44
46
  function defaultRuntimeDelay(delayMs) {
45
47
  return new Promise((resolve) => setTimeout(resolve, delayMs));
46
48
  }
47
- function workerReconnectDelayMs(random = Math.random) {
49
+ function workerReconnectDelayMs(random = Math.random, attempt = 0) {
48
50
  const sample = Math.max(0, Math.min(1, random()));
49
- return WORKER_RECONNECT_DELAY_MS + Math.floor(sample * WORKER_RECONNECT_JITTER_MS);
51
+ const exponent = Math.min(20, Math.max(0, Math.floor(attempt)));
52
+ const ceiling = Math.min(WORKER_RECONNECT_MAX_DELAY_MS, (WORKER_RECONNECT_DELAY_MS + WORKER_RECONNECT_JITTER_MS) * 2 ** exponent);
53
+ const floor = Math.min(WORKER_RECONNECT_DELAY_MS * 2 ** exponent, ceiling * 0.4);
54
+ return floor + Math.floor(sample * (ceiling - floor));
50
55
  }
51
56
  async function defaultRuntimeReaper(runtime) {
52
57
  await (0, import_process_tree.terminateProcessTree)(runtime);
@@ -60,10 +65,11 @@ function signalExitCode(signal) {
60
65
  function osSignalNumber(signal) {
61
66
  return import_node_os.constants.signals[signal];
62
67
  }
63
- async function superviseWorkerRuntime(argv, env = process.env, spawnRuntime = defaultRuntimeSpawner, waitBeforeReconnect = defaultRuntimeDelay, reapCredentialRuntime = defaultRuntimeReaper, reconnectDelay = workerReconnectDelayMs) {
68
+ async function superviseWorkerRuntime(argv, env = process.env, spawnRuntime = defaultRuntimeSpawner, waitBeforeReconnect = defaultRuntimeDelay, reapCredentialRuntime = defaultRuntimeReaper, reconnectDelay) {
64
69
  if (!process.argv[1]) {
65
70
  throw new Error("Cannot locate the r5d-worker entrypoint");
66
71
  }
72
+ let reconnectAttempt = 0;
67
73
  while (true) {
68
74
  const runtime = spawnRuntime([process.execPath, process.argv[1], ...argv], {
69
75
  stdin: "inherit",
@@ -112,7 +118,7 @@ async function superviseWorkerRuntime(argv, env = process.env, spawnRuntime = de
112
118
  continue;
113
119
  }
114
120
  if (exitCode === WORKER_RECONNECT_EXIT_CODE) {
115
- const reconnectDelayMs = reconnectDelay();
121
+ const reconnectDelayMs = reconnectDelay?.() ?? workerReconnectDelayMs(Math.random, reconnectAttempt++);
116
122
  process.stderr.write(`[r5d-worker] reconnecting in ${reconnectDelayMs}ms
117
123
  `);
118
124
  await waitBeforeReconnect(reconnectDelayMs);
@@ -132,6 +138,7 @@ async function superviseWorkerRuntime(argv, env = process.env, spawnRuntime = de
132
138
  WORKER_RECONNECT_DELAY_MS,
133
139
  WORKER_RECONNECT_EXIT_CODE,
134
140
  WORKER_RECONNECT_JITTER_MS,
141
+ WORKER_RECONNECT_MAX_DELAY_MS,
135
142
  WORKER_RELOAD_EXIT_CODE,
136
143
  WORKER_RUNTIME_ENV,
137
144
  isRetryableWorkerServerStatus,