my-durable 0.0.62 → 0.0.64
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/gc-cli.ts +87 -1
- package/apps/dpi-backend/src/gc.ts +48 -1
- package/apps/dpi-backend/src/graphs.ts +28 -0
- package/apps/dpi-backend/src/pairing-files.ts +65 -0
- package/apps/dpi-backend/src/pairing.ts +25 -9
- package/apps/dpi-backend/src/routes.ts +6 -0
- package/apps/dpi-backend/src/salvage.ts +34 -13
- package/apps/dpi-backend/src/schedules.ts +98 -3
- package/apps/dpi-backend/src/store.ts +92 -9
- package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +1 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/credentials.ts +46 -0
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +21 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +101 -7
- package/apps/dpi-playground/apps/dpi-playground-hub/src/rotation.ts +80 -2
- package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +160 -35
- package/apps/dpi-sdk/src/api.ts +8 -0
- package/apps/dpi-sdk/src/protocol/limits.ts +27 -0
- package/apps/dpi-sdk/src/protocol/tunnel.ts +18 -14
- package/package.json +1 -1
|
@@ -8,8 +8,11 @@
|
|
|
8
8
|
import { readFileSync } from "node:fs";
|
|
9
9
|
import { join } from "node:path";
|
|
10
10
|
import { homedir } from "node:os";
|
|
11
|
-
import { gcApply, gcPlan, humanBytes, parseDuration } from "./gc.js";
|
|
11
|
+
import { gcApply, gcPlan, humanBytes, parseDuration, removedSessionIds } from "./gc.js";
|
|
12
12
|
import { expand, readEnvFile } from "./doctor.js";
|
|
13
|
+
import { lockFile, DeviceAlreadyRunningError } from "./store.js";
|
|
14
|
+
import { ScheduleRegistry } from "./schedules.js";
|
|
15
|
+
import { GraphRegistry } from "./graphs.js";
|
|
13
16
|
|
|
14
17
|
export interface GcArgs {
|
|
15
18
|
argv: readonly string[];
|
|
@@ -133,14 +136,97 @@ export async function gcCli(args: GcArgs, io: GcIo = defaultGcIo()): Promise<num
|
|
|
133
136
|
io.print("re-run with --yes to delete.");
|
|
134
137
|
}
|
|
135
138
|
for (const skip of plan.skipped) io.printErr(`skipped ${skip.name}: ${skip.reason}`);
|
|
139
|
+
if (plan.danglingRefs.schedules > 0 || plan.danglingRefs.graphRuns > 0) {
|
|
140
|
+
io.print(
|
|
141
|
+
`sweep would clear ${plan.danglingRefs.schedules} schedule ref(s) and ${plan.danglingRefs.graphRuns} graph-run ref(s) pointing at the deletions.`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
136
144
|
return 0;
|
|
137
145
|
}
|
|
138
146
|
|
|
139
147
|
const { removed, bytes } = await gcApply(archiveDir, options);
|
|
140
148
|
io.print(`deleted ${removed.length} archived session(s), ${humanBytes(bytes)} freed.`);
|
|
149
|
+
|
|
150
|
+
// R10 Design B: sweep refs pointing at what we just removed. Daemon-first
|
|
151
|
+
// (registry mutations happen in-process, no file race); offline falls back
|
|
152
|
+
// to the same advisory lock Store.open takes.
|
|
153
|
+
const ids = removedSessionIds(removed);
|
|
154
|
+
if (ids.length > 0) {
|
|
155
|
+
try {
|
|
156
|
+
await sweepRefs(dataDirOf(archiveDir), ids, io, deviceToken(io));
|
|
157
|
+
} catch (e) {
|
|
158
|
+
io.printErr(
|
|
159
|
+
`dpi gc: deleted ${ids.length} session(s) but the ref sweep failed: ${
|
|
160
|
+
e instanceof Error ? e.message : String(e)
|
|
161
|
+
} (re-run later — the sweep is idempotent)`,
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
141
165
|
return 0;
|
|
142
166
|
} catch (e) {
|
|
143
167
|
io.printErr(`dpi gc: ${e instanceof Error ? e.message : String(e)}`);
|
|
144
168
|
return 2;
|
|
145
169
|
}
|
|
146
170
|
}
|
|
171
|
+
|
|
172
|
+
const dataDirOf = (archiveDir: string) => archiveDir.slice(0, archiveDir.length - "/archive".length);
|
|
173
|
+
|
|
174
|
+
/** The device token, from the process env or the env file (DPI_ENV_FILE) —
|
|
175
|
+
* only needed for the daemon-first sweep route. */
|
|
176
|
+
function deviceToken(io: GcIo): string | undefined {
|
|
177
|
+
if (io.env.DPI_TOKEN) return io.env.DPI_TOKEN;
|
|
178
|
+
const envFile = io.env.DPI_ENV_FILE;
|
|
179
|
+
if (!envFile) return undefined;
|
|
180
|
+
try {
|
|
181
|
+
return readEnvFile(io.readFile(envFile)).DPI_TOKEN;
|
|
182
|
+
} catch {
|
|
183
|
+
return undefined; // unreadable env file already failed loudly in resolveDataDir
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Daemon-first dangling-ref sweep: POST /v1/gc/sweep-refs when the device
|
|
188
|
+
* answers locally, else the offline lock-guarded registry sweep. Reports what
|
|
189
|
+
* was cleared either way. Throws on failure (the caller prints and exits
|
|
190
|
+
* non-zero — the DELETE already happened; the sweep is idempotent, retryable). */
|
|
191
|
+
async function sweepRefs(dataDir: string, ids: string[], io: GcIo, token?: string): Promise<void> {
|
|
192
|
+
const port = Number(io.env.DPI_PORT ?? "4780");
|
|
193
|
+
if (token && Number.isInteger(port)) {
|
|
194
|
+
try {
|
|
195
|
+
const res = await fetch(`http://127.0.0.1:${port}/v1/gc/sweep-refs`, {
|
|
196
|
+
method: "POST",
|
|
197
|
+
headers: { "content-type": "application/json", "x-dpi-token": token },
|
|
198
|
+
body: JSON.stringify({ sessionIds: ids }),
|
|
199
|
+
signal: AbortSignal.timeout(10_000),
|
|
200
|
+
});
|
|
201
|
+
if (res.ok) {
|
|
202
|
+
const cleared = (await res.json()) as { schedules: number; graphRuns: number };
|
|
203
|
+
if (cleared.schedules || cleared.graphRuns)
|
|
204
|
+
io.print(`swept ${cleared.schedules} schedule ref(s), ${cleared.graphRuns} graph-run ref(s).`);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
// A non-OK from a LIVE device is a real fault — fall through to the
|
|
208
|
+
// offline path would race the daemon; surface it instead.
|
|
209
|
+
throw new Error(`device answered ${res.status} to the sweep route`);
|
|
210
|
+
} catch (e) {
|
|
211
|
+
if (e instanceof TypeError || (e instanceof Error && /fetch|network|ECONN/i.test(e.message))) {
|
|
212
|
+
/* device not reachable locally — offline path below */
|
|
213
|
+
} else throw e;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
// Offline: the same advisory lock Store.open takes, so a live (but
|
|
217
|
+
// unreachable) daemon refuses instead of racing us on the registry files.
|
|
218
|
+
const unlock = lockFile(join(dataDir, "app-state.sqlite.lock"));
|
|
219
|
+
try {
|
|
220
|
+
const schedules = await ScheduleRegistry.open(join(dataDir, "schedules.json"));
|
|
221
|
+
const graphs = await GraphRegistry.open(join(dataDir, "graphs.json"));
|
|
222
|
+
const s = await schedules.clearSessionRefs(new Set(ids));
|
|
223
|
+
const g = await graphs.clearSessionRefs(new Set(ids));
|
|
224
|
+
if (s || g) io.print(`swept ${s} schedule ref(s), ${g} graph-run ref(s).`);
|
|
225
|
+
} catch (e) {
|
|
226
|
+
if (e instanceof DeviceAlreadyRunningError)
|
|
227
|
+
throw new Error("device is running — retry via the API route (dpi gc after the device answers, or restart it)");
|
|
228
|
+
throw e;
|
|
229
|
+
} finally {
|
|
230
|
+
unlock();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
* readable without opening any database.
|
|
17
17
|
*/
|
|
18
18
|
import { readdir, rm, stat } from "node:fs/promises";
|
|
19
|
-
import {
|
|
19
|
+
import { readFileSync } from "node:fs";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
20
21
|
import { BUNDLE_DIR_PATTERN } from "./archived.js";
|
|
21
22
|
|
|
22
23
|
export interface ArchivedEntry {
|
|
@@ -43,6 +44,10 @@ export interface GcPlan {
|
|
|
43
44
|
candidateBytes: number;
|
|
44
45
|
/** Directories we could not read (kept, never deleted). */
|
|
45
46
|
skipped: { name: string; reason: string }[];
|
|
47
|
+
/** R10 Design B: refs that WOULD dangle if the candidates were deleted —
|
|
48
|
+
* schedule `lastSessionId`s and graph `TaskRunState.sessionId`s pointing at
|
|
49
|
+
* candidate session ids. The operator sees the referential cost of --yes. */
|
|
50
|
+
danglingRefs: { schedules: number; graphRuns: number };
|
|
46
51
|
}
|
|
47
52
|
|
|
48
53
|
async function dirBytes(path: string): Promise<number> {
|
|
@@ -95,6 +100,39 @@ export async function archivedEntries(
|
|
|
95
100
|
return { entries: entries.sort((a, b) => b.closedAt - a.closedAt), skipped };
|
|
96
101
|
}
|
|
97
102
|
|
|
103
|
+
/** R10 Design B: count refs that would dangle if `ids` were removed. Tolerant
|
|
104
|
+
* raw reads — the registries may not exist yet, and a corrupt file must never
|
|
105
|
+
* stop a gc plan (the sweep itself runs through the registries' own safe
|
|
106
|
+
* commit paths). */
|
|
107
|
+
export function danglingRefCounts(
|
|
108
|
+
dataDir: string,
|
|
109
|
+
ids: ReadonlySet<string>,
|
|
110
|
+
readFile: (p: string) => string = (p) => readFileSync(p, "utf8"),
|
|
111
|
+
): { schedules: number; graphRuns: number } {
|
|
112
|
+
if (ids.size === 0) return { schedules: 0, graphRuns: 0 };
|
|
113
|
+
let schedules = 0;
|
|
114
|
+
let graphRuns = 0;
|
|
115
|
+
try {
|
|
116
|
+
const doc = JSON.parse(readFile(join(dataDir, "schedules.json"))) as {
|
|
117
|
+
schedules?: Array<{ lastSessionId?: string }>;
|
|
118
|
+
};
|
|
119
|
+
for (const s of doc.schedules ?? []) if (s.lastSessionId && ids.has(s.lastSessionId)) schedules += 1;
|
|
120
|
+
} catch {
|
|
121
|
+
/* absent or unreadable — nothing countable */
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const doc = JSON.parse(readFile(join(dataDir, "graphs.json"))) as {
|
|
125
|
+
runs?: Array<{ tasks?: Record<string, { sessionId?: string }> }>;
|
|
126
|
+
};
|
|
127
|
+
for (const run of doc.runs ?? [])
|
|
128
|
+
for (const task of Object.values(run.tasks ?? {}))
|
|
129
|
+
if (task.sessionId && ids.has(task.sessionId)) graphRuns += 1;
|
|
130
|
+
} catch {
|
|
131
|
+
/* absent or unreadable — nothing countable */
|
|
132
|
+
}
|
|
133
|
+
return { schedules, graphRuns };
|
|
134
|
+
}
|
|
135
|
+
|
|
98
136
|
/** What a retention policy would delete. Pure read: nothing is touched. */
|
|
99
137
|
export async function gcPlan(archiveDir: string, options: { closedBeforeDays: number; now?: number }): Promise<GcPlan> {
|
|
100
138
|
const now = options.now ?? Date.now();
|
|
@@ -107,11 +145,13 @@ export async function gcPlan(archiveDir: string, options: { closedBeforeDays: nu
|
|
|
107
145
|
const candidates = entries
|
|
108
146
|
.filter((entry) => entry.closedAt <= cutoff)
|
|
109
147
|
.map((entry) => ({ ...entry, ageDays: Math.floor((now - entry.closedAt) / 86_400_000) }));
|
|
148
|
+
const candidateIds = new Set(candidates.map((c) => c.sessionId));
|
|
110
149
|
return {
|
|
111
150
|
total: { count: entries.length, bytes: entries.reduce((n, e) => n + e.bytes, 0) },
|
|
112
151
|
candidates,
|
|
113
152
|
candidateBytes: candidates.reduce((n, e) => n + e.bytes, 0),
|
|
114
153
|
skipped,
|
|
154
|
+
danglingRefs: danglingRefCounts(dirname(archiveDir), candidateIds),
|
|
115
155
|
};
|
|
116
156
|
}
|
|
117
157
|
|
|
@@ -138,6 +178,13 @@ export async function gcApply(
|
|
|
138
178
|
return { removed, bytes: removed.reduce((n, e) => n + e.bytes, 0) };
|
|
139
179
|
}
|
|
140
180
|
|
|
181
|
+
/** R10 Design B: the removed ids a ref-sweep should target (gcApply callers
|
|
182
|
+
* pass these on — to the daemon route when it answers, else the offline
|
|
183
|
+
* sweep). Derived from what gcApply actually removed. */
|
|
184
|
+
export function removedSessionIds(removed: readonly GcCandidate[]): string[] {
|
|
185
|
+
return removed.map((c) => c.sessionId);
|
|
186
|
+
}
|
|
187
|
+
|
|
141
188
|
/**
|
|
142
189
|
* "30d", "12h", "90m", "2w" → days (fractional). Days is the unit the plan
|
|
143
190
|
* reasons in, so hours/weeks are converted here rather than refused.
|
|
@@ -682,6 +682,34 @@ export class GraphRegistry {
|
|
|
682
682
|
});
|
|
683
683
|
}
|
|
684
684
|
|
|
685
|
+
/** R10 Design B: clear TaskRunState.sessionId links pointing at sessions a gc
|
|
686
|
+
* pass removed — the run's status/error/timestamps stay (history is true,
|
|
687
|
+
* the link is gone). Idempotent by construction; returns how many links
|
|
688
|
+
* were cleared (for the CLI report and the dry-run parity check). */
|
|
689
|
+
async clearSessionRefs(ids: Set<string>): Promise<number> {
|
|
690
|
+
if (ids.size === 0) return 0;
|
|
691
|
+
let cleared = 0;
|
|
692
|
+
await this.run(async () => {
|
|
693
|
+
const runs = this.runRecords.map((run) => {
|
|
694
|
+
if (!run.tasks) return run;
|
|
695
|
+
let touched = false;
|
|
696
|
+
const tasks: Record<string, TaskRunState> = {};
|
|
697
|
+
for (const [taskId, task] of Object.entries(run.tasks)) {
|
|
698
|
+
if (task.sessionId !== undefined && ids.has(task.sessionId)) {
|
|
699
|
+
const { sessionId, ...rest } = task;
|
|
700
|
+
void sessionId;
|
|
701
|
+
tasks[taskId] = rest as TaskRunState;
|
|
702
|
+
cleared += 1;
|
|
703
|
+
touched = true;
|
|
704
|
+
} else tasks[taskId] = task;
|
|
705
|
+
}
|
|
706
|
+
return touched ? { ...run, tasks } : run;
|
|
707
|
+
});
|
|
708
|
+
await this.commit(new Map(this.graphs), runs);
|
|
709
|
+
});
|
|
710
|
+
return cleared;
|
|
711
|
+
}
|
|
712
|
+
|
|
685
713
|
/**
|
|
686
714
|
* Soft delete. Archiving an already-archived graph keeps the original stamp —
|
|
687
715
|
* the first archive is the fact, a second one is a double click.
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import {
|
|
11
11
|
chmodSync,
|
|
12
12
|
closeSync,
|
|
13
|
+
copyFileSync,
|
|
13
14
|
fsyncSync,
|
|
14
15
|
openSync,
|
|
15
16
|
readFileSync,
|
|
@@ -101,6 +102,70 @@ export function loadJson<T>(path: string): T | undefined {
|
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
104
|
|
|
105
|
+
/** Outcome of loading the device pairing state. Exactly one of `file`/`corrupt` is set; a fresh device has neither. */
|
|
106
|
+
export interface PairingFileLoad {
|
|
107
|
+
/** A parseable pairing.json (shape is judged by the caller). */
|
|
108
|
+
file?: PairingFile;
|
|
109
|
+
/** pairing.json existed but was not valid JSON — it was quarantined (or, if that failed, left in place). */
|
|
110
|
+
corrupt?: { quarantinedAs: string };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* R9 (audit 1.1): a corrupt pairing.json must never read as a silent "unpaired" —
|
|
115
|
+
* that orphans a live hub credential with no trace on disk. Following the
|
|
116
|
+
* schedules registry pattern (schedules.ts load(): move aside + warn): a parse
|
|
117
|
+
* failure renames the file aside so the bytes survive for inspection/restore,
|
|
118
|
+
* with a loud warning naming the quarantine path. A read failure (permissions,
|
|
119
|
+
* I/O) keeps the file in place — its bytes may be fine — but is warned about,
|
|
120
|
+
* never swallowed.
|
|
121
|
+
*/
|
|
122
|
+
export function loadPairingFile(home: string): PairingFileLoad {
|
|
123
|
+
const path = pairingPath(home);
|
|
124
|
+
let raw: string;
|
|
125
|
+
try {
|
|
126
|
+
raw = readFileSync(path, "utf8");
|
|
127
|
+
} catch (e) {
|
|
128
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") return {}; // fresh device: nothing to load
|
|
129
|
+
console.warn(
|
|
130
|
+
`[pairing] ${path} could not be read (${(e as Error).message}); the device reads as unpaired — fix the file before re-pairing, or a live hub credential stays orphaned`,
|
|
131
|
+
);
|
|
132
|
+
return {};
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
return { file: JSON.parse(raw) as PairingFile };
|
|
136
|
+
} catch (e) {
|
|
137
|
+
const aside = `${path}.corrupt-${Date.now()}`;
|
|
138
|
+
try {
|
|
139
|
+
renameSync(path, aside);
|
|
140
|
+
} catch {
|
|
141
|
+
console.warn(
|
|
142
|
+
`[pairing] pairing.json is not valid JSON (${(e as Error).message}) and could not be moved aside; it was left untouched in place`,
|
|
143
|
+
);
|
|
144
|
+
return { corrupt: { quarantinedAs: path } };
|
|
145
|
+
}
|
|
146
|
+
console.warn(
|
|
147
|
+
`[pairing] pairing.json was not valid JSON (${(e as Error).message}) — a live hub credential may now be orphaned. ` +
|
|
148
|
+
`The unreadable file was quarantined as ${aside}; recover it from a backup (or the last-good ${path}.bak), or re-pair this device`,
|
|
149
|
+
);
|
|
150
|
+
return { corrupt: { quarantinedAs: aside } };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Keep the previous good pairing.json as `.bak` before it is replaced (R9 1.1,
|
|
156
|
+
* same recovery story as the schedules registry): even after the corrupt
|
|
157
|
+
* original was quarantined there is a known-good recovery source on disk.
|
|
158
|
+
* Best effort — a failed backup never blocks the atomic replacement.
|
|
159
|
+
*/
|
|
160
|
+
export function backUpPairingFile(path: string): void {
|
|
161
|
+
try {
|
|
162
|
+
copyFileSync(path, `${path}.bak`);
|
|
163
|
+
ensureFileMode0600(`${path}.bak`);
|
|
164
|
+
} catch {
|
|
165
|
+
/* nothing to back up (first pairing) or the copy failed — the new file still lands atomically */
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
104
169
|
/**
|
|
105
170
|
* The device key, or undefined when there is none yet. Anything else that keeps it from being read (permissions,
|
|
106
171
|
* I/O error, truncated or damaged contents) throws: the caller must not answer that by minting a new identity
|
|
@@ -24,10 +24,11 @@ import {
|
|
|
24
24
|
import { hostname, platform } from "node:os";
|
|
25
25
|
import type { Store } from "./store.js";
|
|
26
26
|
import {
|
|
27
|
+
backUpPairingFile,
|
|
27
28
|
ensureFileMode0600,
|
|
28
29
|
ensurePrivateDir,
|
|
29
30
|
keypairPath,
|
|
30
|
-
|
|
31
|
+
loadPairingFile,
|
|
31
32
|
pairingPath,
|
|
32
33
|
readKeypairFile,
|
|
33
34
|
removeStaleTemps,
|
|
@@ -80,7 +81,8 @@ export interface PairingStartInput {
|
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
export type PairingStatus = {
|
|
83
|
-
|
|
84
|
+
/** `file-error`: pairing.json was present but unreadable/unparseable — it was quarantined (R9 1.1); lastError names the path. */
|
|
85
|
+
state: "unpaired" | "pairing" | "paired" | "revoked" | "file-error";
|
|
84
86
|
deviceUid: string;
|
|
85
87
|
deviceName: string;
|
|
86
88
|
fingerprint: string; // from the LOCAL key — never echoed from the hub
|
|
@@ -180,6 +182,8 @@ export class DevicePairing {
|
|
|
180
182
|
private keypair: DeviceKeypair | undefined;
|
|
181
183
|
private paired: PairingFile | undefined;
|
|
182
184
|
private revokedNotice = false;
|
|
185
|
+
/** R9 1.1: pairing.json was quarantined at boot — a live hub credential may be orphaned (detail names the path). */
|
|
186
|
+
private fileError: string | undefined;
|
|
183
187
|
|
|
184
188
|
constructor(
|
|
185
189
|
private readonly store: Store,
|
|
@@ -197,7 +201,12 @@ export class DevicePairing {
|
|
|
197
201
|
ensurePrivateDir(home);
|
|
198
202
|
removeStaleTemps(home);
|
|
199
203
|
this.loadKeypair();
|
|
200
|
-
|
|
204
|
+
const loaded = loadPairingFile(home);
|
|
205
|
+
if (loaded.corrupt)
|
|
206
|
+
this.fileError =
|
|
207
|
+
`pairing.json was not valid JSON and was quarantined as ${loaded.corrupt.quarantinedAs}; ` +
|
|
208
|
+
`a live hub credential may be orphaned — recover it from a backup or ${pairingPath(home)}.bak, or re-pair`;
|
|
209
|
+
this.paired = loaded.file;
|
|
201
210
|
if (this.paired) ensureFileMode0600(pairingPath(home));
|
|
202
211
|
if (this.paired) ensurePrivateDir(home);
|
|
203
212
|
}
|
|
@@ -229,11 +238,13 @@ export class DevicePairing {
|
|
|
229
238
|
const base: PairingStatus = {
|
|
230
239
|
state: this.pending
|
|
231
240
|
? "pairing"
|
|
232
|
-
: this.
|
|
233
|
-
? "
|
|
234
|
-
: this.
|
|
235
|
-
? "
|
|
236
|
-
:
|
|
241
|
+
: this.fileError
|
|
242
|
+
? "file-error"
|
|
243
|
+
: this.revokedNotice
|
|
244
|
+
? "revoked"
|
|
245
|
+
: this.paired
|
|
246
|
+
? "paired"
|
|
247
|
+
: "unpaired",
|
|
237
248
|
deviceUid: this.store.uid,
|
|
238
249
|
deviceName: this.deviceName,
|
|
239
250
|
fingerprint: this.keypair!.fingerprint,
|
|
@@ -254,7 +265,9 @@ export class DevicePairing {
|
|
|
254
265
|
},
|
|
255
266
|
}
|
|
256
267
|
: {}),
|
|
257
|
-
...(this.lastFailure
|
|
268
|
+
...((this.lastFailure ?? this.fileError)
|
|
269
|
+
? { lastError: this.lastFailure ?? this.fileError }
|
|
270
|
+
: {}),
|
|
258
271
|
};
|
|
259
272
|
return base;
|
|
260
273
|
}
|
|
@@ -680,6 +693,8 @@ export class DevicePairing {
|
|
|
680
693
|
// never authenticated (the proof was checked at the challenge, not here).
|
|
681
694
|
...(pending.kfp ? { hubKeyFingerprint: pending.kfp } : {}),
|
|
682
695
|
};
|
|
696
|
+
// R9 1.1: keep the previous good file recoverable before it is replaced.
|
|
697
|
+
backUpPairingFile(pairingPath(this.home));
|
|
683
698
|
writeAtomic(pairingPath(this.home), JSON.stringify(file, null, 2));
|
|
684
699
|
// Re-check: a newer operation/pairing must not be clobbered by this commit.
|
|
685
700
|
if (this.pending?.operationId !== pending.operationId) return;
|
|
@@ -688,6 +703,7 @@ export class DevicePairing {
|
|
|
688
703
|
this.paired = file;
|
|
689
704
|
this.pending = undefined;
|
|
690
705
|
this.lastFailure = undefined;
|
|
706
|
+
this.fileError = undefined; // a good file just landed; the quarantine notice is obsolete
|
|
691
707
|
this.revokedNotice = false;
|
|
692
708
|
// The old hub keeps its tunnel and its pairing right up to here: only a persisted replacement ends them.
|
|
693
709
|
if (previous && previous.hubOrigin !== file.hubOrigin) {
|
|
@@ -307,6 +307,12 @@ export function v1(
|
|
|
307
307
|
// The device owns execution (systemd/cron are deliberately rejected by config);
|
|
308
308
|
// these routes only read and edit the schedule records.
|
|
309
309
|
r.get("/schedules", (_req, res) => res.json({ schedules: store.scheduleList() }));
|
|
310
|
+
// R10 Design B: the daemon-side dangling-ref sweep. Deliberately NOT in the
|
|
311
|
+
// tunnel REST allowlist (apps/dpi-sdk/src/protocol/rest-routes.ts): this is
|
|
312
|
+
// device-LOCAL operator maintenance (the gc CLI calls it when the device is
|
|
313
|
+
// up, so registry mutations happen in-process with no file race) — the same
|
|
314
|
+
// operator-only surface as `dpi gc` itself.
|
|
315
|
+
r.post("/gc/sweep-refs", route(async (req, res) => res.json(await store.gcSweepRefs((req.body ?? {}).sessionIds))));
|
|
310
316
|
r.post("/schedules", route(async (req, res) => res.status(201).json(await store.createSchedule(req.body ?? {}))));
|
|
311
317
|
r.patch("/schedules/:id", route(async (req, res) => res.json(await store.updateSchedule(param(req, "id"), req.body ?? {}))));
|
|
312
318
|
r.delete("/schedules/:id", route(async (req, res) => res.json(await store.removeSchedule(param(req, "id")))));
|
|
@@ -34,7 +34,8 @@
|
|
|
34
34
|
* are removed and the original is left byte-identical.
|
|
35
35
|
*/
|
|
36
36
|
import { Worker } from "node:worker_threads";
|
|
37
|
-
import { existsSync, renameSync, rmSync } from "node:fs";
|
|
37
|
+
import { existsSync, linkSync, renameSync, rmSync } from "node:fs";
|
|
38
|
+
import { randomUUID } from "node:crypto";
|
|
38
39
|
|
|
39
40
|
/** The open path must never hang on salvage: everything above this ceiling is abandoned. */
|
|
40
41
|
export const SALVAGE_CEILING_MS = 5_000;
|
|
@@ -61,7 +62,7 @@ const { parentPort, workerData } = require("node:worker_threads");
|
|
|
61
62
|
const { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } = require("node:fs");
|
|
62
63
|
const { DatabaseSync } = require("node:sqlite");
|
|
63
64
|
const main = workerData.dbPath;
|
|
64
|
-
const copy =
|
|
65
|
+
const copy = workerData.copyPath; // R10 5.2: unique per attempt — two workers never share scratch files
|
|
65
66
|
const fail = (reason) => parentPort.postMessage({ ok: false, reason: String(reason).slice(0, 80) });
|
|
66
67
|
function run() {
|
|
67
68
|
try {
|
|
@@ -118,17 +119,36 @@ try {
|
|
|
118
119
|
run();
|
|
119
120
|
`;
|
|
120
121
|
|
|
121
|
-
const rmCopyFiles = (
|
|
122
|
-
for (const suffix of ["
|
|
122
|
+
const rmCopyFiles = (copyPath: string) => {
|
|
123
|
+
for (const suffix of ["", "-wal", "-shm"]) rmSync(copyPath + suffix, { force: true });
|
|
123
124
|
};
|
|
124
125
|
|
|
125
|
-
/**
|
|
126
|
-
|
|
126
|
+
/** R10 5.2: a scratch name unique per attempt, so a second salvage on the same
|
|
127
|
+
* session (two routes opening one corrupt db concurrently) can never eat the
|
|
128
|
+
* first attempt's in-flight copy — the audit's strand-the-db scenario. */
|
|
129
|
+
const scratchPath = (dbPath: string): string =>
|
|
130
|
+
`${dbPath}.salvage-${process.pid.toString(36)}-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
|
|
131
|
+
|
|
132
|
+
/** Promote the verified copy (R10 5.1: crash-window free). The ORIGINAL and its
|
|
133
|
+
* sidecars are hardlink-kept aside FIRST (link(2) — same bytes, no copy), the
|
|
134
|
+
* stale live sidecars are then removed, and ONE atomic rename puts the copy in
|
|
135
|
+
* place. At every crash point either the original or the promoted copy sits at
|
|
136
|
+
* the db path — never neither:
|
|
137
|
+
* - before the sidecar rm: retry sees the untouched original (+ its sidecars).
|
|
138
|
+
* - after it, before the rename: the original main is still in place (its
|
|
139
|
+
* sidecars live on via the aside links; a retry re-salvages to the last
|
|
140
|
+
* checkpoint — the honest-stale case, disclosed in the promote warning). */
|
|
141
|
+
const promote = (dbPath: string, copyPath: string): string => {
|
|
127
142
|
const aside = `${dbPath}.corrupt-${Date.now()}`;
|
|
128
|
-
|
|
129
|
-
for (const suffix of ["-wal", "-shm"])
|
|
130
|
-
|
|
131
|
-
|
|
143
|
+
linkSync(dbPath, aside);
|
|
144
|
+
for (const suffix of ["-wal", "-shm"]) {
|
|
145
|
+
if (existsSync(dbPath + suffix)) {
|
|
146
|
+
linkSync(dbPath + suffix, `${aside}${suffix}`);
|
|
147
|
+
rmSync(dbPath + suffix, { force: true }); // stale against the promoted main
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
renameSync(copyPath, dbPath); // POSIX rename: atomic replace
|
|
151
|
+
rmCopyFiles(copyPath); // the copy's own sidecars were checkpointed away; drop leftovers
|
|
132
152
|
return aside;
|
|
133
153
|
};
|
|
134
154
|
|
|
@@ -140,8 +160,9 @@ const promote = (dbPath: string): string => {
|
|
|
140
160
|
export function salvageSessionDb(dbPath: string, ceilingMs: number = SALVAGE_CEILING_MS): Promise<SalvageOutcome> {
|
|
141
161
|
return new Promise((resolve) => {
|
|
142
162
|
let worker: Worker;
|
|
163
|
+
const copyPath = scratchPath(dbPath); // R10 5.2: unique scratch per attempt
|
|
143
164
|
try {
|
|
144
|
-
worker = new Worker(WORKER_SRC, { eval: true, workerData: { dbPath } });
|
|
165
|
+
worker = new Worker(WORKER_SRC, { eval: true, workerData: { dbPath, copyPath } });
|
|
145
166
|
} catch {
|
|
146
167
|
resolve({ attempted: false, recovered: false, reason: "salvage worker unavailable" });
|
|
147
168
|
return;
|
|
@@ -155,12 +176,12 @@ export function salvageSessionDb(dbPath: string, ceilingMs: number = SALVAGE_CEI
|
|
|
155
176
|
let outcome = result;
|
|
156
177
|
if (outcome.recovered) {
|
|
157
178
|
try {
|
|
158
|
-
outcome = { ...outcome, keptAs: promote(dbPath) };
|
|
179
|
+
outcome = { ...outcome, keptAs: promote(dbPath, copyPath) };
|
|
159
180
|
} catch {
|
|
160
181
|
outcome = { attempted: true, recovered: false, reason: "promotion failed" };
|
|
161
182
|
}
|
|
162
183
|
}
|
|
163
|
-
if (!outcome.recovered) rmCopyFiles(
|
|
184
|
+
if (!outcome.recovered) rmCopyFiles(copyPath);
|
|
164
185
|
resolve(outcome);
|
|
165
186
|
};
|
|
166
187
|
const timer = setTimeout(() => {
|