@indigoai-us/hq-cli 5.345.245 → 5.345.246
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/CHANGELOG.md +82 -0
- package/dist/command-catalog.generated.d.ts +93 -6
- package/dist/command-catalog.generated.js +114 -6
- package/dist/commands/bot.js +1 -1
- package/dist/commands/core-checkpoint-native.d.ts +5 -1
- package/dist/commands/core-checkpoint-native.js +13 -5
- package/dist/commands/deploy-comments.js +139 -0
- package/dist/commands/deploy-list.d.ts +5 -0
- package/dist/commands/deploy-list.js +8 -0
- package/dist/commands/dm.d.ts +4 -1
- package/dist/commands/dm.js +11 -2
- package/dist/commands/files.d.ts +11 -2
- package/dist/commands/files.js +48 -3
- package/dist/commands/lanes-loop.js +4 -1
- package/dist/commands/lanes.js +16 -5
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +26 -6
- package/dist/commands/reindex.js +2 -1
- package/dist/commands/rescue.d.ts +22 -1
- package/dist/commands/rescue.js +56 -9
- package/dist/commands/sources.d.ts +1 -1
- package/dist/commands/sources.js +1 -1
- package/dist/commands/storage.d.ts +15 -2
- package/dist/commands/storage.js +74 -7
- package/dist/hq-cloud-sync-runner/bin/sync-runner.js +232 -225
- package/dist/hq-cloud-sync-runner/package.json +1 -1
- package/dist/lib/agent-kit/mcp/tools.js +22 -0
- package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
- package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
- package/dist/lib/daemon/fleet-members-cache.js +266 -0
- package/dist/lib/daemon/handoff.d.ts +4 -0
- package/dist/lib/daemon/handoff.js +2 -1
- package/dist/lib/daemon/hook-requests.d.ts +2 -1
- package/dist/lib/daemon/hook-requests.js +19 -2
- package/dist/lib/daemon/install.d.ts +9 -1
- package/dist/lib/daemon/install.js +11 -2
- package/dist/lib/daemon/ops/policy.d.ts +23 -3
- package/dist/lib/daemon/ops/policy.js +62 -15
- package/dist/lib/daemon/run.js +12 -0
- package/dist/lib/daemon/server.d.ts +5 -0
- package/dist/lib/daemon/server.js +1 -1
- package/dist/lib/daemon/supervisor.d.ts +6 -0
- package/dist/lib/daemon/supervisor.js +31 -2
- package/dist/lib/doctor/checks/sync-runtime.js +8 -1
- package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
- package/dist/lib/flag-registry-worker-source.generated.js +1 -1
- package/dist/lib/hook-engine/coverage.d.ts +68 -0
- package/dist/lib/hook-engine/coverage.js +163 -0
- package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
- package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
- package/dist/lib/hot-channels/signals-pass.js +65 -3
- package/dist/lib/install/claude-targets.d.ts +6 -0
- package/dist/lib/install/claude-targets.js +9 -1
- package/dist/lib/lanes/reconcile-result.d.ts +1 -1
- package/dist/lib/lanes/reconcile.js +19 -4
- package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
- package/dist/lib/lanes/remote-control-lane.js +10 -1
- package/dist/lib/lanes/spawn.d.ts +2 -0
- package/dist/lib/lanes/spawn.js +19 -3
- package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
- package/dist/lib/lanes/worker-env-scrub.js +146 -0
- package/dist/lib/lanes/worker-process.js +4 -1
- package/dist/lib/mesh/client.js +5 -1
- package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
- package/dist/lib/mesh/live/daemon/doctor.js +51 -6
- package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
- package/dist/lib/mesh/live/daemon/install.js +70 -0
- package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
- package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
- package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
- package/dist/lib/mesh/live/daemon/run.js +48 -3
- package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
- package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
- package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
- package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
- package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
- package/dist/lib/mesh/live/direct-drain.js +3 -1
- package/dist/lib/mesh/live/emit.js +4 -2
- package/dist/lib/mesh/live/flush.d.ts +61 -0
- package/dist/lib/mesh/live/flush.js +434 -114
- package/dist/lib/mesh/live/paths.d.ts +10 -0
- package/dist/lib/mesh/live/paths.js +14 -0
- package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
- package/dist/lib/mesh/live/reporting-privacy.js +81 -7
- package/dist/lib/mesh/live/spool.d.ts +171 -17
- package/dist/lib/mesh/live/spool.js +777 -62
- package/dist/lib/signals/engine.d.ts +82 -2
- package/dist/lib/signals/engine.js +389 -53
- package/dist/lib/signals/steps/extract.js +5 -0
- package/dist/lib/work-context/organize.d.ts +22 -4
- package/dist/lib/work-context/organize.js +50 -21
- package/dist/lib/work-context/paths.d.ts +6 -0
- package/dist/lib/work-context/paths.js +9 -0
- package/dist/lib/work-context/reconcile.d.ts +1 -1
- package/dist/lib/work-context/reconcile.js +1 -1
- package/dist/startup-registration.d.ts +14 -0
- package/dist/startup-registration.js +26 -0
- package/dist/utils/cli-telemetry.d.ts +6 -0
- package/dist/utils/cli-telemetry.js +154 -9
- package/dist/utils/github-tag-fallback.d.ts +7 -2
- package/dist/utils/github-tag-fallback.js +17 -8
- package/dist/utils/hq-core-source.d.ts +31 -0
- package/dist/utils/hq-core-source.js +144 -0
- package/dist/utils/interactive-caller.d.ts +6 -0
- package/dist/utils/interactive-caller.js +8 -0
- package/dist/utils/shipped-codex-hooks.d.ts +6 -4
- package/dist/utils/shipped-codex-hooks.js +22 -10
- package/dist/utils/vault-api.js +1 -0
- package/dist/utils/version-report.d.ts +3 -1
- package/dist/utils/version-report.js +13 -5
- package/docs/anywhere-runtime.md +2 -2
- package/package.json +8 -8
- package/scripts/check-function-manifest.mjs +99 -18
|
@@ -8,7 +8,7 @@ import * as path from "node:path";
|
|
|
8
8
|
import { randomBytes } from "node:crypto";
|
|
9
9
|
import { ensureOwnerDir } from "../../work-context/atomic.js";
|
|
10
10
|
import { updateLivenessCarry } from "./liveness-carry.js";
|
|
11
|
-
import { workMeshClaimPath, workMeshDeadLetterPath, workMeshDroppedReceiptPath, workMeshHeldPath, workMeshRoot, workMeshSpoolPath, } from "./paths.js";
|
|
11
|
+
import { workMeshClaimPath, workMeshDeadLetterPath, workMeshDroppedReceiptPath, workMeshHeldPath, workMeshParkedIndexPath, workMeshParkedPath, workMeshRoot, workMeshSpoolPath, } from "./paths.js";
|
|
12
12
|
/** Linux PIPE_BUF is typically 4096; keep a conservative ceiling for one line. */
|
|
13
13
|
export const SPOOL_LINE_MAX_BYTES = 4096;
|
|
14
14
|
export class SpoolWriteError extends Error {
|
|
@@ -60,29 +60,6 @@ export function appendJsonlLine(filePath, line) {
|
|
|
60
60
|
}
|
|
61
61
|
chmodOwnerFile(filePath);
|
|
62
62
|
}
|
|
63
|
-
/**
|
|
64
|
-
* Put lines back on the spool exactly as they were read: the same bytes, one
|
|
65
|
-
* write per line under O_APPEND, in the order given. Nothing is parsed or
|
|
66
|
-
* checked; a line a flush is not allowed to act on is not its to change.
|
|
67
|
-
*/
|
|
68
|
-
export function appendRawSpoolLines(lines, root) {
|
|
69
|
-
if (lines.length === 0)
|
|
70
|
-
return;
|
|
71
|
-
const spool = workMeshSpoolPath(root ?? workMeshRoot());
|
|
72
|
-
ensureSpoolFile(spool);
|
|
73
|
-
const fd = fs.openSync(spool, fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_WRONLY, 0o600);
|
|
74
|
-
try {
|
|
75
|
-
for (const line of lines) {
|
|
76
|
-
const buf = Buffer.from(`${line}\n`, "utf8");
|
|
77
|
-
const written = fs.writeSync(fd, buf, 0, buf.length);
|
|
78
|
-
if (written !== buf.length)
|
|
79
|
-
throw new SpoolWriteError(`Short write to spool (${written} of ${buf.length} bytes)`);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
finally {
|
|
83
|
-
fs.closeSync(fd);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
63
|
export function appendSpoolLine(line, root) {
|
|
87
64
|
const spool = workMeshSpoolPath(root ?? workMeshRoot());
|
|
88
65
|
appendJsonlLine(spool, line);
|
|
@@ -132,36 +109,93 @@ function heldEventId(line) {
|
|
|
132
109
|
return null;
|
|
133
110
|
}
|
|
134
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* The eventIds a held or dead-letter file already holds. Streams the file:
|
|
114
|
+
* dead-letter.jsonl has been seen past V8's ~512 MB string limit, where a
|
|
115
|
+
* whole-file read throws "Cannot create a string longer than 0x1fffffe8".
|
|
116
|
+
*/
|
|
135
117
|
function readEventIds(filePath) {
|
|
136
118
|
const ids = new Set();
|
|
137
|
-
|
|
138
|
-
try {
|
|
139
|
-
raw = fs.readFileSync(filePath, "utf8");
|
|
140
|
-
}
|
|
141
|
-
catch (error) {
|
|
142
|
-
if (error.code === "ENOENT")
|
|
143
|
-
return ids;
|
|
144
|
-
throw error;
|
|
145
|
-
}
|
|
146
|
-
for (const line of raw.split("\n")) {
|
|
119
|
+
forEachJsonlLine(filePath, (line) => {
|
|
147
120
|
if (!line.trim())
|
|
148
|
-
|
|
121
|
+
return;
|
|
149
122
|
const eventId = heldEventId(line);
|
|
150
123
|
if (eventId)
|
|
151
124
|
ids.add(eventId);
|
|
152
|
-
}
|
|
125
|
+
});
|
|
153
126
|
return ids;
|
|
154
127
|
}
|
|
128
|
+
/** Appended lines are written in chunks of about this many bytes. */
|
|
129
|
+
const JSONL_APPEND_CHUNK_BYTES = 64 * 1024;
|
|
155
130
|
function appendJsonlLines(filePath, lines) {
|
|
156
131
|
if (lines.length === 0)
|
|
157
132
|
return;
|
|
158
133
|
ensureSpoolFile(filePath);
|
|
159
|
-
|
|
134
|
+
const out = new JsonlAppender(filePath);
|
|
135
|
+
for (const line of lines)
|
|
136
|
+
out.push(line);
|
|
137
|
+
out.flush();
|
|
160
138
|
chmodOwnerFile(filePath);
|
|
161
139
|
}
|
|
140
|
+
/**
|
|
141
|
+
* Appends whole lines to a JSONL file with bounded memory: lines are buffered
|
|
142
|
+
* up to about 64 KB, then written with one open, one O_APPEND write and one
|
|
143
|
+
* close. A short write throws SpoolWriteError. `writeChunk` replaces the plain
|
|
144
|
+
* append (the parked file writes its index under a lock first).
|
|
145
|
+
*/
|
|
146
|
+
export class JsonlAppender {
|
|
147
|
+
filePath;
|
|
148
|
+
writeChunk;
|
|
149
|
+
buffered = [];
|
|
150
|
+
bytes = 0;
|
|
151
|
+
/** Lines written to disk so far. */
|
|
152
|
+
written = 0;
|
|
153
|
+
constructor(filePath, writeChunk = appendChunk) {
|
|
154
|
+
this.filePath = filePath;
|
|
155
|
+
this.writeChunk = writeChunk;
|
|
156
|
+
}
|
|
157
|
+
push(line) {
|
|
158
|
+
this.buffered.push(line);
|
|
159
|
+
this.bytes += Buffer.byteLength(line, "utf8") + 1;
|
|
160
|
+
if (this.bytes >= JSONL_APPEND_CHUNK_BYTES)
|
|
161
|
+
this.flush();
|
|
162
|
+
}
|
|
163
|
+
/** Lines pushed and not yet written. */
|
|
164
|
+
get pending() {
|
|
165
|
+
return this.buffered.length;
|
|
166
|
+
}
|
|
167
|
+
flush() {
|
|
168
|
+
if (this.buffered.length === 0)
|
|
169
|
+
return;
|
|
170
|
+
const lines = this.buffered;
|
|
171
|
+
this.writeChunk(this.filePath, lines);
|
|
172
|
+
this.written += lines.length;
|
|
173
|
+
this.buffered = [];
|
|
174
|
+
this.bytes = 0;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function appendChunk(filePath, lines) {
|
|
178
|
+
ensureSpoolFile(filePath);
|
|
179
|
+
const buf = Buffer.from(`${lines.join("\n")}\n`, "utf8");
|
|
180
|
+
const fd = fs.openSync(filePath, fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_WRONLY, 0o600);
|
|
181
|
+
try {
|
|
182
|
+
const written = fs.writeSync(fd, buf, 0, buf.length);
|
|
183
|
+
if (written !== buf.length) {
|
|
184
|
+
throw new SpoolWriteError(`Short write to ${path.basename(filePath)} (${written} of ${buf.length} bytes)`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
fs.closeSync(fd);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
162
191
|
const JSONL_LOCK_STALE_MS = 5 * 60_000;
|
|
163
192
|
const JSONL_LOCK_TIMEOUT_MS = 5_000;
|
|
164
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* Serialize check-and-append with claims; stale locks expire after five
|
|
195
|
+
* minutes. `fn` gets `touch`, which marks the lock fresh: work that may take
|
|
196
|
+
* longer than that (a long copy) calls it as it goes, so no other process
|
|
197
|
+
* takes the lock as stale while it is still held.
|
|
198
|
+
*/
|
|
165
199
|
function withJsonlLock(filePath, fn) {
|
|
166
200
|
const lockPath = `${filePath}.lock`;
|
|
167
201
|
const token = randomBytes(12).toString("hex");
|
|
@@ -206,11 +240,22 @@ function withJsonlLock(filePath, fn) {
|
|
|
206
240
|
Atomics.wait(waitCell, 0, 0, 10);
|
|
207
241
|
}
|
|
208
242
|
}
|
|
243
|
+
const touch = () => {
|
|
244
|
+
try {
|
|
245
|
+
const at = new Date();
|
|
246
|
+
fs.utimesSync(lockPath, at, at);
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
// A lock already gone was taken over; the cleanup below checks the token.
|
|
250
|
+
if (error.code !== "ENOENT")
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
209
254
|
let result;
|
|
210
255
|
let operationError;
|
|
211
256
|
let operationFailed = false;
|
|
212
257
|
try {
|
|
213
|
-
result = fn();
|
|
258
|
+
result = fn(touch);
|
|
214
259
|
}
|
|
215
260
|
catch (error) {
|
|
216
261
|
operationError = error;
|
|
@@ -239,10 +284,18 @@ export function appendDeadLetterLine(line, root) {
|
|
|
239
284
|
const dl = workMeshDeadLetterPath(root ?? workMeshRoot());
|
|
240
285
|
withJsonlLock(dl, () => {
|
|
241
286
|
ensureSpoolFile(dl);
|
|
242
|
-
const ids = readEventIds(dl);
|
|
243
287
|
const eventId = heldEventId(line);
|
|
244
|
-
|
|
288
|
+
// A line without an eventId is never deduplicated, so the file is not read.
|
|
289
|
+
// Known ids are kept per process; only lines added since are read.
|
|
290
|
+
if (!eventId) {
|
|
245
291
|
appendJsonlLine(dl, line);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const ids = deadLetterIds(dl);
|
|
295
|
+
if (ids.has(eventId))
|
|
296
|
+
return;
|
|
297
|
+
appendJsonlLine(dl, line);
|
|
298
|
+
ids.add(eventId);
|
|
246
299
|
});
|
|
247
300
|
return dl;
|
|
248
301
|
}
|
|
@@ -356,29 +409,447 @@ export function appendDroppedReceipt(receipt, root) {
|
|
|
356
409
|
appendJsonlLine(dest, JSON.stringify(receipt));
|
|
357
410
|
return dest;
|
|
358
411
|
}
|
|
412
|
+
/**
|
|
413
|
+
* Append a dropped receipt unless one with the same `receiptId` is already in
|
|
414
|
+
* the file: a flush that dies after writing it and before removing its claim
|
|
415
|
+
* reads the same claim again and drops the same lines, and must not count
|
|
416
|
+
* them twice. Returns true when the receipt was written.
|
|
417
|
+
*/
|
|
418
|
+
export function appendDroppedReceiptOnce(receipt, root) {
|
|
419
|
+
const dest = workMeshDroppedReceiptPath(root ?? workMeshRoot());
|
|
420
|
+
const needle = `"receiptId":${JSON.stringify(receipt.receiptId)}`;
|
|
421
|
+
let seen = false;
|
|
422
|
+
forEachJsonlLine(dest, (line) => {
|
|
423
|
+
if (line.includes(needle))
|
|
424
|
+
seen = true;
|
|
425
|
+
return !seen;
|
|
426
|
+
});
|
|
427
|
+
if (seen)
|
|
428
|
+
return false;
|
|
429
|
+
appendJsonlLine(dest, JSON.stringify(receipt));
|
|
430
|
+
return true;
|
|
431
|
+
}
|
|
359
432
|
/**
|
|
360
433
|
* Claim a jsonl file by renaming it aside (never read-then-truncate).
|
|
361
434
|
* Concurrent appends after the rename land on a fresh file.
|
|
362
435
|
*/
|
|
363
436
|
export function claimJsonlByRename(sourcePath, claimPath) {
|
|
437
|
+
if (!claimJsonlPathByRename(sourcePath, claimPath))
|
|
438
|
+
return { claimPath: null, lines: [] };
|
|
439
|
+
// Streamed: a claim past V8's string limit cannot be read in one string.
|
|
440
|
+
const lines = [];
|
|
441
|
+
forEachJsonlLine(claimPath, (line) => {
|
|
442
|
+
if (line.trim())
|
|
443
|
+
lines.push(line);
|
|
444
|
+
});
|
|
445
|
+
return { claimPath, lines };
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Rename a jsonl file aside and return the claim path without reading it, or
|
|
449
|
+
* null when there was nothing to claim. The flush streams the claim itself.
|
|
450
|
+
*/
|
|
451
|
+
export function claimJsonlPathByRename(sourcePath, claimPath) {
|
|
364
452
|
try {
|
|
365
453
|
fs.renameSync(sourcePath, claimPath);
|
|
366
454
|
}
|
|
367
455
|
catch (err) {
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
return { claimPath: null, lines: [] };
|
|
371
|
-
}
|
|
456
|
+
if (err?.code === "ENOENT")
|
|
457
|
+
return null;
|
|
372
458
|
throw err;
|
|
373
459
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
460
|
+
return claimPath;
|
|
461
|
+
}
|
|
462
|
+
/** {@link claimSpool} without reading the claim. */
|
|
463
|
+
export function claimSpoolPath(root, ts = `${Date.now()}`) {
|
|
464
|
+
ensureOwnerDir(root);
|
|
465
|
+
return claimJsonlPathByRename(workMeshSpoolPath(root), workMeshClaimPath("spool", ts, root));
|
|
466
|
+
}
|
|
467
|
+
/** {@link claimHeld} without reading the claim. */
|
|
468
|
+
export function claimHeldPath(root, ts = `${Date.now()}`) {
|
|
469
|
+
ensureOwnerDir(root);
|
|
470
|
+
const heldPath = workMeshHeldPath(root);
|
|
471
|
+
return withJsonlLock(heldPath, () => claimJsonlPathByRename(heldPath, workMeshClaimPath("held", ts, root)));
|
|
472
|
+
}
|
|
473
|
+
function fileSizeOrZero(file) {
|
|
474
|
+
try {
|
|
475
|
+
return fs.statSync(file).size;
|
|
476
|
+
}
|
|
477
|
+
catch (err) {
|
|
478
|
+
if (err.code === "ENOENT")
|
|
479
|
+
return 0;
|
|
480
|
+
throw err;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
function parseSegments(value) {
|
|
484
|
+
if (!Array.isArray(value))
|
|
485
|
+
return undefined;
|
|
486
|
+
const out = [];
|
|
487
|
+
for (const entry of value) {
|
|
488
|
+
if (!entry || typeof entry !== "object")
|
|
489
|
+
return undefined;
|
|
490
|
+
const { lines, parkedAt } = entry;
|
|
491
|
+
if (typeof lines !== "number" || !Number.isInteger(lines) || lines < 0)
|
|
492
|
+
return undefined;
|
|
493
|
+
if (parkedAt !== null && (typeof parkedAt !== "string" || !Number.isFinite(Date.parse(parkedAt))))
|
|
494
|
+
return undefined;
|
|
495
|
+
out.push({ lines, parkedAt: parkedAt });
|
|
496
|
+
}
|
|
497
|
+
return out;
|
|
498
|
+
}
|
|
499
|
+
function readParkedIndex(root) {
|
|
500
|
+
try {
|
|
501
|
+
const parsed = JSON.parse(fs.readFileSync(workMeshParkedIndexPath(root), "utf8"));
|
|
502
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
503
|
+
return null;
|
|
504
|
+
const sessions = parsed.sessions;
|
|
505
|
+
if (parsed.v !== 1 || !sessions || typeof sessions !== "object" || Array.isArray(sessions))
|
|
506
|
+
return null;
|
|
507
|
+
const out = {};
|
|
508
|
+
for (const [sessionId, binding] of Object.entries(sessions)) {
|
|
509
|
+
if (typeof binding === "string")
|
|
510
|
+
out[sessionId] = binding;
|
|
511
|
+
}
|
|
512
|
+
const segments = parseSegments(parsed.segments);
|
|
513
|
+
const bytes = parsed.bytes;
|
|
514
|
+
return {
|
|
515
|
+
v: 1,
|
|
516
|
+
sessions: out,
|
|
517
|
+
...(segments ? { segments } : {}),
|
|
518
|
+
...(typeof bytes === "number" && Number.isInteger(bytes) && bytes >= 0 ? { bytes } : {}),
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
catch {
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/** The oldest and newest known parked-at times of the parked file, or null when none is known. */
|
|
526
|
+
export function parkedTimesRange(root) {
|
|
527
|
+
const size = fileSizeOrZero(workMeshParkedPath(root));
|
|
528
|
+
if (size === 0)
|
|
529
|
+
return null;
|
|
530
|
+
const index = readParkedIndex(root);
|
|
531
|
+
// Times recorded for a file of another size do not describe this one.
|
|
532
|
+
if (!index?.segments || index.bytes !== size)
|
|
533
|
+
return null;
|
|
534
|
+
return segmentsRange(index.segments);
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* The segments of a parked claim, only when they describe it: the claim is
|
|
538
|
+
* the size recorded with them and holds as many non-empty lines as they
|
|
539
|
+
* count. Otherwise null, and every line is of unknown age.
|
|
540
|
+
*/
|
|
541
|
+
export function verifiedParkedClaimTimes(claimPath) {
|
|
542
|
+
const recorded = readParkedClaimTimesRecord(claimPath);
|
|
543
|
+
if (!recorded || recorded.bytes === undefined)
|
|
544
|
+
return null;
|
|
545
|
+
if (fileSizeOrZero(claimPath) !== recorded.bytes)
|
|
546
|
+
return null;
|
|
547
|
+
const expected = recorded.segments.reduce((sum, segment) => sum + segment.lines, 0);
|
|
548
|
+
if (countJsonlLines(claimPath) !== expected)
|
|
549
|
+
return null;
|
|
550
|
+
return recorded.segments;
|
|
551
|
+
}
|
|
552
|
+
export function segmentsRange(segments) {
|
|
553
|
+
let oldestMs = Infinity;
|
|
554
|
+
let newestMs = -Infinity;
|
|
555
|
+
for (const segment of segments) {
|
|
556
|
+
if (segment.parkedAt === null || segment.lines === 0)
|
|
378
557
|
continue;
|
|
379
|
-
|
|
558
|
+
const at = Date.parse(segment.parkedAt);
|
|
559
|
+
if (at < oldestMs)
|
|
560
|
+
oldestMs = at;
|
|
561
|
+
if (at > newestMs)
|
|
562
|
+
newestMs = at;
|
|
380
563
|
}
|
|
381
|
-
return {
|
|
564
|
+
return Number.isFinite(oldestMs) ? { oldestMs, newestMs } : null;
|
|
565
|
+
}
|
|
566
|
+
/** Sidecar of a parked claim: the parked-at segments its lines had in the parked file. */
|
|
567
|
+
export function parkedClaimTimesPath(claimPath) {
|
|
568
|
+
return `${claimPath}.parked-at.json`;
|
|
569
|
+
}
|
|
570
|
+
/** The parked-at segments recorded for a parked claim (unverified), or null when none were. */
|
|
571
|
+
export function readParkedClaimTimes(claimPath) {
|
|
572
|
+
return readParkedClaimTimesRecord(claimPath)?.segments ?? null;
|
|
573
|
+
}
|
|
574
|
+
function readParkedClaimTimesRecord(claimPath) {
|
|
575
|
+
try {
|
|
576
|
+
const parsed = JSON.parse(fs.readFileSync(parkedClaimTimesPath(claimPath), "utf8"));
|
|
577
|
+
if (parsed?.v !== 1)
|
|
578
|
+
return null;
|
|
579
|
+
const segments = parseSegments(parsed.segments);
|
|
580
|
+
if (!segments)
|
|
581
|
+
return null;
|
|
582
|
+
return typeof parsed.bytes === "number" ? { segments, bytes: parsed.bytes } : { segments };
|
|
583
|
+
}
|
|
584
|
+
catch (err) {
|
|
585
|
+
if (err.code === "ENOENT")
|
|
586
|
+
return null;
|
|
587
|
+
// An unreadable sidecar means the times are not known: nothing is aged.
|
|
588
|
+
return null;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
function writeJsonAtomic(target, value) {
|
|
592
|
+
const tmp = `${target}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
593
|
+
try {
|
|
594
|
+
fs.writeFileSync(tmp, `${JSON.stringify(value)}\n`, { mode: 0o600, flag: "wx" });
|
|
595
|
+
fs.renameSync(tmp, target);
|
|
596
|
+
}
|
|
597
|
+
finally {
|
|
598
|
+
fs.rmSync(tmp, { force: true });
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/** Append segments, merging a run with the same parked-at time. */
|
|
602
|
+
function appendSegments(into, add) {
|
|
603
|
+
for (const segment of add) {
|
|
604
|
+
if (segment.lines === 0)
|
|
605
|
+
continue;
|
|
606
|
+
const last = into[into.length - 1];
|
|
607
|
+
if (last && last.parkedAt === segment.parkedAt)
|
|
608
|
+
last.lines += segment.lines;
|
|
609
|
+
else
|
|
610
|
+
into.push({ ...segment });
|
|
611
|
+
}
|
|
612
|
+
return into;
|
|
613
|
+
}
|
|
614
|
+
function writeParkedIndex(root, index) {
|
|
615
|
+
writeJsonAtomic(workMeshParkedIndexPath(root), index);
|
|
616
|
+
}
|
|
617
|
+
/** Staging files a flush writes while it reads its claims (see createStagedAppender). */
|
|
618
|
+
const STAGING_RE = /^spool\.(parked\.)?staging\.\d+\.[0-9a-f]+\.jsonl$/;
|
|
619
|
+
/** Parked-at sidecars of parked claims (see parkedClaimTimesPath). */
|
|
620
|
+
const PARKED_TIMES_RE = /^spool\..+\.claimed\.parked-at\.json$/;
|
|
621
|
+
/** A staging file this old belongs to a flush that died; it is removed. */
|
|
622
|
+
const STAGING_STALE_MS = 60 * 60_000;
|
|
623
|
+
function stagingPath(root, kind) {
|
|
624
|
+
const name = `spool.${kind === "parked" ? "parked." : ""}staging.${process.pid}.${randomBytes(6).toString("hex")}.jsonl`;
|
|
625
|
+
return path.join(root, name);
|
|
626
|
+
}
|
|
627
|
+
/** Remove staging files left by a flush that died more than an hour ago. */
|
|
628
|
+
export function removeStaleStagingFiles(root, nowMs = Date.now()) {
|
|
629
|
+
let names;
|
|
630
|
+
try {
|
|
631
|
+
names = fs.readdirSync(root);
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
for (const name of names) {
|
|
637
|
+
const sidecar = PARKED_TIMES_RE.test(name);
|
|
638
|
+
if (!STAGING_RE.test(name) && !sidecar)
|
|
639
|
+
continue;
|
|
640
|
+
const file = path.join(root, name);
|
|
641
|
+
// A parked-at sidecar is kept while its claim is there.
|
|
642
|
+
if (sidecar && fs.existsSync(file.slice(0, -".parked-at.json".length)))
|
|
643
|
+
continue;
|
|
644
|
+
try {
|
|
645
|
+
if (nowMs - fs.statSync(file).mtimeMs >= STAGING_STALE_MS)
|
|
646
|
+
fs.rmSync(file, { force: true });
|
|
647
|
+
}
|
|
648
|
+
catch {
|
|
649
|
+
// gone already, or not ours to remove
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Append every line of `src` to `dest` in bounded chunks; `onChunk` runs after
|
|
655
|
+
* each written chunk. Returns the lines copied, or null when `src` could not
|
|
656
|
+
* be opened.
|
|
657
|
+
*/
|
|
658
|
+
function copyJsonlLines(src, dest, onChunk) {
|
|
659
|
+
const out = new JsonlAppender(dest, (filePath, lines) => {
|
|
660
|
+
appendChunk(filePath, lines);
|
|
661
|
+
onChunk?.();
|
|
662
|
+
});
|
|
663
|
+
let copied = 0;
|
|
664
|
+
const opened = forEachJsonlLine(src, (line) => {
|
|
665
|
+
if (!line.trim())
|
|
666
|
+
return;
|
|
667
|
+
out.push(line);
|
|
668
|
+
copied += 1;
|
|
669
|
+
});
|
|
670
|
+
out.flush();
|
|
671
|
+
return opened ? copied : null;
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Move a staging file's lines onto `target`. The staging file must still hold
|
|
675
|
+
* exactly the bytes written to it: one removed by another process's stale
|
|
676
|
+
* cleanup and started again would otherwise lose its earlier lines quietly.
|
|
677
|
+
* With no `target` yet, the staging file is linked into place (no copy, so a
|
|
678
|
+
* large flush does not need the disk space twice); a link fails if `target`
|
|
679
|
+
* exists, so a file created meanwhile is never replaced. Otherwise the lines
|
|
680
|
+
* are appended, and the copied count must match.
|
|
681
|
+
*/
|
|
682
|
+
function commitStagingFile(staging, target, expected, onChunk) {
|
|
683
|
+
if (expected.lines === 0) {
|
|
684
|
+
fs.rmSync(staging, { force: true });
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
let size = -1;
|
|
688
|
+
try {
|
|
689
|
+
size = fs.statSync(staging).size;
|
|
690
|
+
}
|
|
691
|
+
catch (error) {
|
|
692
|
+
if (error.code !== "ENOENT")
|
|
693
|
+
throw error;
|
|
694
|
+
}
|
|
695
|
+
if (size !== expected.bytes) {
|
|
696
|
+
throw new SpoolWriteError(`Staging file ${path.basename(staging)} holds ${size < 0 ? "nothing" : `${size} bytes`}, expected ${expected.bytes}`);
|
|
697
|
+
}
|
|
698
|
+
try {
|
|
699
|
+
fs.linkSync(staging, target);
|
|
700
|
+
fs.rmSync(staging, { force: true });
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
catch (error) {
|
|
704
|
+
// EEXIST: the target is there, append to it. Anything else (a file system
|
|
705
|
+
// without hard links): fall back to the copy as well.
|
|
706
|
+
void error;
|
|
707
|
+
}
|
|
708
|
+
const copied = copyJsonlLines(staging, target, onChunk);
|
|
709
|
+
if (copied !== expected.lines) {
|
|
710
|
+
throw new SpoolWriteError(`Copied ${copied ?? 0} of ${expected.lines} staged lines to ${path.basename(target)}`);
|
|
711
|
+
}
|
|
712
|
+
fs.rmSync(staging, { force: true });
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Lines a flush writes back while it is still reading its claims go to a
|
|
716
|
+
* private staging file first, and reach the spool only on commit, once every
|
|
717
|
+
* claim was read to the end. A flush that fails partway through the read
|
|
718
|
+
* discards the staging file and keeps its claims, so a failure that repeats
|
|
719
|
+
* on every flush never writes the same lines to the spool again and again.
|
|
720
|
+
*/
|
|
721
|
+
export function createStagedAppender(root, target) {
|
|
722
|
+
const staging = stagingPath(root, "spool");
|
|
723
|
+
const out = new JsonlAppender(staging);
|
|
724
|
+
let count = 0;
|
|
725
|
+
let bytes = 0;
|
|
726
|
+
return {
|
|
727
|
+
push(line) {
|
|
728
|
+
out.push(line);
|
|
729
|
+
count += 1;
|
|
730
|
+
bytes += Buffer.byteLength(line, "utf8") + 1;
|
|
731
|
+
},
|
|
732
|
+
get count() {
|
|
733
|
+
return count;
|
|
734
|
+
},
|
|
735
|
+
commit() {
|
|
736
|
+
out.flush();
|
|
737
|
+
commitStagingFile(staging, target, { lines: count, bytes });
|
|
738
|
+
},
|
|
739
|
+
discard() {
|
|
740
|
+
fs.rmSync(staging, { force: true });
|
|
741
|
+
},
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Appender for the parked file. Lines are staged (see createStagedAppender)
|
|
746
|
+
* and reach the parked file on commit, under the parked lock together with the
|
|
747
|
+
* index entries of their sessions, so a concurrent re-offer (which renames the
|
|
748
|
+
* file and removes the index under the same lock) never separates lines from
|
|
749
|
+
* their index entries. The index is written on every commit, also when no
|
|
750
|
+
* parked line has a session id, so such lines are not re-offered on every
|
|
751
|
+
* flush. `bindingOf` gives the binding to record for a session.
|
|
752
|
+
*/
|
|
753
|
+
export function createParkedAppender(root, bindingOf) {
|
|
754
|
+
const parkedPath = workMeshParkedPath(root);
|
|
755
|
+
const staging = stagingPath(root, "parked");
|
|
756
|
+
const out = new JsonlAppender(staging);
|
|
757
|
+
const sessions = new Map();
|
|
758
|
+
const segments = [];
|
|
759
|
+
let count = 0;
|
|
760
|
+
let bytes = 0;
|
|
761
|
+
return {
|
|
762
|
+
push(line, sessionId, parkedAt) {
|
|
763
|
+
if (sessionId && !sessions.has(sessionId))
|
|
764
|
+
sessions.set(sessionId, bindingOf(sessionId));
|
|
765
|
+
out.push(line);
|
|
766
|
+
appendSegments(segments, [{ lines: 1, parkedAt }]);
|
|
767
|
+
count += 1;
|
|
768
|
+
bytes += Buffer.byteLength(line, "utf8") + 1;
|
|
769
|
+
},
|
|
770
|
+
get count() {
|
|
771
|
+
return count;
|
|
772
|
+
},
|
|
773
|
+
commit() {
|
|
774
|
+
out.flush();
|
|
775
|
+
if (count === 0) {
|
|
776
|
+
fs.rmSync(staging, { force: true });
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
// The lines were written to the staging file outside the lock. Under it,
|
|
780
|
+
// a missing parked file is a link (no copy); an append to an existing
|
|
781
|
+
// one keeps the lock fresh after each chunk.
|
|
782
|
+
withJsonlLock(parkedPath, (touch) => {
|
|
783
|
+
const index = readParkedIndex(root) ?? { v: 1, sessions: {} };
|
|
784
|
+
for (const [sessionId, binding] of sessions)
|
|
785
|
+
index.sessions[sessionId] = binding;
|
|
786
|
+
// The parked-at times follow the file's lines in order, and hold only
|
|
787
|
+
// while the file is the size recorded with them. A file of another
|
|
788
|
+
// size (an append that failed partway, a crash between the append and
|
|
789
|
+
// the index write, a file written before times were recorded) has
|
|
790
|
+
// lines of unknown age.
|
|
791
|
+
const sizeBefore = fileSizeOrZero(parkedPath);
|
|
792
|
+
const base = sizeBefore === 0
|
|
793
|
+
? []
|
|
794
|
+
: index.segments && index.bytes === sizeBefore
|
|
795
|
+
? index.segments.map((segment) => ({ ...segment }))
|
|
796
|
+
: [{ lines: countJsonlLines(parkedPath), parkedAt: null }];
|
|
797
|
+
// Sessions first, with the times unchanged: a re-offer never finds
|
|
798
|
+
// lines whose sessions are not in the index. The new times are
|
|
799
|
+
// written only after the lines are in the file.
|
|
800
|
+
writeParkedIndex(root, index);
|
|
801
|
+
commitStagingFile(staging, parkedPath, { lines: count, bytes }, touch);
|
|
802
|
+
index.segments = appendSegments(base, segments);
|
|
803
|
+
index.bytes = fileSizeOrZero(parkedPath);
|
|
804
|
+
writeParkedIndex(root, index);
|
|
805
|
+
});
|
|
806
|
+
},
|
|
807
|
+
commitTo(target) {
|
|
808
|
+
out.flush();
|
|
809
|
+
commitStagingFile(staging, target, { lines: count, bytes });
|
|
810
|
+
},
|
|
811
|
+
discard() {
|
|
812
|
+
fs.rmSync(staging, { force: true });
|
|
813
|
+
},
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Offer the parked lines to a flush again: under the parked lock, rename the
|
|
818
|
+
* parked file to a spool claim (`spool.<ts>.parked.claimed`, which orphan
|
|
819
|
+
* recovery reads like any spool claim) and remove its index. `changed` decides
|
|
820
|
+
* from the index; it is not asked when the index is missing or unreadable, and
|
|
821
|
+
* the lines are offered then, so the index is rebuilt. Returns the claim path,
|
|
822
|
+
* or null when nothing was offered.
|
|
823
|
+
*/
|
|
824
|
+
export function reofferParkedLines(root, ts, changed) {
|
|
825
|
+
const parkedPath = workMeshParkedPath(root);
|
|
826
|
+
const indexPath = workMeshParkedIndexPath(root);
|
|
827
|
+
if (!fs.existsSync(parkedPath)) {
|
|
828
|
+
if (fs.existsSync(indexPath))
|
|
829
|
+
fs.rmSync(indexPath, { force: true });
|
|
830
|
+
return null;
|
|
831
|
+
}
|
|
832
|
+
return withJsonlLock(parkedPath, () => {
|
|
833
|
+
if (!jsonlHasBytes(parkedPath)) {
|
|
834
|
+
fs.rmSync(parkedPath, { force: true });
|
|
835
|
+
fs.rmSync(indexPath, { force: true });
|
|
836
|
+
return null;
|
|
837
|
+
}
|
|
838
|
+
const index = readParkedIndex(root);
|
|
839
|
+
if (changed && index && !changed(index))
|
|
840
|
+
return null;
|
|
841
|
+
const target = workMeshClaimPath("spool", `${ts}.parked`, root);
|
|
842
|
+
// The parked-at times go with the lines, beside the claim, before the
|
|
843
|
+
// rename: a flush that reads the claim finds them whenever it finds it.
|
|
844
|
+
if (index?.segments && index.bytes !== undefined) {
|
|
845
|
+
writeJsonAtomic(parkedClaimTimesPath(target), { v: 1, segments: index.segments, bytes: index.bytes });
|
|
846
|
+
}
|
|
847
|
+
const claimPath = claimJsonlPathByRename(parkedPath, target);
|
|
848
|
+
if (!claimPath)
|
|
849
|
+
fs.rmSync(parkedClaimTimesPath(target), { force: true });
|
|
850
|
+
fs.rmSync(indexPath, { force: true });
|
|
851
|
+
return claimPath;
|
|
852
|
+
});
|
|
382
853
|
}
|
|
383
854
|
export function claimSpool(root, ts = `${Date.now()}`) {
|
|
384
855
|
ensureOwnerDir(root);
|
|
@@ -430,7 +901,7 @@ export function hasPendingFlushWork(root) {
|
|
|
430
901
|
catch {
|
|
431
902
|
return true;
|
|
432
903
|
}
|
|
433
|
-
return jsonlHasBytes(workMeshSpoolPath(root)) || jsonlHasBytes(workMeshHeldPath(root));
|
|
904
|
+
return jsonlHasBytes(workMeshSpoolPath(root)) || jsonlHasBytes(workMeshHeldPath(root)) || jsonlHasBytes(workMeshParkedPath(root));
|
|
434
905
|
}
|
|
435
906
|
/**
|
|
436
907
|
* Like hasPendingFlushWork, without the held file: true when the spool has
|
|
@@ -445,7 +916,7 @@ export function hasPendingSpoolWork(root) {
|
|
|
445
916
|
catch {
|
|
446
917
|
return true;
|
|
447
918
|
}
|
|
448
|
-
return jsonlHasBytes(workMeshSpoolPath(root));
|
|
919
|
+
return jsonlHasBytes(workMeshSpoolPath(root)) || jsonlHasBytes(workMeshParkedPath(root));
|
|
449
920
|
}
|
|
450
921
|
/**
|
|
451
922
|
* Read a claim file's non-empty lines with the streaming reader, so a claim
|
|
@@ -499,6 +970,10 @@ function recoverClaims(claimFiles) {
|
|
|
499
970
|
export function recoverOrphanClaims(root) {
|
|
500
971
|
return recoverClaims(listOrphanClaimFiles(root));
|
|
501
972
|
}
|
|
973
|
+
/** Every orphaned claim file, spool and held, oldest name first. */
|
|
974
|
+
export function listOrphanClaims(root) {
|
|
975
|
+
return listOrphanClaimFiles(root);
|
|
976
|
+
}
|
|
502
977
|
/** Orphaned claim files of the spool only (never held claims). */
|
|
503
978
|
export function listOrphanSpoolClaims(root) {
|
|
504
979
|
try {
|
|
@@ -508,13 +983,6 @@ export function listOrphanSpoolClaims(root) {
|
|
|
508
983
|
return [];
|
|
509
984
|
}
|
|
510
985
|
}
|
|
511
|
-
/**
|
|
512
|
-
* {@link recoverOrphanClaims} for spool claims only. Used when the member has
|
|
513
|
-
* HQ Anywhere switched off: held lines and held claims are left where they are.
|
|
514
|
-
*/
|
|
515
|
-
export function recoverOrphanSpoolClaims(root) {
|
|
516
|
-
return recoverClaims(listOrphanSpoolClaims(root));
|
|
517
|
-
}
|
|
518
986
|
export function removeClaimFile(claimPath) {
|
|
519
987
|
if (!claimPath)
|
|
520
988
|
return;
|
|
@@ -523,7 +991,9 @@ export function removeClaimFile(claimPath) {
|
|
|
523
991
|
}
|
|
524
992
|
catch {
|
|
525
993
|
// leave for audit if unlink fails
|
|
994
|
+
return;
|
|
526
995
|
}
|
|
996
|
+
fs.rmSync(parkedClaimTimesPath(claimPath), { force: true });
|
|
527
997
|
}
|
|
528
998
|
export function deadLetterNonEmpty(root) {
|
|
529
999
|
const dl = workMeshDeadLetterPath(root ?? workMeshRoot());
|
|
@@ -544,7 +1014,7 @@ const JSONL_READ_CHUNK_BYTES = 1024 * 1024;
|
|
|
544
1014
|
* string. Queue files (dead-letter especially) can grow past V8's ~512 MB
|
|
545
1015
|
* string ceiling, where readFileSync(..., "utf8") throws. Splits on the raw
|
|
546
1016
|
* newline byte so multi-byte UTF-8 sequences are never cut. Returns false when
|
|
547
|
-
* the file cannot be opened.
|
|
1017
|
+
* the file cannot be opened. A visitor that returns `false` stops the read.
|
|
548
1018
|
*/
|
|
549
1019
|
export function forEachJsonlLine(filePath, visit) {
|
|
550
1020
|
let fd;
|
|
@@ -564,7 +1034,8 @@ export function forEachJsonlLine(filePath, visit) {
|
|
|
564
1034
|
let data = carry.length > 0 ? Buffer.concat([carry, chunk.subarray(0, n)]) : chunk.subarray(0, n);
|
|
565
1035
|
let start = 0;
|
|
566
1036
|
for (let nl = data.indexOf(0x0a, start); nl !== -1; nl = data.indexOf(0x0a, start)) {
|
|
567
|
-
visit(data.toString("utf8", start, nl))
|
|
1037
|
+
if (visit(data.toString("utf8", start, nl)) === false)
|
|
1038
|
+
return true;
|
|
568
1039
|
start = nl + 1;
|
|
569
1040
|
}
|
|
570
1041
|
carry = Buffer.from(data.subarray(start));
|
|
@@ -578,6 +1049,250 @@ export function forEachJsonlLine(filePath, visit) {
|
|
|
578
1049
|
}
|
|
579
1050
|
return true;
|
|
580
1051
|
}
|
|
1052
|
+
/** Let timers, sockets and MQTT keepalives run between read chunks. */
|
|
1053
|
+
export const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
|
|
1054
|
+
/**
|
|
1055
|
+
* {@link forEachJsonlLine}, yielding to the event loop after every full read
|
|
1056
|
+
* chunk (1 MB), so a read of a very large file does not hold up timers,
|
|
1057
|
+
* sockets or MQTT keepalives for its whole length. A file under one chunk is
|
|
1058
|
+
* read without yielding. Lines are visited in the same order
|
|
1059
|
+
* with the same content. Returns false when the file cannot be opened.
|
|
1060
|
+
*/
|
|
1061
|
+
export async function forEachJsonlLineAsync(filePath, visit, yieldNow = yieldToEventLoop) {
|
|
1062
|
+
const read = await readJsonlRangeAsync(filePath, 0, Number.POSITIVE_INFINITY, visit, yieldNow, true);
|
|
1063
|
+
return read !== null;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* Read a JSONL file: synchronously when it fits in one read chunk (no pause,
|
|
1067
|
+
* no extra promise, as before), otherwise with {@link forEachJsonlLineAsync}.
|
|
1068
|
+
* Callers await only a promise result.
|
|
1069
|
+
*/
|
|
1070
|
+
export function forEachJsonlLineYielding(filePath, visit) {
|
|
1071
|
+
let size = 0;
|
|
1072
|
+
try {
|
|
1073
|
+
size = fs.statSync(filePath).size;
|
|
1074
|
+
}
|
|
1075
|
+
catch {
|
|
1076
|
+
return false;
|
|
1077
|
+
}
|
|
1078
|
+
return size <= JSONL_READ_CHUNK_BYTES ? forEachJsonlLine(filePath, visit) : forEachJsonlLineAsync(filePath, visit);
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Read the lines of `filePath` that end before byte `end`, from byte `start`,
|
|
1082
|
+
* yielding after every chunk. With `trailing`, a last line without a newline
|
|
1083
|
+
* is visited too. Returns the offset just past the last line visited, or null
|
|
1084
|
+
* when the file cannot be opened.
|
|
1085
|
+
*/
|
|
1086
|
+
async function readJsonlRangeAsync(filePath, start, end, visit, yieldNow, trailing) {
|
|
1087
|
+
let fd;
|
|
1088
|
+
try {
|
|
1089
|
+
fd = fs.openSync(filePath, "r");
|
|
1090
|
+
}
|
|
1091
|
+
catch {
|
|
1092
|
+
return null;
|
|
1093
|
+
}
|
|
1094
|
+
let consumed = start;
|
|
1095
|
+
try {
|
|
1096
|
+
const chunk = Buffer.alloc(JSONL_READ_CHUNK_BYTES);
|
|
1097
|
+
let carry = Buffer.alloc(0);
|
|
1098
|
+
let position = start;
|
|
1099
|
+
while (position < end) {
|
|
1100
|
+
const want = Math.min(chunk.length, end - position);
|
|
1101
|
+
const n = fs.readSync(fd, chunk, 0, want, position);
|
|
1102
|
+
if (n <= 0)
|
|
1103
|
+
break;
|
|
1104
|
+
position += n;
|
|
1105
|
+
const data = carry.length > 0 ? Buffer.concat([carry, chunk.subarray(0, n)]) : chunk.subarray(0, n);
|
|
1106
|
+
let lineStart = 0;
|
|
1107
|
+
for (let nl = data.indexOf(0x0a, lineStart); nl !== -1; nl = data.indexOf(0x0a, lineStart)) {
|
|
1108
|
+
if (visit(data.toString("utf8", lineStart, nl)) === false)
|
|
1109
|
+
return position - (data.length - nl - 1);
|
|
1110
|
+
lineStart = nl + 1;
|
|
1111
|
+
}
|
|
1112
|
+
consumed = position - (data.length - lineStart);
|
|
1113
|
+
carry = Buffer.from(data.subarray(lineStart));
|
|
1114
|
+
// Yield only after a full chunk, when more of the file is likely to
|
|
1115
|
+
// follow: a file smaller than one chunk is read without a pause, as
|
|
1116
|
+
// before.
|
|
1117
|
+
if (n === chunk.length)
|
|
1118
|
+
await yieldNow();
|
|
1119
|
+
}
|
|
1120
|
+
if (trailing && carry.length > 0) {
|
|
1121
|
+
visit(carry.toString("utf8"));
|
|
1122
|
+
consumed += carry.length;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
finally {
|
|
1126
|
+
fs.closeSync(fd);
|
|
1127
|
+
}
|
|
1128
|
+
return consumed;
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* Visit the complete lines of a file from byte `offset` on. Returns the
|
|
1132
|
+
* offset just past the last complete line read (a partial last line is left
|
|
1133
|
+
* for the next read), or null when the file cannot be opened.
|
|
1134
|
+
*/
|
|
1135
|
+
function forEachJsonlLineFrom(filePath, offset, visit) {
|
|
1136
|
+
let fd;
|
|
1137
|
+
try {
|
|
1138
|
+
fd = fs.openSync(filePath, "r");
|
|
1139
|
+
}
|
|
1140
|
+
catch {
|
|
1141
|
+
return null;
|
|
1142
|
+
}
|
|
1143
|
+
let consumed = offset;
|
|
1144
|
+
try {
|
|
1145
|
+
const chunk = Buffer.alloc(JSONL_READ_CHUNK_BYTES);
|
|
1146
|
+
let carry = Buffer.alloc(0);
|
|
1147
|
+
let position = offset;
|
|
1148
|
+
for (;;) {
|
|
1149
|
+
const n = fs.readSync(fd, chunk, 0, chunk.length, position);
|
|
1150
|
+
if (n <= 0)
|
|
1151
|
+
break;
|
|
1152
|
+
position += n;
|
|
1153
|
+
const data = carry.length > 0 ? Buffer.concat([carry, chunk.subarray(0, n)]) : chunk.subarray(0, n);
|
|
1154
|
+
let start = 0;
|
|
1155
|
+
for (let nl = data.indexOf(0x0a, start); nl !== -1; nl = data.indexOf(0x0a, start)) {
|
|
1156
|
+
visit(data.toString("utf8", start, nl));
|
|
1157
|
+
start = nl + 1;
|
|
1158
|
+
}
|
|
1159
|
+
consumed = position - (data.length - start);
|
|
1160
|
+
carry = Buffer.from(data.subarray(start));
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
finally {
|
|
1164
|
+
fs.closeSync(fd);
|
|
1165
|
+
}
|
|
1166
|
+
return consumed;
|
|
1167
|
+
}
|
|
1168
|
+
const deadLetterIdIndexes = new Map();
|
|
1169
|
+
/** How the dead-letter id index was kept up to date (tests read this). */
|
|
1170
|
+
export const deadLetterIdIndexStats = { fullScans: 0, tailReads: 0 };
|
|
1171
|
+
/** Forget remembered dead-letter ids (tests). */
|
|
1172
|
+
export function resetDeadLetterIdIndexes() {
|
|
1173
|
+
deadLetterIdIndexes.clear();
|
|
1174
|
+
deadLetterIdIndexStats.fullScans = 0;
|
|
1175
|
+
deadLetterIdIndexStats.tailReads = 0;
|
|
1176
|
+
}
|
|
1177
|
+
/** Call with the dead-letter lock held. */
|
|
1178
|
+
function deadLetterIds(dl) {
|
|
1179
|
+
let stat;
|
|
1180
|
+
try {
|
|
1181
|
+
stat = fs.statSync(dl);
|
|
1182
|
+
}
|
|
1183
|
+
catch {
|
|
1184
|
+
deadLetterIdIndexes.delete(dl);
|
|
1185
|
+
return new Set();
|
|
1186
|
+
}
|
|
1187
|
+
let index = deadLetterIdIndexes.get(dl);
|
|
1188
|
+
if (!index || index.ino !== stat.ino || stat.size < index.offset) {
|
|
1189
|
+
index = { ino: stat.ino, offset: 0, ids: new Set() };
|
|
1190
|
+
deadLetterIdIndexStats.fullScans += 1;
|
|
1191
|
+
}
|
|
1192
|
+
else if (stat.size > index.offset) {
|
|
1193
|
+
deadLetterIdIndexStats.tailReads += 1;
|
|
1194
|
+
}
|
|
1195
|
+
else {
|
|
1196
|
+
return index.ids;
|
|
1197
|
+
}
|
|
1198
|
+
const ids = index.ids;
|
|
1199
|
+
const end = forEachJsonlLineFrom(dl, index.offset, (line) => {
|
|
1200
|
+
if (!line.trim())
|
|
1201
|
+
return;
|
|
1202
|
+
const eventId = heldEventId(line);
|
|
1203
|
+
if (eventId)
|
|
1204
|
+
ids.add(eventId);
|
|
1205
|
+
});
|
|
1206
|
+
if (end === null) {
|
|
1207
|
+
deadLetterIdIndexes.delete(dl);
|
|
1208
|
+
return ids;
|
|
1209
|
+
}
|
|
1210
|
+
index.offset = end;
|
|
1211
|
+
deadLetterIdIndexes.set(dl, index);
|
|
1212
|
+
return ids;
|
|
1213
|
+
}
|
|
1214
|
+
/** A dead-letter file at least this large is compacted when the daemon starts. */
|
|
1215
|
+
export const DEAD_LETTER_COMPACT_MIN_BYTES = 50 * 1024 * 1024;
|
|
1216
|
+
/**
|
|
1217
|
+
* Rewrite dead-letter.jsonl keeping the first line per eventId (lines with no
|
|
1218
|
+
* eventId are all kept). Nothing is expired by age. The file is read with the
|
|
1219
|
+
* event loop yielding between chunks and written to a temp file; then, under
|
|
1220
|
+
* the dead-letter lock, lines appended meanwhile are added and the temp file
|
|
1221
|
+
* is renamed over the original. Below `minBytes` nothing is done.
|
|
1222
|
+
*/
|
|
1223
|
+
export async function compactDeadLetter(root, opts = {}) {
|
|
1224
|
+
const dl = workMeshDeadLetterPath(root);
|
|
1225
|
+
const minBytes = opts.minBytes ?? DEAD_LETTER_COMPACT_MIN_BYTES;
|
|
1226
|
+
const none = (bytes) => ({
|
|
1227
|
+
compacted: false, linesBefore: 0, linesAfter: 0, bytesBefore: bytes, bytesAfter: bytes,
|
|
1228
|
+
});
|
|
1229
|
+
let before;
|
|
1230
|
+
try {
|
|
1231
|
+
before = fs.statSync(dl);
|
|
1232
|
+
}
|
|
1233
|
+
catch {
|
|
1234
|
+
return none(0);
|
|
1235
|
+
}
|
|
1236
|
+
if (before.size < minBytes)
|
|
1237
|
+
return none(before.size);
|
|
1238
|
+
const tmp = `${dl}.${process.pid}.${randomBytes(6).toString("hex")}.compact.tmp`;
|
|
1239
|
+
const ids = new Set();
|
|
1240
|
+
let linesBefore = 0;
|
|
1241
|
+
let linesAfter = 0;
|
|
1242
|
+
const out = new JsonlAppender(tmp);
|
|
1243
|
+
const keep = (line) => {
|
|
1244
|
+
if (!line.trim())
|
|
1245
|
+
return;
|
|
1246
|
+
linesBefore += 1;
|
|
1247
|
+
const eventId = heldEventId(line);
|
|
1248
|
+
if (eventId) {
|
|
1249
|
+
if (ids.has(eventId))
|
|
1250
|
+
return;
|
|
1251
|
+
ids.add(eventId);
|
|
1252
|
+
}
|
|
1253
|
+
out.push(line);
|
|
1254
|
+
linesAfter += 1;
|
|
1255
|
+
};
|
|
1256
|
+
try {
|
|
1257
|
+
// Read the complete lines present at the start; later appends (and a
|
|
1258
|
+
// partial last line) are taken under the lock.
|
|
1259
|
+
const consumed = await readJsonlRangeAsync(dl, 0, before.size, keep, opts.yieldNow ?? yieldToEventLoop, false);
|
|
1260
|
+
if (consumed === null)
|
|
1261
|
+
return none(before.size);
|
|
1262
|
+
out.flush();
|
|
1263
|
+
return withJsonlLock(dl, () => {
|
|
1264
|
+
let current;
|
|
1265
|
+
try {
|
|
1266
|
+
current = fs.statSync(dl);
|
|
1267
|
+
}
|
|
1268
|
+
catch {
|
|
1269
|
+
return none(0);
|
|
1270
|
+
}
|
|
1271
|
+
if (current.ino !== before.ino || current.size < before.size) {
|
|
1272
|
+
// Replaced or truncated by someone else meanwhile: leave it alone.
|
|
1273
|
+
return none(current.size);
|
|
1274
|
+
}
|
|
1275
|
+
forEachJsonlLineFrom(dl, consumed, keep);
|
|
1276
|
+
out.flush();
|
|
1277
|
+
ensureSpoolFile(tmp);
|
|
1278
|
+
const fd = fs.openSync(tmp, "r");
|
|
1279
|
+
try {
|
|
1280
|
+
fs.fsyncSync(fd);
|
|
1281
|
+
}
|
|
1282
|
+
finally {
|
|
1283
|
+
fs.closeSync(fd);
|
|
1284
|
+
}
|
|
1285
|
+
fs.renameSync(tmp, dl);
|
|
1286
|
+
chmodOwnerFile(dl);
|
|
1287
|
+
deadLetterIdIndexes.delete(dl);
|
|
1288
|
+
const bytesAfter = fs.statSync(dl).size;
|
|
1289
|
+
return { compacted: true, linesBefore, linesAfter, bytesBefore: current.size, bytesAfter };
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
finally {
|
|
1293
|
+
fs.rmSync(tmp, { force: true });
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
581
1296
|
export function countJsonlLines(filePath) {
|
|
582
1297
|
let n = 0;
|
|
583
1298
|
forEachJsonlLine(filePath, (line) => {
|