engine7 7.1.137 → 7.1.140
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/bg-worker.mjs +133 -127
- package/dist/cli.mjs +4418 -3209
- package/dist/cpu-router-worker.mjs +604 -8
- package/dist/device-connectors/reader +0 -0
- package/dist/engine-startup.mjs +10270 -5968
- package/dist/main.mjs +10262 -5939
- package/dist/optional-deps.json +78 -0
- package/dist/recall-worker.mjs +57 -53
- package/dist/sqlite-maintenance-worker.mjs +16 -18
- package/dist/topics-worker.mjs +56 -52
- package/dist/travel-authority.mjs +71 -25
- package/dist/travel-console.mjs +301 -110
- package/dist/travel-controller.mjs +321 -56
- package/dist/travel-data.mjs +655 -351
- package/dist/travel-gateway.mjs +34863 -2643
- package/dist/travel-host.mjs +43421 -0
- package/dist/travel-node-data.mjs +609 -281
- package/dist/travel-node.mjs +1424 -621
- package/dist/travel-pairing.mjs +35915 -0
- package/dist/travel-resource.mjs +131 -0
- package/dist/travel-retire.mjs +136 -60
- package/dist/web-console.mjs +2095 -290
- package/package.json +17 -8
- package/scripts/verify-cpu-router-package.mjs +14 -1
- package/templates/config.template.json +14 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
2
|
|
|
3
3
|
// src/continuity/controller-main.ts
|
|
4
|
-
import { readFileSync as
|
|
5
|
-
import { isAbsolute, resolve as
|
|
4
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
5
|
+
import { isAbsolute as isAbsolute2, resolve as resolve3 } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
|
|
8
8
|
// src/continuity/controller.ts
|
|
@@ -19,19 +19,15 @@ import {
|
|
|
19
19
|
fstatSync,
|
|
20
20
|
fsyncSync,
|
|
21
21
|
readSync,
|
|
22
|
-
writeSync,
|
|
23
22
|
lstatSync,
|
|
24
23
|
realpathSync,
|
|
25
|
-
mkdirSync
|
|
26
|
-
readFileSync,
|
|
27
|
-
writeFileSync,
|
|
28
|
-
linkSync,
|
|
29
|
-
unlinkSync
|
|
24
|
+
mkdirSync
|
|
30
25
|
} from "node:fs";
|
|
31
26
|
import { join, dirname, resolve } from "node:path";
|
|
32
27
|
var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
|
|
33
28
|
var HASH = /^[a-f0-9]{64}$/;
|
|
34
29
|
var MAGIC = Buffer.from("E7P1");
|
|
30
|
+
var INLINE_BYTES = 64 * 1024;
|
|
35
31
|
var noFollow = constants.O_NOFOLLOW ?? 0;
|
|
36
32
|
function validateObjectRef(ref) {
|
|
37
33
|
if (!ref || !HASH.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > PUBLICATION_CHUNK_BYTES)
|
|
@@ -143,7 +139,7 @@ var TravelController = class {
|
|
|
143
139
|
if (!binding.length) this.db.prepare("INSERT INTO binding VALUES(?)").run(identity);
|
|
144
140
|
else if (binding.length !== 1 || binding[0].identity !== identity) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
145
141
|
this.db.prepare("INSERT OR IGNORE INTO preferences VALUES(1,?)").run(options.preferredNodeId);
|
|
146
|
-
this.db.
|
|
142
|
+
this.db.prepare("INSERT OR IGNORE INTO automatic VALUES(1,?)").run(options.initialAutomatic === false ? 0 : 1);
|
|
147
143
|
if (!options.nodes[this.preferredNodeId()]) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
148
144
|
if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_CONTROLLER_RECOVERY_REQUIRED");
|
|
149
145
|
} catch (error) {
|
|
@@ -213,6 +209,39 @@ var TravelController = class {
|
|
|
213
209
|
});
|
|
214
210
|
return this.active;
|
|
215
211
|
}
|
|
212
|
+
/** Manual synchronization shares the controller's mutation slot with ticks
|
|
213
|
+
* and handoffs, and leaves the owner's automatic preference untouched. */
|
|
214
|
+
synchronize() {
|
|
215
|
+
if (this.closed) return Promise.reject(new Error("TRAVEL_CONTROLLER_CLOSED"));
|
|
216
|
+
if (this.active || this.job()) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
|
|
217
|
+
const operation = (async () => {
|
|
218
|
+
const reference = this.options.nodes[this.preferredNodeId()];
|
|
219
|
+
const current = await this.options.authority.status(reference.principal);
|
|
220
|
+
const source = current.activeNodeId ? this.options.nodes[current.activeNodeId] : void 0;
|
|
221
|
+
if (current.expired || !source || !source.synchronize) throw new Error("not_ready");
|
|
222
|
+
const target = Object.values(this.options.nodes).find((node) => node !== source);
|
|
223
|
+
const observations = await Promise.all([source.observe(), target.observe()]);
|
|
224
|
+
if (observations.some((node) => !node.connected || node.busy) || !observations[0].running) throw new Error("not_ready");
|
|
225
|
+
const permit = await source.permit();
|
|
226
|
+
await this.options.authority.assertPermit(permit, "CONTROL");
|
|
227
|
+
const assertSource = async () => {
|
|
228
|
+
const renewed = await source.permit();
|
|
229
|
+
if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((field) => renewed[field] !== permit[field])) throw new Error("TRAVEL_CONTROLLER_COMMIT_SUPERSEDED");
|
|
230
|
+
await this.options.authority.assertPermit(renewed, "CONTROL");
|
|
231
|
+
};
|
|
232
|
+
if (!await this.replicate(source, target)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
233
|
+
await assertSource();
|
|
234
|
+
await source.synchronize();
|
|
235
|
+
await assertSource();
|
|
236
|
+
})();
|
|
237
|
+
this.active = operation.catch((error) => {
|
|
238
|
+
this.lastError = error instanceof Error && /^TRAVEL_[A-Z_]+$/.test(error.message) ? error.message : "TRAVEL_CONTROLLER_OPERATION_FAILED";
|
|
239
|
+
throw error;
|
|
240
|
+
}).finally(() => {
|
|
241
|
+
this.active = void 0;
|
|
242
|
+
});
|
|
243
|
+
return this.active;
|
|
244
|
+
}
|
|
216
245
|
async launch(node, permit, checkpoint) {
|
|
217
246
|
const prior = this.db.prepare("SELECT checkpoint FROM starts WHERE node=? AND boot=? AND epoch=?").get(permit.nodeId, permit.bootId, permit.epoch);
|
|
218
247
|
if (prior) {
|
|
@@ -263,19 +292,28 @@ var TravelController = class {
|
|
|
263
292
|
this.healthySince = null;
|
|
264
293
|
const candidates = Object.values(this.options.nodes).sort((a, b) => Number(a.principal.nodeId === status.activeNodeId) - Number(b.principal.nodeId === status.activeNodeId) || Number(a.principal.role !== "CLOUD") - Number(b.principal.role !== "CLOUD"));
|
|
265
294
|
let node;
|
|
295
|
+
let missingCheckpoint = false;
|
|
266
296
|
for (const candidate of candidates) if ((await candidate.observe()).connected === true) {
|
|
267
|
-
|
|
268
|
-
|
|
297
|
+
try {
|
|
298
|
+
await candidate.pinBranch(status.checkpointDigest);
|
|
299
|
+
node = candidate;
|
|
300
|
+
break;
|
|
301
|
+
} catch (error) {
|
|
302
|
+
if (!(error instanceof Error) || error.message !== "TRAVEL_NODE_COMMON_CHECKPOINT") throw error;
|
|
303
|
+
missingCheckpoint = true;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (!node) {
|
|
307
|
+
if (missingCheckpoint) throw new Error("TRAVEL_NODE_COMMON_CHECKPOINT");
|
|
308
|
+
return;
|
|
269
309
|
}
|
|
270
|
-
if (!node) return;
|
|
271
|
-
await node.pinBranch(status.checkpointDigest);
|
|
272
310
|
const ready = await node.prepare(status.checkpointDigest);
|
|
273
311
|
const latest = await this.options.authority.status(node.principal);
|
|
274
312
|
if (latest.authorityBootId !== status.authorityBootId || latest.epoch !== status.epoch || latest.checkpointDigest !== status.checkpointDigest || latest.deletionWatermark !== status.deletionWatermark || latest.activeNodeId && !latest.expired) return;
|
|
275
313
|
const permit = await this.options.authority.acquire(node.principal, ready);
|
|
276
314
|
await this.launch(node, permit, status.checkpointDigest);
|
|
277
315
|
}
|
|
278
|
-
async replicate(source, target) {
|
|
316
|
+
async replicate(source, target, recheckBranches = false) {
|
|
279
317
|
if (!source.replicationOffer || !source.connectReplica || !target.replicaProfile || !target.bootstrapReplica) return true;
|
|
280
318
|
const offer = await source.replicationOffer();
|
|
281
319
|
if (!offer) return true;
|
|
@@ -295,8 +333,11 @@ var TravelController = class {
|
|
|
295
333
|
if (!profile || JSON.stringify(profile) !== JSON.stringify(offer.profile)) throw new Error("TRAVEL_CONTROLLER_REPLICA");
|
|
296
334
|
await assertSource();
|
|
297
335
|
await source.connectReplica(profile);
|
|
298
|
-
|
|
299
|
-
|
|
336
|
+
if (recheckBranches) {
|
|
337
|
+
const recovered = await source.recoverBranches?.();
|
|
338
|
+
if (recovered && recovered.unresolvedCritical !== 0) return false;
|
|
339
|
+
}
|
|
340
|
+
return true;
|
|
300
341
|
}
|
|
301
342
|
async advance(job) {
|
|
302
343
|
const target = this.options.nodes[job.target], control = this.options.authority;
|
|
@@ -310,7 +351,7 @@ var TravelController = class {
|
|
|
310
351
|
}
|
|
311
352
|
const source2 = this.options.nodes[status.activeNodeId];
|
|
312
353
|
if (!source2) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
313
|
-
if (!await this.replicate(source2, target)) return;
|
|
354
|
+
if (!await this.replicate(source2, target, true)) return;
|
|
314
355
|
this.db.prepare("UPDATE jobs SET source=?,state='PREPARING' WHERE id=?").run(source2.principal.nodeId, job.id);
|
|
315
356
|
await control.beginHandoff(source2.principal, await source2.permit(), job.id, job.target);
|
|
316
357
|
return;
|
|
@@ -397,14 +438,16 @@ var TravelController = class {
|
|
|
397
438
|
this.timer = setTimeout(() => {
|
|
398
439
|
this.timer = void 0;
|
|
399
440
|
const started = this.clock();
|
|
400
|
-
void this.tick().
|
|
441
|
+
void this.tick().catch(() => {
|
|
442
|
+
}).finally(() => this.schedule(this.interval - (this.clock() - started) % this.interval));
|
|
401
443
|
}, delay);
|
|
402
444
|
}
|
|
403
445
|
async stop() {
|
|
404
446
|
this.running = false;
|
|
405
447
|
if (this.timer) clearTimeout(this.timer);
|
|
406
448
|
this.timer = void 0;
|
|
407
|
-
await this.active
|
|
449
|
+
await this.active?.catch(() => {
|
|
450
|
+
});
|
|
408
451
|
}
|
|
409
452
|
close() {
|
|
410
453
|
if (this.closed) return;
|
|
@@ -505,9 +548,12 @@ var TravelReportClient = class {
|
|
|
505
548
|
this.timeout = options.timeoutMs ?? 8e3;
|
|
506
549
|
if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
|
|
507
550
|
this.key = options.key ? Buffer.from(options.key) : void 0;
|
|
508
|
-
|
|
551
|
+
const tls = { ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, maxSockets: 1 };
|
|
552
|
+
this.agent = new Agent({ ...tls, keepAlive: true });
|
|
553
|
+
this.mutationAgent = new Agent({ ...tls, keepAlive: false });
|
|
509
554
|
}
|
|
510
555
|
agent;
|
|
556
|
+
mutationAgent;
|
|
511
557
|
key;
|
|
512
558
|
url;
|
|
513
559
|
timeout;
|
|
@@ -524,7 +570,7 @@ var TravelReportClient = class {
|
|
|
524
570
|
const unavailable = () => new Error(this.closed ? "TRAVEL_CONTROL_CLOSED" : "TRAVEL_CONTROL_UNAVAILABLE");
|
|
525
571
|
const remaining = deadline - performance.now();
|
|
526
572
|
if (remaining <= 0) return Promise.reject(unavailable());
|
|
527
|
-
return new Promise((
|
|
573
|
+
return new Promise((resolve4, reject) => {
|
|
528
574
|
let complete = false, responseStarted = false;
|
|
529
575
|
const finish = (error, value) => {
|
|
530
576
|
if (complete) return;
|
|
@@ -532,9 +578,9 @@ var TravelReportClient = class {
|
|
|
532
578
|
clearTimeout(timer);
|
|
533
579
|
this.pending.delete(req);
|
|
534
580
|
if (error) reject(error);
|
|
535
|
-
else
|
|
581
|
+
else resolve4(value);
|
|
536
582
|
};
|
|
537
|
-
const req = request(this.url, { method: "POST", agent: this.agent, headers: {
|
|
583
|
+
const req = request(this.url, { method: "POST", agent: readActions.has(input?.action) ? this.agent : this.mutationAgent, headers: {
|
|
538
584
|
Authorization: "Bearer " + this.options.credential,
|
|
539
585
|
"X-Engine7-Travel-Node": this.options.nodeId,
|
|
540
586
|
"Content-Type": "application/json",
|
|
@@ -585,7 +631,7 @@ var TravelReportClient = class {
|
|
|
585
631
|
complete = true;
|
|
586
632
|
clearTimeout(timer);
|
|
587
633
|
this.pending.delete(req);
|
|
588
|
-
|
|
634
|
+
resolve4(this.attempt(input, false, deadline, body));
|
|
589
635
|
} else finish(unavailable());
|
|
590
636
|
});
|
|
591
637
|
req.once("close", () => {
|
|
@@ -609,6 +655,7 @@ var TravelReportClient = class {
|
|
|
609
655
|
this.closed = true;
|
|
610
656
|
for (const req of this.pending) req.destroy();
|
|
611
657
|
this.agent.destroy();
|
|
658
|
+
this.mutationAgent.destroy();
|
|
612
659
|
this.key?.fill(0);
|
|
613
660
|
}
|
|
614
661
|
};
|
|
@@ -635,6 +682,9 @@ var TravelManagementClient = class extends TravelReportClient {
|
|
|
635
682
|
if (url.pathname !== "/travel/manage/v1") throw new Error("TRAVEL_MANAGEMENT_ENDPOINT_REQUIRED");
|
|
636
683
|
super(options);
|
|
637
684
|
}
|
|
685
|
+
async bindInitialCheckpoint(digest2, buildManifestId) {
|
|
686
|
+
await this.call({ action: "bindInitialCheckpoint", digest: digest2, buildManifestId });
|
|
687
|
+
}
|
|
638
688
|
async verifyAncestor(ancestor, descendant) {
|
|
639
689
|
await this.call({ action: "verifyAncestor", ancestor, descendant });
|
|
640
690
|
}
|
|
@@ -656,6 +706,9 @@ var TravelManagementClient = class extends TravelReportClient {
|
|
|
656
706
|
async assertPermit(permit, operation) {
|
|
657
707
|
await this.call({ action: "assertPermit", permit, operation });
|
|
658
708
|
}
|
|
709
|
+
async assertPermitWithStatus(permit, operation) {
|
|
710
|
+
return (await this.call({ action: "assertPermit", permit, operation })).status;
|
|
711
|
+
}
|
|
659
712
|
async acquire(ready) {
|
|
660
713
|
return (await this.call({ action: "acquire", ready })).permit;
|
|
661
714
|
}
|
|
@@ -691,7 +744,22 @@ import { Agent as Agent2, request as request2 } from "node:https";
|
|
|
691
744
|
// src/continuity/publication.ts
|
|
692
745
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
693
746
|
import { createHash } from "node:crypto";
|
|
694
|
-
|
|
747
|
+
|
|
748
|
+
// src/continuity/inventory.ts
|
|
749
|
+
import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "node:path";
|
|
750
|
+
var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
|
|
751
|
+
var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
|
|
752
|
+
var CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
|
|
753
|
+
function validateRelativePath(path2) {
|
|
754
|
+
if (typeof path2 !== "string" || !path2 || path2.length > 2048 || isAbsolute(path2)) throw new Error("INVALID_ARTIFACT_PATH");
|
|
755
|
+
for (const part of path2.split("/")) {
|
|
756
|
+
if (!part || part === "." || part === ".." || /[\x00-\x1f]/.test(part) || Buffer.byteLength(part) > 255 || process.platform === "win32" && (/[<>:"|?*\\]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part)))
|
|
757
|
+
throw new Error("INVALID_ARTIFACT_PATH");
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// src/continuity/publication.ts
|
|
762
|
+
var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
|
|
695
763
|
var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
|
|
696
764
|
var ZERO = "0".repeat(64);
|
|
697
765
|
var HASH2 = /^[a-f0-9]{64}$/;
|
|
@@ -732,8 +800,12 @@ function normalizePublicationProfile(value) {
|
|
|
732
800
|
return Object.freeze(profile);
|
|
733
801
|
}
|
|
734
802
|
function validatePublicationPath(path2) {
|
|
735
|
-
if (typeof path2 !== "string" ||
|
|
803
|
+
if (typeof path2 !== "string" || path2.normalize("NFC") !== path2) throw new Error("PUBLICATION_INVALID_PATH");
|
|
804
|
+
try {
|
|
805
|
+
validateRelativePath(path2);
|
|
806
|
+
} catch {
|
|
736
807
|
throw new Error("PUBLICATION_INVALID_PATH");
|
|
808
|
+
}
|
|
737
809
|
}
|
|
738
810
|
function normalizePublication(value) {
|
|
739
811
|
if (!value || value.format !== "engine7-publication-v1" || !natural(value.sequence) || !value.sequence || !HASH2.test(value.parentDigest) || !natural(value.deletionWatermark) || !Array.isArray(value.databases) || !Array.isArray(value.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
|
|
@@ -809,6 +881,7 @@ var nodeSupervisorErrors = /* @__PURE__ */ new Set([
|
|
|
809
881
|
"TRAVEL_NODE_CANCELLED",
|
|
810
882
|
"TRAVEL_NODE_BOOT_MISMATCH",
|
|
811
883
|
"TRAVEL_NODE_CHECKPOINT",
|
|
884
|
+
"TRAVEL_NODE_COMMON_CHECKPOINT",
|
|
812
885
|
"TRAVEL_NODE_GENERATION_COLLISION",
|
|
813
886
|
"TRAVEL_NODE_KEY_UNAVAILABLE",
|
|
814
887
|
"TRAVEL_NODE_KEY_BARRIER",
|
|
@@ -842,7 +915,8 @@ var fields = {
|
|
|
842
915
|
replicaProfile: [],
|
|
843
916
|
bootstrapReplica: ["request"],
|
|
844
917
|
connectReplica: ["profile"],
|
|
845
|
-
recoverBranches: []
|
|
918
|
+
recoverBranches: [],
|
|
919
|
+
synchronize: []
|
|
846
920
|
};
|
|
847
921
|
function exact(value, allowed, required = allowed) {
|
|
848
922
|
return Object.keys(value).every((key) => allowed.includes(key)) && required.every((key) => Object.hasOwn(value, key));
|
|
@@ -899,31 +973,53 @@ var RemoteTravelNodeSupervisor = class {
|
|
|
899
973
|
observeQuery;
|
|
900
974
|
permitQuery;
|
|
901
975
|
closed = false;
|
|
902
|
-
call(action, args = {}, discover = false) {
|
|
976
|
+
call(action, args = {}, discover = false, retryStale = true, deadline, wireBody) {
|
|
903
977
|
if (this.closed) return Promise.reject(new Error("TRAVEL_NODE_CLOSED"));
|
|
904
978
|
const slot = action === "stop" ? "stop" : action === "observe" ? "observe" : action === "permit" ? "permit" : "operation";
|
|
905
979
|
if ([...this.pending.values()].includes(slot)) return Promise.reject(new Error("TRAVEL_NODE_BUSY"));
|
|
906
|
-
const body = Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
|
|
980
|
+
const body = wireBody ?? Buffer.from(JSON.stringify({ node: { version: 1, nodeId: this.principal.nodeId, ...discover ? {} : { bootId: this.bootId }, action, ...args } }));
|
|
907
981
|
if (body.length > nodeSupervisorLimit) return Promise.reject(new Error("TRAVEL_NODE_INVALID_REQUEST"));
|
|
908
982
|
const unavailable = () => new Error(this.closed ? "TRAVEL_NODE_CLOSED" : "TRAVEL_NODE_UNAVAILABLE");
|
|
909
|
-
|
|
983
|
+
deadline ??= performance.now() + (slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
|
|
984
|
+
const remaining = deadline - performance.now();
|
|
985
|
+
if (remaining <= 0) return Promise.reject(unavailable());
|
|
986
|
+
return new Promise((resolve4, reject) => {
|
|
987
|
+
const started = performance.now();
|
|
988
|
+
let responseStarted = false, receivedBytes = 0, reported = false;
|
|
989
|
+
const lost = (code) => {
|
|
990
|
+
if (!reported && slot !== "observe") process.stderr.write("[travel-node-client] " + JSON.stringify({
|
|
991
|
+
at: Date.now(),
|
|
992
|
+
action,
|
|
993
|
+
nodeId: this.principal.nodeId,
|
|
994
|
+
phase: responseStarted ? "response" : "request",
|
|
995
|
+
elapsedMs: Math.round(performance.now() - started),
|
|
996
|
+
receivedBytes,
|
|
997
|
+
reusedSocket: req.reusedSocket,
|
|
998
|
+
code: typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : "OTHER"
|
|
999
|
+
}) + "\n");
|
|
1000
|
+
reported = true;
|
|
1001
|
+
reject(unavailable());
|
|
1002
|
+
};
|
|
910
1003
|
const req = request2(this.url, { method: "POST", agent: this.agents[slot], headers: {
|
|
911
1004
|
Authorization: "Bearer " + this.options.credential,
|
|
912
1005
|
"X-Engine7-Travel-Node": this.principal.nodeId,
|
|
913
1006
|
"Content-Type": "application/json",
|
|
914
1007
|
"Content-Length": body.length
|
|
915
1008
|
} }, (res) => {
|
|
1009
|
+
responseStarted = true;
|
|
916
1010
|
const parts = [];
|
|
917
1011
|
let bytes = 0;
|
|
918
1012
|
res.on("data", (part) => {
|
|
919
1013
|
bytes += part.length;
|
|
1014
|
+
receivedBytes = bytes;
|
|
920
1015
|
if (bytes > nodeSupervisorLimit) {
|
|
921
1016
|
req.destroy();
|
|
922
1017
|
reject(new Error("TRAVEL_NODE_INVALID_RESPONSE"));
|
|
923
1018
|
} else parts.push(part);
|
|
924
1019
|
});
|
|
925
|
-
res.once("error", () =>
|
|
1020
|
+
res.once("error", (error) => lost(error.code));
|
|
926
1021
|
res.once("end", () => {
|
|
1022
|
+
reported = true;
|
|
927
1023
|
cleanup();
|
|
928
1024
|
if (this.closed) {
|
|
929
1025
|
reject(unavailable());
|
|
@@ -946,21 +1042,24 @@ var RemoteTravelNodeSupervisor = class {
|
|
|
946
1042
|
return;
|
|
947
1043
|
}
|
|
948
1044
|
if (discover) this.bootId = response.bootId;
|
|
949
|
-
|
|
1045
|
+
resolve4(response.result);
|
|
950
1046
|
});
|
|
951
1047
|
});
|
|
952
1048
|
this.pending.set(req, slot);
|
|
953
1049
|
const timer = setTimeout(() => {
|
|
1050
|
+
lost("TIMEOUT");
|
|
954
1051
|
req.destroy();
|
|
955
|
-
|
|
956
|
-
}, slot === "observe" || slot === "permit" ? Math.min(this.timeout, 8e3) : this.timeout);
|
|
1052
|
+
}, remaining);
|
|
957
1053
|
const cleanup = () => {
|
|
958
1054
|
clearTimeout(timer);
|
|
959
1055
|
this.pending.delete(req);
|
|
960
1056
|
};
|
|
961
|
-
req.once("error", () => {
|
|
1057
|
+
req.once("error", (error) => {
|
|
962
1058
|
cleanup();
|
|
963
|
-
|
|
1059
|
+
if (!reported && retryStale && !this.closed && !responseStarted && (slot === "observe" || slot === "permit") && req.reusedSocket && error.code === "ECONNRESET") {
|
|
1060
|
+
reported = true;
|
|
1061
|
+
resolve4(this.call(action, args, discover, false, deadline, body));
|
|
1062
|
+
} else lost(error.code);
|
|
964
1063
|
});
|
|
965
1064
|
req.once("close", cleanup);
|
|
966
1065
|
req.end(body);
|
|
@@ -1030,6 +1129,9 @@ var RemoteTravelNodeSupervisor = class {
|
|
|
1030
1129
|
recoverBranches() {
|
|
1031
1130
|
return this.invoke("recoverBranches");
|
|
1032
1131
|
}
|
|
1132
|
+
synchronize() {
|
|
1133
|
+
return this.invoke("synchronize");
|
|
1134
|
+
}
|
|
1033
1135
|
close() {
|
|
1034
1136
|
if (this.closed) return;
|
|
1035
1137
|
this.closed = true;
|
|
@@ -1041,7 +1143,7 @@ var RemoteTravelNodeSupervisor = class {
|
|
|
1041
1143
|
|
|
1042
1144
|
// src/continuity/key-service-store.ts
|
|
1043
1145
|
import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
|
|
1044
|
-
import { constants as constants2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, closeSync as closeSync2, readFileSync
|
|
1146
|
+
import { constants as constants2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, closeSync as closeSync2, readFileSync, writeSync, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync } from "node:fs";
|
|
1045
1147
|
function assertPrivateStat(stat, directory) {
|
|
1046
1148
|
if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1047
1149
|
throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
|
|
@@ -1053,7 +1155,7 @@ function readPrivateFile(path2, maximumBytes = 65536) {
|
|
|
1053
1155
|
const stat = fstatSync2(fd);
|
|
1054
1156
|
assertPrivateStat(stat, false);
|
|
1055
1157
|
if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
|
|
1056
|
-
return
|
|
1158
|
+
return readFileSync(fd);
|
|
1057
1159
|
} finally {
|
|
1058
1160
|
closeSync2(fd);
|
|
1059
1161
|
}
|
|
@@ -1174,6 +1276,10 @@ function createTravelNodeSupervisorServer(options) {
|
|
|
1174
1276
|
if (!node.recoverBranches) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
|
|
1175
1277
|
result = await node.recoverBranches();
|
|
1176
1278
|
break;
|
|
1279
|
+
case "synchronize":
|
|
1280
|
+
if (!node.synchronize) throw new Error("TRAVEL_NODE_REPLICATION_PEER");
|
|
1281
|
+
result = await node.synchronize();
|
|
1282
|
+
break;
|
|
1177
1283
|
}
|
|
1178
1284
|
const body = JSON.stringify({ node: { version: 1, nodeId: node.principal.nodeId, bootId, result: result ?? null } });
|
|
1179
1285
|
if (Buffer.byteLength(body) > nodeSupervisorLimit) throw new Error("TRAVEL_NODE_RESPONSE_LIMIT");
|
|
@@ -1217,9 +1323,12 @@ var RemoteTravelDataAuthority = class {
|
|
|
1217
1323
|
this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
|
|
1218
1324
|
}
|
|
1219
1325
|
async authenticate(credential) {
|
|
1326
|
+
return Object.freeze({ ...(await this.readIdentity(credential)).principal });
|
|
1327
|
+
}
|
|
1328
|
+
readIdentity(credential) {
|
|
1220
1329
|
const grant = this.grants.find((grant2) => grant2.credential === credential);
|
|
1221
1330
|
if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1222
|
-
return
|
|
1331
|
+
return this.read(grant);
|
|
1223
1332
|
}
|
|
1224
1333
|
grant(principal) {
|
|
1225
1334
|
const grant = this.grants.find((grant2) => equal(principal, grant2.principal));
|
|
@@ -1260,6 +1369,7 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
|
|
|
1260
1369
|
this.publicKey = publicKey;
|
|
1261
1370
|
this.nodeGrants = nodeGrants;
|
|
1262
1371
|
}
|
|
1372
|
+
permitReads = /* @__PURE__ */ new Map();
|
|
1263
1373
|
static async open(options) {
|
|
1264
1374
|
try {
|
|
1265
1375
|
if (createPublicKey(options.publicKey).asymmetricKeyType !== "ed25519") throw new Error();
|
|
@@ -1268,9 +1378,8 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
|
|
|
1268
1378
|
}
|
|
1269
1379
|
const remote = new _RemoteTravelNodeAuthority(options.publicKey, options.grants);
|
|
1270
1380
|
for (const grant of options.grants) {
|
|
1271
|
-
const identity = await grant.
|
|
1381
|
+
const identity = await remote.readIdentity(grant.credential);
|
|
1272
1382
|
if (identity.publicKey !== options.publicKey) throw new Error("TRAVEL_NODE_SIGNER_MISMATCH");
|
|
1273
|
-
await remote.authenticate(grant.credential);
|
|
1274
1383
|
}
|
|
1275
1384
|
return remote;
|
|
1276
1385
|
}
|
|
@@ -1279,6 +1388,20 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
|
|
|
1279
1388
|
if (!grant) throw new Error("TRAVEL_AUTH_DENIED");
|
|
1280
1389
|
return grant.client;
|
|
1281
1390
|
}
|
|
1391
|
+
async assertPermit(...args) {
|
|
1392
|
+
await this.assertPermitWithStatus(...args);
|
|
1393
|
+
}
|
|
1394
|
+
assertPermitWithStatus(...[permit, operation]) {
|
|
1395
|
+
const grant = this.nodeGrants.find((value) => ["tenantId", "companionId", "seatId", "nodeId"].every((field) => permit[field] === value.principal[field]));
|
|
1396
|
+
if (!grant) return Promise.reject(new Error("TRAVEL_AUTH_DENIED"));
|
|
1397
|
+
const key = JSON.stringify([permit, operation]), pending = this.permitReads.get(key);
|
|
1398
|
+
if (pending) return pending;
|
|
1399
|
+
const read = grant.client.assertPermitWithStatus(permit, operation).then((current) => current === void 0 ? this.status(grant.principal) : current).finally(() => {
|
|
1400
|
+
this.permitReads.delete(key);
|
|
1401
|
+
});
|
|
1402
|
+
this.permitReads.set(key, read);
|
|
1403
|
+
return read;
|
|
1404
|
+
}
|
|
1282
1405
|
async handoffStatus(principal, id2) {
|
|
1283
1406
|
return this.client(principal).handoffStatus(id2);
|
|
1284
1407
|
}
|
|
@@ -1403,7 +1526,7 @@ function createPublicationServer(options) {
|
|
|
1403
1526
|
};
|
|
1404
1527
|
switch (value.operation) {
|
|
1405
1528
|
case "status":
|
|
1406
|
-
result = preservePublished ? await mutate(() => receiver.status()) : await receiver.status();
|
|
1529
|
+
result = preservePublished ? await mutate(() => receiver.status(false)) : await receiver.status(false);
|
|
1407
1530
|
break;
|
|
1408
1531
|
case "replication-status":
|
|
1409
1532
|
result = await receiver.replicationStatus();
|
|
@@ -1411,7 +1534,6 @@ function createPublicationServer(options) {
|
|
|
1411
1534
|
case "missing": {
|
|
1412
1535
|
if (!Array.isArray(value.refs) || value.refs.length > 128) throw new Error("PUBLICATION_INVALID_OBJECT_LIST");
|
|
1413
1536
|
const missing = await Promise.all(value.refs.map(async (ref) => {
|
|
1414
|
-
await check();
|
|
1415
1537
|
validateObjectRef(ref);
|
|
1416
1538
|
return await receiver.objects.has(ref) ? null : ref.sha256;
|
|
1417
1539
|
}));
|
|
@@ -1462,6 +1584,8 @@ function createPublicationServer(options) {
|
|
|
1462
1584
|
|
|
1463
1585
|
// src/continuity/recovery-archive-transfer.ts
|
|
1464
1586
|
import { Agent as Agent4, createServer as createServer3, request as request4 } from "node:https";
|
|
1587
|
+
import { gzipSync, gunzipSync, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants3 } from "node:zlib";
|
|
1588
|
+
import { pipeline as pipelineAsync } from "node:stream/promises";
|
|
1465
1589
|
|
|
1466
1590
|
// src/continuity/recovery-archive.ts
|
|
1467
1591
|
import { DatabaseSync as DatabaseSync5, backup } from "node:sqlite";
|
|
@@ -1474,7 +1598,8 @@ var HEADER_SIZE = MAGIC2.length + 12;
|
|
|
1474
1598
|
import { createHash as createHash4 } from "node:crypto";
|
|
1475
1599
|
var ID2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
1476
1600
|
var FORMAT = "engine7-runtime-recovery-archive-v1";
|
|
1477
|
-
var
|
|
1601
|
+
var RECOVERY_ARCHIVE_METADATA_BYTES = PUBLICATION_MANIFEST_BYTES + 8 * 1024 * 1024;
|
|
1602
|
+
var MAX_METADATA = RECOVERY_ARCHIVE_METADATA_BYTES;
|
|
1478
1603
|
var same2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
1479
1604
|
function validateRecoveryArchiveEntry(entry, identity) {
|
|
1480
1605
|
if (!entry || Object.keys(entry).some((key) => !["format", "id", "kind", "manifest", "databases", "publication", "receipt"].includes(key)) || entry.format !== FORMAT || !ID2.test(entry.id) || !["COMMON", "LOCAL", "REMOTE"].includes(entry.kind)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
|
|
@@ -1517,10 +1642,24 @@ async function checkRecoveryDeletionAsync(manifest, current, previous = 0) {
|
|
|
1517
1642
|
|
|
1518
1643
|
// src/continuity/recovery-archive-transfer.ts
|
|
1519
1644
|
var endpoint = "/travel/archives/v1";
|
|
1520
|
-
var metadataLimit =
|
|
1645
|
+
var metadataLimit = RECOVERY_ARCHIVE_METADATA_BYTES;
|
|
1521
1646
|
var requestLimit = 65536;
|
|
1522
1647
|
var objectGroupLimit = 8;
|
|
1523
1648
|
var partBodyLimit = 65536;
|
|
1649
|
+
var streamRefLimit = 512;
|
|
1650
|
+
var streamBatchBytes = 8 * 1024 * 1024;
|
|
1651
|
+
var streamBatchObjects = 128;
|
|
1652
|
+
var brotliOptions = { params: { [constants3.BROTLI_PARAM_QUALITY]: 4, [constants3.BROTLI_PARAM_LGWIN]: 22 } };
|
|
1653
|
+
function validateStreamRefs(value) {
|
|
1654
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > streamRefLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1655
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1656
|
+
for (const ref of value) {
|
|
1657
|
+
validateObjectRef(ref);
|
|
1658
|
+
if (Object.keys(ref).length !== 2 || seen.has(ref.sha256)) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
1659
|
+
seen.add(ref.sha256);
|
|
1660
|
+
}
|
|
1661
|
+
return value;
|
|
1662
|
+
}
|
|
1524
1663
|
var validId = (id2) => typeof id2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id2);
|
|
1525
1664
|
function validateObjectParts(value) {
|
|
1526
1665
|
if (!Array.isArray(value) || value.length < 1 || value.length > objectGroupLimit) throw new Error("RECOVERY_TRANSFER_INVALID_REQUEST");
|
|
@@ -1572,7 +1711,7 @@ function refs(entry) {
|
|
|
1572
1711
|
return result;
|
|
1573
1712
|
}
|
|
1574
1713
|
function createRecoveryArchiveServer(options) {
|
|
1575
|
-
const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, ...tls } = options;
|
|
1714
|
+
const { archive: fixedArchive, resolveArchive, listReceipts, readManifests, readManifestEvidence, identity = options.archive?.objects.identity, authority, allowedPeers, assertAvailable, bodyTimeoutMs = 5e3, streaming = true, ...tls } = options;
|
|
1576
1715
|
if (!identity || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
|
|
1577
1716
|
if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
|
|
1578
1717
|
const peers = new Map(Object.entries(allowedPeers).map(([fingerprint, credential]) => [fingerprint.replaceAll(":", "").toLowerCase(), credential]));
|
|
@@ -1581,6 +1720,7 @@ function createRecoveryArchiveServer(options) {
|
|
|
1581
1720
|
const server = createServer3({ ...tls, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
|
|
1582
1721
|
const started = Date.now(), timings = {};
|
|
1583
1722
|
let phase = "authenticate", action = "unknown", failure;
|
|
1723
|
+
let streamStats;
|
|
1584
1724
|
const mark = (next) => {
|
|
1585
1725
|
timings[phase] = Date.now() - started;
|
|
1586
1726
|
phase = next;
|
|
@@ -1588,6 +1728,10 @@ function createRecoveryArchiveServer(options) {
|
|
|
1588
1728
|
res.setHeader("Cache-Control", "no-store");
|
|
1589
1729
|
const refuse = (status, error) => {
|
|
1590
1730
|
if (!res.writableEnded && !res.destroyed) {
|
|
1731
|
+
if (res.headersSent) {
|
|
1732
|
+
res.destroy();
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1591
1735
|
res.statusCode = status;
|
|
1592
1736
|
res.setHeader("Content-Type", "application/json");
|
|
1593
1737
|
res.end(JSON.stringify({ error }));
|
|
@@ -1625,6 +1769,11 @@ function createRecoveryArchiveServer(options) {
|
|
|
1625
1769
|
const slot = { archiveDigest };
|
|
1626
1770
|
slots.add(slot);
|
|
1627
1771
|
busy.set(fingerprint, slots);
|
|
1772
|
+
const releaseSlot = () => {
|
|
1773
|
+
slots.delete(slot);
|
|
1774
|
+
if (!slots.size && busy.get(fingerprint) === slots) busy.delete(fingerprint);
|
|
1775
|
+
};
|
|
1776
|
+
res.once("close", releaseSlot);
|
|
1628
1777
|
mark("body");
|
|
1629
1778
|
const timer = setTimeout(() => {
|
|
1630
1779
|
refuse(408, "RECOVERY_TRANSFER_REFUSED");
|
|
@@ -1640,8 +1789,8 @@ function createRecoveryArchiveServer(options) {
|
|
|
1640
1789
|
}
|
|
1641
1790
|
clearTimeout(timer);
|
|
1642
1791
|
const input = JSON.parse(Buffer.concat(chunks).toString());
|
|
1643
|
-
if (archiveDigest && input?.action
|
|
1644
|
-
action = ["list", "read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
|
|
1792
|
+
if (archiveDigest && !["parts", "stream"].includes(input?.action)) throw new Error();
|
|
1793
|
+
action = ["list", "read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
|
|
1645
1794
|
mark("resolve");
|
|
1646
1795
|
if (input?.version === 1 && input.action === "list") {
|
|
1647
1796
|
if (Object.keys(input).some((key) => !["version", "action"].includes(key))) throw new Error();
|
|
@@ -1656,8 +1805,8 @@ function createRecoveryArchiveServer(options) {
|
|
|
1656
1805
|
return;
|
|
1657
1806
|
}
|
|
1658
1807
|
const ancestry = ["manifests", "manifest-page"].includes(input?.action), paged = input?.action === "manifest-page";
|
|
1659
|
-
if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : input.action
|
|
1660
|
-
await
|
|
1808
|
+
if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : ["objects", "stream"].includes(input.action) ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key))) throw new Error();
|
|
1809
|
+
await assertAvailable();
|
|
1661
1810
|
if (ancestry && !validCommon(input.common)) throw new Error();
|
|
1662
1811
|
const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
|
|
1663
1812
|
const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
|
|
@@ -1673,6 +1822,111 @@ function createRecoveryArchiveServer(options) {
|
|
|
1673
1822
|
const floor = (await authority.status(principal)).deletionWatermark;
|
|
1674
1823
|
await checkRecoveryDeletionAsync(entry.manifest, () => floor);
|
|
1675
1824
|
mark("content");
|
|
1825
|
+
if (input.action === "stream") {
|
|
1826
|
+
if (!streaming || !archiveDigest) throw new Error();
|
|
1827
|
+
const requested = validateStreamRefs(input.refs), allowed = refs(entry);
|
|
1828
|
+
if (requested.some((ref) => allowed.get(ref.sha256)?.bytes !== ref.bytes)) throw new Error();
|
|
1829
|
+
let currentFloor = floor;
|
|
1830
|
+
const check = async () => {
|
|
1831
|
+
if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
|
|
1832
|
+
const [control2] = await Promise.all([authority.status(principal), assertAvailable()]);
|
|
1833
|
+
currentFloor = await checkRecoveryDeletionAsync(entry.manifest, () => control2.deletionWatermark, currentFloor);
|
|
1834
|
+
if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
|
|
1835
|
+
};
|
|
1836
|
+
const accepted2 = String(req.headers["accept-encoding"] ?? "").split(",").map((value) => value.trim());
|
|
1837
|
+
const encoding2 = accepted2.includes("br") ? "br" : accepted2.includes("gzip") ? "gzip" : void 0;
|
|
1838
|
+
streamStats = { encoding: encoding2 ?? "identity", objects: requested.length, batches: 0, rawBytes: 0, wireBytes: 0, readMs: 0, controlMs: 0, encodeAndWriteMs: 0 };
|
|
1839
|
+
const encoder = encoding2 === "br" ? createBrotliCompress(brotliOptions) : void 0, output = encoder ?? res;
|
|
1840
|
+
encoder?.on("data", (body2) => {
|
|
1841
|
+
streamStats.wireBytes += body2.length;
|
|
1842
|
+
});
|
|
1843
|
+
const streamed = encoder ? pipelineAsync(encoder, res) : void 0;
|
|
1844
|
+
void streamed?.catch(() => {
|
|
1845
|
+
});
|
|
1846
|
+
const write = (body2) => new Promise((resolve4, reject) => {
|
|
1847
|
+
if (res.destroyed || output.destroyed) {
|
|
1848
|
+
reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
|
|
1849
|
+
return;
|
|
1850
|
+
}
|
|
1851
|
+
if (!encoder) streamStats.wireBytes += body2.length;
|
|
1852
|
+
if (output.write(body2)) {
|
|
1853
|
+
resolve4();
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
const cleanup = () => {
|
|
1857
|
+
output.off("drain", drain);
|
|
1858
|
+
output.off("close", closed);
|
|
1859
|
+
output.off("error", closed);
|
|
1860
|
+
};
|
|
1861
|
+
const drain = () => {
|
|
1862
|
+
cleanup();
|
|
1863
|
+
resolve4();
|
|
1864
|
+
}, closed = () => {
|
|
1865
|
+
cleanup();
|
|
1866
|
+
reject(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
|
|
1867
|
+
};
|
|
1868
|
+
output.once("drain", drain);
|
|
1869
|
+
output.once("close", closed);
|
|
1870
|
+
output.once("error", closed);
|
|
1871
|
+
});
|
|
1872
|
+
res.setHeader("Content-Type", "application/octet-stream");
|
|
1873
|
+
if (encoding2) {
|
|
1874
|
+
res.setHeader("Content-Encoding", encoding2);
|
|
1875
|
+
res.setHeader("Vary", "Accept-Encoding");
|
|
1876
|
+
}
|
|
1877
|
+
try {
|
|
1878
|
+
for (let offset = 0; offset < requested.length; ) {
|
|
1879
|
+
let end = offset, bytes2 = 0;
|
|
1880
|
+
while (end < requested.length && end - offset < streamBatchObjects && bytes2 + requested[end].bytes <= streamBatchBytes) {
|
|
1881
|
+
bytes2 += requested[end].bytes;
|
|
1882
|
+
end++;
|
|
1883
|
+
}
|
|
1884
|
+
if (res.destroyed) throw new Error("RECOVERY_TRANSFER_UNAVAILABLE");
|
|
1885
|
+
let step = Date.now();
|
|
1886
|
+
const results = await Promise.allSettled(requested.slice(offset, end).map((ref) => archive.objects.read(ref)));
|
|
1887
|
+
for (const result of results) if (result.status === "rejected") throw result.reason;
|
|
1888
|
+
streamStats.readMs += Date.now() - step;
|
|
1889
|
+
step = Date.now();
|
|
1890
|
+
await check();
|
|
1891
|
+
streamStats.controlMs += Date.now() - step;
|
|
1892
|
+
step = Date.now();
|
|
1893
|
+
const bodies = results.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
|
|
1894
|
+
if (encoder) {
|
|
1895
|
+
await write(Buffer.concat(bodies));
|
|
1896
|
+
await new Promise((resolve4, reject) => {
|
|
1897
|
+
const cleanup = () => {
|
|
1898
|
+
encoder.off("error", failed);
|
|
1899
|
+
encoder.off("close", closed);
|
|
1900
|
+
};
|
|
1901
|
+
const failed = (error) => {
|
|
1902
|
+
cleanup();
|
|
1903
|
+
reject(error);
|
|
1904
|
+
}, closed = () => failed(new Error("RECOVERY_TRANSFER_UNAVAILABLE"));
|
|
1905
|
+
encoder.once("error", failed);
|
|
1906
|
+
encoder.once("close", closed);
|
|
1907
|
+
encoder.flush(constants3.BROTLI_OPERATION_FLUSH, () => {
|
|
1908
|
+
cleanup();
|
|
1909
|
+
resolve4();
|
|
1910
|
+
});
|
|
1911
|
+
});
|
|
1912
|
+
} else if (encoding2 === "gzip") await write(gzipSync(Buffer.concat(bodies), { level: 1 }));
|
|
1913
|
+
else for (const body2 of bodies) await write(body2);
|
|
1914
|
+
streamStats.encodeAndWriteMs += Date.now() - step;
|
|
1915
|
+
streamStats.rawBytes += bytes2;
|
|
1916
|
+
streamStats.batches++;
|
|
1917
|
+
offset = end;
|
|
1918
|
+
}
|
|
1919
|
+
await check();
|
|
1920
|
+
mark("reply");
|
|
1921
|
+
if (encoder) {
|
|
1922
|
+
encoder.end();
|
|
1923
|
+
await streamed;
|
|
1924
|
+
} else res.end();
|
|
1925
|
+
return;
|
|
1926
|
+
} finally {
|
|
1927
|
+
encoder?.destroy();
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1676
1930
|
let body;
|
|
1677
1931
|
if (ancestry) {
|
|
1678
1932
|
if (!evidence && !readManifests || entry.kind !== "LOCAL") throw new Error();
|
|
@@ -1693,6 +1947,7 @@ function createRecoveryArchiveServer(options) {
|
|
|
1693
1947
|
body = Buffer.from(JSON.stringify(entry));
|
|
1694
1948
|
if (body.length > metadataLimit) throw new Error();
|
|
1695
1949
|
res.setHeader("Content-Type", "application/json");
|
|
1950
|
+
if (streaming) res.setHeader("X-Engine7-Recovery-Stream", "1");
|
|
1696
1951
|
} else if (input.action === "parts") {
|
|
1697
1952
|
const group = validateObjectParts(input.parts), allowed = refs(entry), parts = [];
|
|
1698
1953
|
if (group.some((part) => allowed.get(part.ref.sha256)?.bytes !== part.ref.bytes)) throw new Error();
|
|
@@ -1719,6 +1974,16 @@ function createRecoveryArchiveServer(options) {
|
|
|
1719
1974
|
const [control] = await Promise.all([authority.status(principal), assertAvailable()]), latest = control.deletionWatermark;
|
|
1720
1975
|
await checkRecoveryDeletionAsync(entry.manifest, () => latest, floor);
|
|
1721
1976
|
mark("reply");
|
|
1977
|
+
const accepted = String(req.headers["accept-encoding"] ?? "").split(",").map((value) => value.trim());
|
|
1978
|
+
const encoding = accepted.includes("br") ? "br" : accepted.includes("gzip") ? "gzip" : void 0;
|
|
1979
|
+
if (encoding) {
|
|
1980
|
+
const compressed = encoding === "br" ? brotliCompressSync(body, brotliOptions) : gzipSync(body, { level: 1 });
|
|
1981
|
+
if (res.getHeader("Content-Type") === "application/json" || compressed.length < body.length) {
|
|
1982
|
+
body = compressed;
|
|
1983
|
+
res.setHeader("Content-Encoding", encoding);
|
|
1984
|
+
res.setHeader("Vary", "Accept-Encoding");
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1722
1987
|
res.setHeader("Content-Length", body.length);
|
|
1723
1988
|
res.end(body);
|
|
1724
1989
|
} catch (error) {
|
|
@@ -1726,9 +1991,8 @@ function createRecoveryArchiveServer(options) {
|
|
|
1726
1991
|
refuse(409, "RECOVERY_TRANSFER_REFUSED");
|
|
1727
1992
|
} finally {
|
|
1728
1993
|
clearTimeout(timer);
|
|
1729
|
-
|
|
1730
|
-
if (
|
|
1731
|
-
if (failure || Date.now() - started >= 5e3) process.stderr.write("[travel-archive] " + JSON.stringify({ at: Date.now(), action, phase, elapsedMs: Date.now() - started, timings, failure }) + "\n");
|
|
1994
|
+
releaseSlot();
|
|
1995
|
+
if (failure || Date.now() - started >= 5e3) process.stderr.write("[travel-archive] " + JSON.stringify({ at: Date.now(), action, phase, elapsedMs: Date.now() - started, timings, stream: streamStats, failure }) + "\n");
|
|
1732
1996
|
}
|
|
1733
1997
|
});
|
|
1734
1998
|
server.headersTimeout = 5e3;
|
|
@@ -1792,7 +2056,7 @@ async function createTravelNodeDataServer(options) {
|
|
|
1792
2056
|
|
|
1793
2057
|
// src/continuity/controller-main.ts
|
|
1794
2058
|
var path = (value) => {
|
|
1795
|
-
if (typeof value !== "string" || !
|
|
2059
|
+
if (typeof value !== "string" || !isAbsolute2(value) || resolve3(value) !== value) throw new Error("TRAVEL_CONTROLLER_PATH");
|
|
1796
2060
|
return value;
|
|
1797
2061
|
};
|
|
1798
2062
|
function openTravelController(input) {
|
|
@@ -1806,7 +2070,7 @@ function openTravelController(input) {
|
|
|
1806
2070
|
privateKey.fill(0);
|
|
1807
2071
|
};
|
|
1808
2072
|
try {
|
|
1809
|
-
const tls = { ca:
|
|
2073
|
+
const tls = { ca: readFileSync2(path(config.tls?.caFile)), cert: readFileSync2(path(config.tls?.certFile)), key: privateKey };
|
|
1810
2074
|
for (const [nodeId, value] of Object.entries(config.nodes)) {
|
|
1811
2075
|
if (!nodeSupervisorId(nodeId) || !nodeSupervisorRecord(value) || !nodeSupervisorRecord(value.principal) || value.principal.nodeId !== nodeId) throw new Error("TRAVEL_CONTROLLER_IDENTITY");
|
|
1812
2076
|
const principal = value.principal;
|
|
@@ -1819,6 +2083,7 @@ function openTravelController(input) {
|
|
|
1819
2083
|
authority,
|
|
1820
2084
|
nodes,
|
|
1821
2085
|
preferredNodeId: config.preferredNodeId,
|
|
2086
|
+
initialAutomatic: config.initialAutomatic,
|
|
1822
2087
|
intervalMs: config.intervalMs,
|
|
1823
2088
|
healthyForMs: config.healthyForMs,
|
|
1824
2089
|
handbackCooldownMs: config.handbackCooldownMs
|
|
@@ -1866,7 +2131,7 @@ async function runTravelControllerCli(args) {
|
|
|
1866
2131
|
await service.close();
|
|
1867
2132
|
}
|
|
1868
2133
|
}
|
|
1869
|
-
if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) &&
|
|
2134
|
+
if (process.argv[1] && /[\\/](controller-main\.ts|travel-controller\.mjs)$/.test(fileURLToPath(import.meta.url)) && resolve3(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1870
2135
|
runTravelControllerCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
|
|
1871
2136
|
process.stderr.write("TRAVEL_CONTROLLER_REFUSED\n");
|
|
1872
2137
|
process.exitCode = 1;
|