my-durable 0.0.64 → 0.0.66
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/apps/dpi-backend/src/archived.ts +8 -2
- package/apps/dpi-backend/src/gc-cli.ts +11 -2
- package/apps/dpi-backend/src/gc.ts +15 -3
- package/apps/dpi-backend/src/graphs.ts +3 -1
- package/apps/dpi-backend/src/routes.ts +10 -1
- package/apps/dpi-backend/src/schedule-cli.ts +8 -3
- package/apps/dpi-backend/src/schedules.ts +14 -7
- package/apps/dpi-backend/src/store.ts +122 -19
- package/apps/dpi-backend/src/tunnel.ts +13 -2
- package/apps/dpi-backend/src/zip.ts +71 -11
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-DCz-aq0b.css → index-DSU1QhGO.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-D10XyhhO.js → index-d3YKeCCM.js} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/SchedulesPanel.vue +1 -1
- package/package.json +1 -1
|
@@ -39,8 +39,14 @@ const DB_NAME = "agent.sqlite";
|
|
|
39
39
|
const FILE_MODE = 0o600;
|
|
40
40
|
const DIR_MODE = 0o700;
|
|
41
41
|
|
|
42
|
-
/** `<uuid>-<archivedAtMs>`: the only identity an old bundle has.
|
|
43
|
-
|
|
42
|
+
/** `<uuid>-<archivedAtMs>`: the only identity an old bundle has. R11 4.1:
|
|
43
|
+
* CANONICAL uuid shape (8-4-4-4-12 lowercase hex) — the old `[0-9a-f-]{36}`
|
|
44
|
+
* character class also matched 36 dashes, hex-without-dashes and other
|
|
45
|
+
* lookalikes an operator might drop in archive/ from another tool; those are
|
|
46
|
+
* now skipped+reported by BOTH gc and the browser (this ONE pattern is the
|
|
47
|
+
* shared source — real bundles are canonical-uuid session ids by
|
|
48
|
+
* construction, so nothing legitimate is lost). */
|
|
49
|
+
export const BUNDLE_DIR_PATTERN = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-(\d{13})$/;
|
|
44
50
|
/** Full lowercase uuid, 8-4-4-4-12: a PREFIX of another uuid must never match a bundle. */
|
|
45
51
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
46
52
|
|
|
@@ -160,6 +160,10 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
|
|
|
160
160
|
e instanceof Error ? e.message : String(e)
|
|
161
161
|
} (re-run later — the sweep is idempotent)`,
|
|
162
162
|
);
|
|
163
|
+
// R12 P2-3: cron/scripts gate on the exit code — a failed sweep after
|
|
164
|
+
// a real delete must not read as success (nothing retries it
|
|
165
|
+
// otherwise; a later no-delete gc pass never sweeps).
|
|
166
|
+
return 1;
|
|
163
167
|
}
|
|
164
168
|
}
|
|
165
169
|
return 0;
|
|
@@ -204,8 +208,13 @@ async function sweepRefs(dataDir: string, ids: string[], io: GcIo, token?: strin
|
|
|
204
208
|
io.print(`swept ${cleared.schedules} schedule ref(s), ${cleared.graphRuns} graph-run ref(s).`);
|
|
205
209
|
return;
|
|
206
210
|
}
|
|
207
|
-
//
|
|
208
|
-
//
|
|
211
|
+
// R12 P3-6: name the two skew shapes an operator can actually hit —
|
|
212
|
+
// anything else is a real fault; falling through to the offline path
|
|
213
|
+
// would race the daemon, so surface it instead.
|
|
214
|
+
if (res.status === 404)
|
|
215
|
+
throw new Error("device predates the sweep route — upgrade it (npm i -g my-durable) and re-run dpi gc");
|
|
216
|
+
if (res.status === 401)
|
|
217
|
+
throw new Error("device refused the sweep token — stale DPI_TOKEN in the env file; refresh it and re-run dpi gc");
|
|
209
218
|
throw new Error(`device answered ${res.status} to the sweep route`);
|
|
210
219
|
} catch (e) {
|
|
211
220
|
if (e instanceof TypeError || (e instanceof Error && /fetch|network|ECONN/i.test(e.message))) {
|
|
@@ -82,7 +82,13 @@ export async function archivedEntries(
|
|
|
82
82
|
const entries: ArchivedEntry[] = [];
|
|
83
83
|
const skipped: GcPlan["skipped"] = [];
|
|
84
84
|
for (const entry of await readdir(archiveDir, { withFileTypes: true }).catch(() => [])) {
|
|
85
|
-
if (!entry.isDirectory())
|
|
85
|
+
if (!entry.isDirectory()) {
|
|
86
|
+
// R11 4.2: files and SYMLINKED dirs at archive/ root used to be silently
|
|
87
|
+
// invisible (not in total, not in skipped, never explained). Now the plan
|
|
88
|
+
// says what it ignored and why — an honest plan is auditable.
|
|
89
|
+
skipped.push({ name: entry.name, reason: "not a directory (file or symlink) — left untouched" });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
86
92
|
const parsed = parseArchivedName(entry.name);
|
|
87
93
|
if (!parsed) {
|
|
88
94
|
skipped.push({ name: entry.name, reason: "not an archived-session directory" });
|
|
@@ -114,9 +120,15 @@ export function danglingRefCounts(
|
|
|
114
120
|
let graphRuns = 0;
|
|
115
121
|
try {
|
|
116
122
|
const doc = JSON.parse(readFile(join(dataDir, "schedules.json"))) as {
|
|
117
|
-
schedules?: Array<{ lastSessionId?: string }>;
|
|
123
|
+
schedules?: Array<{ lastSessionId?: string; recentSessionIds?: string[] }>;
|
|
118
124
|
};
|
|
119
|
-
|
|
125
|
+
// R12 P3-11: count what the sweep actually clears — the retention ring
|
|
126
|
+
// too (clearSessionRefs deletes ring entries alongside lastSessionId), so
|
|
127
|
+
// the dry-run's "would clear N" stops under-promising.
|
|
128
|
+
for (const s of doc.schedules ?? []) {
|
|
129
|
+
if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
|
|
130
|
+
else if ((s.recentSessionIds ?? []).some((id) => ids.has(id))) schedules += 1;
|
|
131
|
+
}
|
|
120
132
|
} catch {
|
|
121
133
|
/* absent or unreadable — nothing countable */
|
|
122
134
|
}
|
|
@@ -705,7 +705,9 @@ export class GraphRegistry {
|
|
|
705
705
|
}
|
|
706
706
|
return touched ? { ...run, tasks } : run;
|
|
707
707
|
});
|
|
708
|
-
|
|
708
|
+
// R12 P3-7: no-op sweeps skip the commit — the schedules twin guards the
|
|
709
|
+
// same way; a no-op must not churn graphs.json (+ its .bak) forever.
|
|
710
|
+
if (cleared > 0) await this.commit(new Map(this.graphs), runs);
|
|
709
711
|
});
|
|
710
712
|
return cleared;
|
|
711
713
|
}
|
|
@@ -50,6 +50,12 @@ export function v1(
|
|
|
50
50
|
// (/V1/DEVICE used to answer 200 over loopback and 404 through the tunnel).
|
|
51
51
|
// Every client (sdk/TUI/web) speaks lowercase — verified against sdk client.ts.
|
|
52
52
|
const r = Router({ caseSensitive: true });
|
|
53
|
+
// R11 6.3 (doc): `create` auto-keys un-keyed mutations (sha256 of method+path+body,
|
|
54
|
+
// 24 h retention) — a deliberate second identical create (same body) within 24 h
|
|
55
|
+
// REPLAYS the first response instead of creating again. That collapse is the
|
|
56
|
+
// accepted retry-safety tradeoff; clients that need deliberate repeats must send
|
|
57
|
+
// their own Idempotency-Key (which always wins over the auto-key), and replays
|
|
58
|
+
// are visible in the Idempotent-Replay: true response header.
|
|
53
59
|
const create = idempotent(store);
|
|
54
60
|
// `dpi device stop`: graceful local shutdown (token-authed like every /v1
|
|
55
61
|
// route). The response flushes BEFORE the daemon tears down so the caller
|
|
@@ -316,7 +322,10 @@ export function v1(
|
|
|
316
322
|
r.post("/schedules", route(async (req, res) => res.status(201).json(await store.createSchedule(req.body ?? {}))));
|
|
317
323
|
r.patch("/schedules/:id", route(async (req, res) => res.json(await store.updateSchedule(param(req, "id"), req.body ?? {}))));
|
|
318
324
|
r.delete("/schedules/:id", route(async (req, res) => res.json(await store.removeSchedule(param(req, "id")))));
|
|
319
|
-
|
|
325
|
+
// R11 2.3: 202 Accepted — the run is ARMED, not finished; the turn is bounded
|
|
326
|
+
// by the dispatch deadlines (60 s submit + 120 s settle) and its outcome lands
|
|
327
|
+
// in the schedule record (GET /schedules) and the schedule.ok/failed events.
|
|
328
|
+
r.post("/schedules/:id/run", route(async (_req, res) => res.status(202).json(await store.runScheduleNow(param(_req, "id")))));
|
|
320
329
|
|
|
321
330
|
// ---------------------------------------------------------- sessions
|
|
322
331
|
r.get("/sessions", route(async (_req, res) => res.json((await store.tree()).sessions)));
|
|
@@ -188,14 +188,19 @@ export async function scheduleCli(argv: readonly string[], io: ScheduleIo = defa
|
|
|
188
188
|
return 0;
|
|
189
189
|
}
|
|
190
190
|
if (sub === "run") {
|
|
191
|
-
io.print(`${target.name}:
|
|
191
|
+
io.print(`${target.name}: starting…`);
|
|
192
|
+
// R11 2.3: the route answers 202 as soon as the run is ARMED — the turn
|
|
193
|
+
// itself is bounded by the dispatch deadlines and lands in the record and
|
|
194
|
+
// the schedule.ok/failed events. `dpi schedule list` shows the outcome.
|
|
192
195
|
const ran = await call<ScheduleView>(io, "POST", `/v1/schedules/${target.id}/run`, {});
|
|
193
196
|
if (!ran.ok) {
|
|
194
197
|
io.printErr(`dpi schedule: ${ran.error}`);
|
|
195
198
|
return 1;
|
|
196
199
|
}
|
|
197
|
-
|
|
198
|
-
|
|
200
|
+
// R12 P3-9: `running` is always true here — the guard-add runs
|
|
201
|
+
// synchronously before the 202 is built — so no ternary.
|
|
202
|
+
io.print(`run started (watch \`dpi schedule list\` for the outcome); next ${when(ran.data.nextRunAt)}`);
|
|
203
|
+
return 0;
|
|
199
204
|
}
|
|
200
205
|
if (sub === "remove") {
|
|
201
206
|
const removed = await call<{ removed: boolean }>(io, "DELETE", `/v1/schedules/${target.id}`);
|
|
@@ -385,15 +385,22 @@ function coerceRecord(raw: unknown, now: number): ScheduleRecord {
|
|
|
385
385
|
if (isOutcome(source.lastOutcome)) record.lastOutcome = source.lastOutcome;
|
|
386
386
|
const lastError = nonEmptyString(source.lastError);
|
|
387
387
|
if (lastError) record.lastError = lastError;
|
|
388
|
-
// R10 Design A: retention window — defensive parse (
|
|
389
|
-
// trimmed
|
|
390
|
-
//
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
388
|
+
// R10 Design A: retention window — defensive parse (junk dropped, ring
|
|
389
|
+
// trimmed) so a hand-edited or future file cannot unbound the registry.
|
|
390
|
+
// R12 P3-8: out-of-range keepRuns is DROPPED, not clamped — create/patch
|
|
391
|
+
// reject those values at the API, so the parse path must not silently ARM
|
|
392
|
+
// (or sharpen) auto-archive from garbage; dropped reads as "no retention",
|
|
393
|
+
// the safe direction.
|
|
394
|
+
if (
|
|
395
|
+
typeof source.keepRuns === "number" &&
|
|
396
|
+
Number.isInteger(source.keepRuns) &&
|
|
397
|
+
source.keepRuns >= MIN_KEEP_RUNS &&
|
|
398
|
+
source.keepRuns <= MAX_KEEP_RUNS
|
|
399
|
+
) {
|
|
400
|
+
record.keepRuns = source.keepRuns;
|
|
394
401
|
if (Array.isArray(source.recentSessionIds)) {
|
|
395
402
|
const ring = source.recentSessionIds.filter((id): id is string => typeof id === "string" && id.length > 0);
|
|
396
|
-
const unique = [...new Set(ring)].slice(-keepRuns);
|
|
403
|
+
const unique = [...new Set(ring)].slice(-source.keepRuns);
|
|
397
404
|
if (unique.length > 0) record.recentSessionIds = unique;
|
|
398
405
|
}
|
|
399
406
|
}
|
|
@@ -1596,10 +1596,20 @@ export class Store {
|
|
|
1596
1596
|
// R10 5.2: single-flight per session — two routes opening one corrupt db
|
|
1597
1597
|
// (UI refresh fetching git-files + agents) used to spawn two salvage
|
|
1598
1598
|
// workers racing on shared scratch; both attempts now share ONE outcome.
|
|
1599
|
-
const inFlight = this.salvageInFlight.get(row.id) ?? salvageSessionDb(row.dbPath).then(
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1599
|
+
const inFlight = this.salvageInFlight.get(row.id) ?? salvageSessionDb(row.dbPath).then(
|
|
1600
|
+
(outcome) => {
|
|
1601
|
+
this.salvageInFlight.delete(row.id);
|
|
1602
|
+
return outcome;
|
|
1603
|
+
},
|
|
1604
|
+
// R12 P3-10: clear on rejection too — a cached rejected promise would
|
|
1605
|
+
// permanently disable salvage for this session. (Unreachable today:
|
|
1606
|
+
// salvageSessionDb resolves on every path — but the map must not
|
|
1607
|
+
// depend on that staying true.)
|
|
1608
|
+
(error: unknown) => {
|
|
1609
|
+
this.salvageInFlight.delete(row.id);
|
|
1610
|
+
throw error;
|
|
1611
|
+
},
|
|
1612
|
+
);
|
|
1603
1613
|
this.salvageInFlight.set(row.id, inFlight);
|
|
1604
1614
|
const outcome = await inFlight;
|
|
1605
1615
|
if (!outcome.recovered) {
|
|
@@ -2597,6 +2607,10 @@ export class Store {
|
|
|
2597
2607
|
|
|
2598
2608
|
async removeSchedule(id: string): Promise<{ removed: boolean }> {
|
|
2599
2609
|
const removed = await this.schedules.remove(id);
|
|
2610
|
+
// R12 P3-4: the schedule is gone — its degraded-episode markers must not
|
|
2611
|
+
// linger in the sets forever (random ids, never reused).
|
|
2612
|
+
this.scheduleRegistryDegraded.delete(id);
|
|
2613
|
+
this.schedulePruneDegraded.delete(id);
|
|
2600
2614
|
this.notify();
|
|
2601
2615
|
return { removed };
|
|
2602
2616
|
}
|
|
@@ -2605,11 +2619,23 @@ export class Store {
|
|
|
2605
2619
|
* Throws ApiFault("busy") (HTTP 409, "already running") when the schedule
|
|
2606
2620
|
* has a run in flight: the guard lives in the shared dispatch entry point
|
|
2607
2621
|
* (R8 2.1), so a double-clicked Run button gets a typed fault instead of a
|
|
2608
|
-
* second concurrent run with duplicated side effects.
|
|
2622
|
+
* second concurrent run with duplicated side effects.
|
|
2623
|
+
*
|
|
2624
|
+
* R11 2.3: returns AS SOON AS the run is armed, not when the turn finishes —
|
|
2625
|
+
* a slow turn used to hold the HTTP request (and the hub tunnel) hostage
|
|
2626
|
+
* for up to the full 60 s dispatch deadline + 120 s settle cap; browsers
|
|
2627
|
+
* and proxies time out long before that. No awaits sit between the busy
|
|
2628
|
+
* pre-check and the dispatch (whose guard-add also runs synchronously), so
|
|
2629
|
+
* two Run clicks in one turn cannot both pass. The outcome lands in the
|
|
2630
|
+
* record (scheduleList/view) and the schedule.ok/failed events, exactly as
|
|
2631
|
+
* the timer path's outcomes always have. The route answers 202. */
|
|
2609
2632
|
async runScheduleNow(id: string): Promise<ScheduleView> {
|
|
2610
2633
|
const record = this.schedules.get(id);
|
|
2611
2634
|
if (!record) throw notFound(`no schedule ${id}`);
|
|
2612
|
-
|
|
2635
|
+
if (this.scheduleInFlight.has(record.id)) {
|
|
2636
|
+
throw new ApiFault("busy", `Schedule "${record.name}" is already running`);
|
|
2637
|
+
}
|
|
2638
|
+
void this.dispatchSchedule(record).catch(() => undefined);
|
|
2613
2639
|
return this.scheduleView(this.schedules.get(id) ?? record);
|
|
2614
2640
|
}
|
|
2615
2641
|
|
|
@@ -2642,6 +2668,14 @@ export class Store {
|
|
|
2642
2668
|
private scheduleInFlight = new Set<string>();
|
|
2643
2669
|
private scheduleTimer?: ReturnType<typeof setTimeout>;
|
|
2644
2670
|
|
|
2671
|
+
/** R11 2.2: schedules whose registry (schedules.json) is currently
|
|
2672
|
+
* unwritable — each is reported ONCE per degraded episode, not per tick. */
|
|
2673
|
+
private scheduleRegistryDegraded = new Set<string>();
|
|
2674
|
+
|
|
2675
|
+
/** R12 P2-1: schedules whose retention prune could not archive an evicted
|
|
2676
|
+
* run — reported once per episode; a later successful prune ends it. */
|
|
2677
|
+
private schedulePruneDegraded = new Set<string>();
|
|
2678
|
+
|
|
2645
2679
|
/** R10 5.2: per-session salvage single-flight — concurrent openers of one
|
|
2646
2680
|
* corrupt session share ONE bounded attempt instead of racing scratch files. */
|
|
2647
2681
|
private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
|
|
@@ -2690,8 +2724,10 @@ export class Store {
|
|
|
2690
2724
|
const started: string[] = [];
|
|
2691
2725
|
for (const record of this.schedules.due(at)) {
|
|
2692
2726
|
if (this.scheduleInFlight.has(record.id)) continue;
|
|
2693
|
-
|
|
2694
|
-
|
|
2727
|
+
// R12 P3-5: only ids that actually DISPATCHED are reported — an
|
|
2728
|
+
// intent-marker skip (degraded registry) must not read as "started".
|
|
2729
|
+
const ran = await this.dispatchSchedule(record).catch(() => false);
|
|
2730
|
+
if (ran) started.push(record.id);
|
|
2695
2731
|
}
|
|
2696
2732
|
return started;
|
|
2697
2733
|
}
|
|
@@ -2710,23 +2746,55 @@ export class Store {
|
|
|
2710
2746
|
* BEFORE the session is created, so a crash in the create→outcome window
|
|
2711
2747
|
* leaves a visible "interrupted" record after restart instead of silently
|
|
2712
2748
|
* re-firing the same minute.
|
|
2749
|
+
*
|
|
2750
|
+
* R12 P3-5: returns true when the dispatch ran (attempted past the intent
|
|
2751
|
+
* marker), false when skipped — runDueSchedules reports only the true ones.
|
|
2713
2752
|
*/
|
|
2714
|
-
private async dispatchSchedule(record: ScheduleRecord): Promise<
|
|
2753
|
+
private async dispatchSchedule(record: ScheduleRecord): Promise<boolean> {
|
|
2715
2754
|
if (this.scheduleInFlight.has(record.id)) {
|
|
2716
2755
|
throw new ApiFault("busy", `Schedule "${record.name}" is already running`);
|
|
2717
2756
|
}
|
|
2718
2757
|
this.scheduleInFlight.add(record.id);
|
|
2719
2758
|
this.notify();
|
|
2720
2759
|
try {
|
|
2721
|
-
//
|
|
2722
|
-
//
|
|
2723
|
-
//
|
|
2724
|
-
|
|
2760
|
+
// R11 2.2: the intent marker is the at-most-once anchor. Without it,
|
|
2761
|
+
// `due()` re-offers this slot on EVERY tick while the registry is
|
|
2762
|
+
// unwritable (disk full, AV lock) and the prompt would re-fire at tick
|
|
2763
|
+
// rate — up to 2,880 duplicate real runs/day, each with a notify event.
|
|
2764
|
+
// So a failed intent persist now SKIPS the dispatch (the run has not
|
|
2765
|
+
// started, so not running it is correct) and surfaces the degraded
|
|
2766
|
+
// state ONCE per episode; the next successful write ends the episode.
|
|
2767
|
+
// Outcome persists inside dispatchBounded stay best-effort.
|
|
2768
|
+
const intentOk = await deadline(
|
|
2725
2769
|
this.schedules.markRun(record.id, { outcome: "started" }),
|
|
2726
2770
|
SCHEDULE_REGISTRY_IO_MS,
|
|
2727
2771
|
"schedule registry write timed out (started)",
|
|
2728
|
-
).
|
|
2772
|
+
).then(
|
|
2773
|
+
() => true,
|
|
2774
|
+
() => false,
|
|
2775
|
+
);
|
|
2776
|
+
if (!intentOk) {
|
|
2777
|
+
if (!this.scheduleRegistryDegraded.has(record.id)) {
|
|
2778
|
+
this.scheduleRegistryDegraded.add(record.id);
|
|
2779
|
+
void this.notifyEvent({
|
|
2780
|
+
kind: "schedule.failed",
|
|
2781
|
+
title: `Schedule paused: ${record.name}`,
|
|
2782
|
+
body: "its registry is unwritable (disk full or locked) — the run was skipped so it cannot re-fire every tick; it resumes when the registry is writable again",
|
|
2783
|
+
data: { scheduleId: record.id },
|
|
2784
|
+
});
|
|
2785
|
+
}
|
|
2786
|
+
return false;
|
|
2787
|
+
}
|
|
2788
|
+
if (this.scheduleRegistryDegraded.delete(record.id)) {
|
|
2789
|
+
void this.notifyEvent({
|
|
2790
|
+
kind: "schedule.ok",
|
|
2791
|
+
title: `Schedule resumed: ${record.name}`,
|
|
2792
|
+
body: "registry writes recovered; scheduled runs continue",
|
|
2793
|
+
data: { scheduleId: record.id },
|
|
2794
|
+
});
|
|
2795
|
+
}
|
|
2729
2796
|
await this.dispatchBounded(record);
|
|
2797
|
+
return true;
|
|
2730
2798
|
} finally {
|
|
2731
2799
|
this.scheduleInFlight.delete(record.id);
|
|
2732
2800
|
this.notify();
|
|
@@ -2801,7 +2869,8 @@ export class Store {
|
|
|
2801
2869
|
SCHEDULE_REGISTRY_IO_MS,
|
|
2802
2870
|
"schedule registry write timed out (ok)",
|
|
2803
2871
|
).catch(() => undefined);
|
|
2804
|
-
if (okRecord?.keepRuns)
|
|
2872
|
+
if (okRecord?.keepRuns)
|
|
2873
|
+
void this.pruneScheduleSessions(okRecord, ringBefore).catch(() => this.markPruneDegraded(okRecord));
|
|
2805
2874
|
void this.notifyEvent({
|
|
2806
2875
|
kind: "schedule.ok",
|
|
2807
2876
|
title: `Schedule ran: ${record.name}`,
|
|
@@ -2838,14 +2907,48 @@ export class Store {
|
|
|
2838
2907
|
* the gc plan). Archive failure leaves the session live; the id is already
|
|
2839
2908
|
* gone from the ring, but the session stays restorable and the operator can
|
|
2840
2909
|
* archive it manually — at most keepRuns stragglers can overstay (bounded). */
|
|
2910
|
+
/** R12 P2-1: the once-per-episode signal for a retention prune that could
|
|
2911
|
+
* not archive an evicted run — shared by the prune's own failure path and
|
|
2912
|
+
* the void-caller's outer catch. */
|
|
2913
|
+
private markPruneDegraded(record: ScheduleRecord): void {
|
|
2914
|
+
if (this.schedulePruneDegraded.has(record.id)) return;
|
|
2915
|
+
this.schedulePruneDegraded.add(record.id);
|
|
2916
|
+
void this.notifyEvent({
|
|
2917
|
+
kind: "schedule.failed",
|
|
2918
|
+
title: `Retention paused: ${record.name}`,
|
|
2919
|
+
body: `an evicted run's session could not be archived (archive/ unwritable or disk full?) — it stays live; ` +
|
|
2920
|
+
`retention resumes when archiving works again`,
|
|
2921
|
+
data: { scheduleId: record.id },
|
|
2922
|
+
});
|
|
2923
|
+
}
|
|
2924
|
+
|
|
2841
2925
|
private async pruneScheduleSessions(record: ScheduleRecord, ringBefore: string[]): Promise<void> {
|
|
2842
2926
|
if (typeof record.keepRuns !== "number") return;
|
|
2843
2927
|
const ringNow = new Set(record.recentSessionIds ?? []);
|
|
2844
2928
|
const evicted = [...new Set(ringBefore)].filter((id) => !ringNow.has(id));
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2929
|
+
let archived = 0;
|
|
2930
|
+
try {
|
|
2931
|
+
for (const id of evicted) {
|
|
2932
|
+
const row = this.catalog.prepare("SELECT * FROM sessions WHERE id=?").get(id) as SessionRow | undefined;
|
|
2933
|
+
if (!row) continue; // already gone (archived/corrupt-removed) — nothing to do
|
|
2934
|
+
await this.archive(row);
|
|
2935
|
+
archived += 1;
|
|
2936
|
+
}
|
|
2937
|
+
} catch {
|
|
2938
|
+
// R12 P2-1: a persistent archive failure (archive/ unwritable, disk full)
|
|
2939
|
+
// used to be swallowed silently — and since markRun already trimmed the
|
|
2940
|
+
// ring, every later run left one more live session behind FOREVER, the
|
|
2941
|
+
// exact growth this feature exists to prevent, with zero signal.
|
|
2942
|
+
this.markPruneDegraded(record);
|
|
2943
|
+
return;
|
|
2944
|
+
}
|
|
2945
|
+
if (evicted.length > 0 && this.schedulePruneDegraded.delete(record.id)) {
|
|
2946
|
+
void this.notifyEvent({
|
|
2947
|
+
kind: "schedule.ok",
|
|
2948
|
+
title: `Retention resumed: ${record.name}`,
|
|
2949
|
+
body: `archived ${archived} evicted run(s); the window is healthy again`,
|
|
2950
|
+
data: { scheduleId: record.id },
|
|
2951
|
+
});
|
|
2849
2952
|
}
|
|
2850
2953
|
}
|
|
2851
2954
|
|
|
@@ -130,7 +130,12 @@ async function readBodyCapped(
|
|
|
130
130
|
* absent for textual responses so older hubs see an unchanged frame. */
|
|
131
131
|
const TEXTUAL_CT_RE = /^(?:text\/|application\/(?:json|javascript|xml|x-www-form-urlencoded)(?:;|$))/i;
|
|
132
132
|
/** base64 inflates by 4/3 and the serialized envelope must still fit the chunk budget
|
|
133
|
-
* (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom.
|
|
133
|
+
* (CHUNK_RAW_BYTES × MAX_CHUNKS_PER_MESSAGE = 16 MiB), so binaries get their own headroom.
|
|
134
|
+
* R11 3.2 (doc): this 12 MB is the ceiling for EVERY tunnelled binary — an export
|
|
135
|
+
* larger than this refuses with response_too_large (deflate ≈ 3-5× on transcripts,
|
|
136
|
+
* so most sessions fit; the LOCAL device ceiling is the 256 MiB streaming one in
|
|
137
|
+
* zip.ts). The asymmetry is physics: textual frames get 16 MiB logical because
|
|
138
|
+
* they never carry the 4/3 inflation; binaries pay it, so they get 12 MB pre-base64. */
|
|
134
139
|
const BINARY_RESPONSE_MAX_BYTES = 12_000_000;
|
|
135
140
|
const safeHeaderValue = (value: string | null | undefined): string | undefined => {
|
|
136
141
|
if (!value) return undefined;
|
|
@@ -739,7 +744,13 @@ export class DeviceConnector {
|
|
|
739
744
|
tooLarge(
|
|
740
745
|
textual
|
|
741
746
|
? `Device response exceeds ${LOGICAL_MESSAGE_MAX_BYTES} bytes`
|
|
742
|
-
: `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget
|
|
747
|
+
: `Binary response exceeds the ${BINARY_RESPONSE_MAX_BYTES}-byte tunnel budget` +
|
|
748
|
+
// R11 1.3: the two export ceilings must tell ONE story — the
|
|
749
|
+
// tunnel cap is 12 MB compressed, the local one 256 MiB raw;
|
|
750
|
+
// name the remedies instead of a bare byte count.
|
|
751
|
+
(frame.path.endsWith("/export")
|
|
752
|
+
? " — compact the session (archive old agents), or export it directly from the device"
|
|
753
|
+
: ""),
|
|
743
754
|
);
|
|
744
755
|
return;
|
|
745
756
|
}
|
|
@@ -13,13 +13,20 @@
|
|
|
13
13
|
* whole bundle (raw texts + deflate + base64 ≈ 2-3× transcript size, the R5
|
|
14
14
|
* audit's scale cliff) — `streamSessionBundle` composes the same entries from
|
|
15
15
|
* the store's public APIs, deflates each one through a pipe while writing a
|
|
16
|
-
* temp file
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
16
|
+
* temp file, and the route pipes that file to the HTTP response before
|
|
17
|
+
* unlinking it. Entries keep today's paths/payloads; the only layout
|
|
18
|
+
* difference is the streaming form's data descriptor (spec bit 3) so entry
|
|
19
|
+
* sizes can be written after the deflated body without buffering it.
|
|
20
|
+
*
|
|
21
|
+
* R11 1.1: the temp file lives BESIDE THE DATA DIR (same volume as the store,
|
|
22
|
+
* DPI_EXPORT_TMPDIR overrides), not `os.tmpdir()` — a tmpfs-backed /tmp is
|
|
23
|
+
* RAM, and the R5 cliff would return through the back door (or ENOSPC at
|
|
24
|
+
* tmpfs size while the real disk sits empty). "Streaming lifted the RAM
|
|
25
|
+
* cliff" is volume-dependent: the deflate WINDOW is always RAM-bounded, the
|
|
26
|
+
* spill file is disk-bounded only where the data dir lives on real disk.
|
|
20
27
|
*/
|
|
21
28
|
import { randomUUID } from "node:crypto";
|
|
22
|
-
import { open, rm } from "node:fs/promises";
|
|
29
|
+
import { open, rm, stat } from "node:fs/promises";
|
|
23
30
|
import { tmpdir, hostname, platform } from "node:os";
|
|
24
31
|
import { join } from "node:path";
|
|
25
32
|
import { Readable } from "node:stream";
|
|
@@ -218,10 +225,25 @@ const FLAG_DESCRIPTOR = 0x0008;
|
|
|
218
225
|
const DATA_DESCRIPTOR_SIG = 0x08074b50;
|
|
219
226
|
|
|
220
227
|
/**
|
|
221
|
-
* A temp file
|
|
222
|
-
*
|
|
228
|
+
* A temp file (never a hardcoded path — Windows-safe), written 0600 like
|
|
229
|
+
* every other transcript-bearing file on the device. R11 1.1: the SPILL
|
|
230
|
+
* volume is the data dir (real disk, same filesystem the store already
|
|
231
|
+
* writes), `DPI_EXPORT_TMPDIR` overrides, `os.tmpdir()` is the last resort —
|
|
232
|
+
* tmpfs-backed /tmp is RAM and would silently reintroduce the R5 cliff.
|
|
223
233
|
*/
|
|
224
|
-
const tempZipPath = () => join(
|
|
234
|
+
const tempZipPath = (baseDir: string) => join(baseDir, `.dpi-export-${process.pid}-${randomUUID()}.zip`);
|
|
235
|
+
|
|
236
|
+
/** Where the export spill file goes: explicit operator override → the store's
|
|
237
|
+
* own data dir (R11 1.1) → the OS temp dir. Dot-prefixed so a casual `ls`
|
|
238
|
+
* of the data dir does not read as a session artifact. */
|
|
239
|
+
export function exportTempDir(dataDir: string): string {
|
|
240
|
+
// R12 P3-12 (known coupling): the spill shares the data volume with the
|
|
241
|
+
// registries — a 12-256 MB export on a nearly-full disk can push registry
|
|
242
|
+
// writes into ENOSPC (schedules degrade gracefully: R11 2.2 skips runs and
|
|
243
|
+
// reports once) until the export finishes and unlinks. Self-healing by
|
|
244
|
+
// design; noted here so nobody "fixes" it back to tmpfs.
|
|
245
|
+
return process.env.DPI_EXPORT_TMPDIR || dataDir || tmpdir();
|
|
246
|
+
}
|
|
225
247
|
|
|
226
248
|
/**
|
|
227
249
|
* The streaming half of the zip writer. Entries are deflated through a pipe and
|
|
@@ -252,8 +274,8 @@ class ZipStreamWriter {
|
|
|
252
274
|
}
|
|
253
275
|
|
|
254
276
|
/** Create the temp file exclusively, so two exports never share one archive. */
|
|
255
|
-
static async create(): Promise<ZipStreamWriter> {
|
|
256
|
-
const path = tempZipPath();
|
|
277
|
+
static async create(baseDir: string): Promise<ZipStreamWriter> {
|
|
278
|
+
const path = tempZipPath(baseDir);
|
|
257
279
|
const handle = await open(path, "wx", 0o600);
|
|
258
280
|
return new ZipStreamWriter(path, handle);
|
|
259
281
|
}
|
|
@@ -416,7 +438,38 @@ export async function streamSessionBundle(
|
|
|
416
438
|
opts: { ceilingBytes?: number } = {},
|
|
417
439
|
): Promise<StreamedBundle> {
|
|
418
440
|
const ceilingBytes = opts.ceilingBytes ?? EXPORT_TOTAL_LIMIT_BYTES;
|
|
419
|
-
|
|
441
|
+
// R11 1.2: refuse MONSTROUS sessions BEFORE the first stringify. The store db
|
|
442
|
+
// holds every entry the bundle re-serializes, so a db over the ceiling can
|
|
443
|
+
// only refuse later — after a ~2-4× transient (entries clone + pretty JSON)
|
|
444
|
+
// that OOMs instead of answering. A cheap stat converts heap death into the
|
|
445
|
+
// polite, remedy-naming refusal. (A db under the ceiling can still overflow
|
|
446
|
+
// mid-write — json+md ≈ 2× content — and the streaming `add()` guard catches
|
|
447
|
+
// that gracefully, as it always has.)
|
|
448
|
+
const dbBytes = await stat(row.dbPath).then(
|
|
449
|
+
(s) => s.size,
|
|
450
|
+
() => 0,
|
|
451
|
+
);
|
|
452
|
+
if (dbBytes > ceilingBytes) {
|
|
453
|
+
throw invalid(
|
|
454
|
+
`Export refused: this session's store is ${mb(dbBytes)} of data, over the ${mb(ceilingBytes)} export ceiling. ` +
|
|
455
|
+
`Compact the session first (archive old agents), or export it directly from the device`,
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
const tempDir = exportTempDir(store.options.dataDir);
|
|
459
|
+
let writer: ZipStreamWriter;
|
|
460
|
+
try {
|
|
461
|
+
writer = await ZipStreamWriter.create(tempDir);
|
|
462
|
+
} catch (e) {
|
|
463
|
+
// R11 1.4: disk-full surfaces as a typed invalid fault naming the remedy
|
|
464
|
+
// (which volume, which knob), not a raw ENOSPC string on a 500.
|
|
465
|
+
if ((e as NodeJS.ErrnoException).code === "ENOSPC") {
|
|
466
|
+
throw invalid(
|
|
467
|
+
`disk full while creating the export temp file under ${tempDir} — free space on that volume ` +
|
|
468
|
+
`(or point DPI_EXPORT_TMPDIR at one with room) and retry`,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
throw e;
|
|
472
|
+
}
|
|
420
473
|
try {
|
|
421
474
|
for await (const entry of sessionBundleEntries(store, row)) await writer.add(entry, ceilingBytes);
|
|
422
475
|
const bytes = await writer.finish();
|
|
@@ -430,6 +483,13 @@ export async function streamSessionBundle(
|
|
|
430
483
|
};
|
|
431
484
|
} catch (cause) {
|
|
432
485
|
await writer.dispose();
|
|
486
|
+
if ((cause as NodeJS.ErrnoException).code === "ENOSPC") {
|
|
487
|
+
// R11 1.4: mid-write disk-full gets the same typed refusal as create-time.
|
|
488
|
+
throw invalid(
|
|
489
|
+
`disk full while writing the export under ${tempDir} — free space on that volume ` +
|
|
490
|
+
`(or point DPI_EXPORT_TMPDIR at one with room) and retry`,
|
|
491
|
+
);
|
|
492
|
+
}
|
|
433
493
|
throw cause;
|
|
434
494
|
}
|
|
435
495
|
}
|