@dench.com/cli 3.12.10-staging.1240 → 3.12.11-staging.1243
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/fs-daemon-sync-tracker.ts +29 -7
- package/fs-daemon-workspace.ts +46 -26
- package/home-sync-lib.ts +131 -0
- package/home-sync.ts +59 -40
- package/lib/machines.ts +80 -0
- package/lib/state-machine.ts +205 -0
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DrainStatus } from "./fs-daemon-flush";
|
|
2
|
+
|
|
2
3
|
const CIRCUIT_BREAKER_LIMIT = 5;
|
|
3
4
|
const CIRCUIT_BREAKER_WINDOW_MS = 10_000;
|
|
4
5
|
const CIRCUIT_BREAKER_PAUSE_MS = 60_000;
|
|
@@ -19,6 +20,14 @@ export class HashTracker {
|
|
|
19
20
|
private timers = new Map<string, NodeJS.Timeout>();
|
|
20
21
|
private recentSyncs = new Map<string, number[]>();
|
|
21
22
|
private paused = new Map<string, BreakerState>();
|
|
23
|
+
/**
|
|
24
|
+
* The release timer of each path's current trip. A release ends only the
|
|
25
|
+
* trip that armed it. Before, the timer was fire-and-forget: after
|
|
26
|
+
* `forget()` (the file was deleted) and a new trip of the recreated file,
|
|
27
|
+
* the first trip's timer released the second pause early and wiped its
|
|
28
|
+
* sync history.
|
|
29
|
+
*/
|
|
30
|
+
private breakerReleases = new Map<string, NodeJS.Timeout>();
|
|
22
31
|
private onBreakerTrip?: (state: BreakerState) => void;
|
|
23
32
|
// Bumped right before each scheduled fn() actually starts; decremented
|
|
24
33
|
// in the fn()'s `.finally()`. The flush subcommand reads this through
|
|
@@ -53,6 +62,11 @@ export class HashTracker {
|
|
|
53
62
|
}
|
|
54
63
|
this.recentSyncs.delete(absPath);
|
|
55
64
|
this.paused.delete(absPath);
|
|
65
|
+
const release = this.breakerReleases.get(absPath);
|
|
66
|
+
if (release) {
|
|
67
|
+
clearTimeout(release);
|
|
68
|
+
this.breakerReleases.delete(absPath);
|
|
69
|
+
}
|
|
56
70
|
}
|
|
57
71
|
|
|
58
72
|
knownPaths(): string[] {
|
|
@@ -93,13 +107,21 @@ export class HashTracker {
|
|
|
93
107
|
`[dench-fs-daemon] CIRCUIT_BREAKER tripped path=${absPath} syncs=${recent.length} pause=${CIRCUIT_BREAKER_PAUSE_MS}ms`,
|
|
94
108
|
);
|
|
95
109
|
this.onBreakerTrip?.(state);
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
110
|
+
const previous = this.breakerReleases.get(absPath);
|
|
111
|
+
if (previous) clearTimeout(previous);
|
|
112
|
+
this.breakerReleases.set(
|
|
113
|
+
absPath,
|
|
114
|
+
setTimeout(() => {
|
|
115
|
+
// Only the trip that armed this timer is released by it.
|
|
116
|
+
if (this.paused.get(absPath) !== state) return;
|
|
117
|
+
this.breakerReleases.delete(absPath);
|
|
118
|
+
this.paused.delete(absPath);
|
|
119
|
+
this.recentSyncs.delete(absPath);
|
|
120
|
+
console.warn(
|
|
121
|
+
`[dench-fs-daemon] circuit breaker released for ${absPath}`,
|
|
122
|
+
);
|
|
123
|
+
}, CIRCUIT_BREAKER_PAUSE_MS),
|
|
124
|
+
);
|
|
103
125
|
return true;
|
|
104
126
|
}
|
|
105
127
|
return false;
|
package/fs-daemon-workspace.ts
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
/** Mounted I/O belongs to a PROCESS, not a worker thread: threads share
|
|
2
2
|
* libuv's pool. A stuck FUSE stat must not starve parent DNS or /tmp queues. */
|
|
3
|
-
import {
|
|
3
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
4
4
|
import { EventEmitter } from "node:events";
|
|
5
5
|
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
6
6
|
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
|
+
import {
|
|
9
|
+
type WorkspaceWorkerState,
|
|
10
|
+
workspaceWorkerMachine,
|
|
11
|
+
} from "./lib/machines";
|
|
8
12
|
|
|
9
13
|
export type WorkspaceWorkerStatus = {
|
|
10
|
-
|
|
14
|
+
/** Moves only through `workspaceWorkerMachine` (lib/machines.ts). */
|
|
15
|
+
state: WorkspaceWorkerState;
|
|
11
16
|
pid: number | null;
|
|
12
17
|
lastProgressAt: number | null;
|
|
13
18
|
restarts: number;
|
|
@@ -83,7 +88,6 @@ export class WorkspaceIo extends EventEmitter {
|
|
|
83
88
|
private child: ChildProcess | null = null;
|
|
84
89
|
private sequence = 0;
|
|
85
90
|
private closed = false;
|
|
86
|
-
private ready = false;
|
|
87
91
|
private restartTimes: number[] = [];
|
|
88
92
|
private restartTimer?: ReturnType<typeof setTimeout>;
|
|
89
93
|
private watching: boolean | null = null;
|
|
@@ -124,10 +128,22 @@ export class WorkspaceIo extends EventEmitter {
|
|
|
124
128
|
private changed() {
|
|
125
129
|
this.emit("status", this.snapshot());
|
|
126
130
|
}
|
|
131
|
+
/** The only writer of `health.state`. */
|
|
132
|
+
private moveTo(to: WorkspaceWorkerState): "moved" | "same" | "refused" {
|
|
133
|
+
const decision = workspaceWorkerMachine.decide(this.health.state, to);
|
|
134
|
+
if (decision.kind === "apply") {
|
|
135
|
+
this.health.state = to;
|
|
136
|
+
return "moved";
|
|
137
|
+
}
|
|
138
|
+
return decision.kind === "same" ? "same" : "refused";
|
|
139
|
+
}
|
|
140
|
+
private get ready(): boolean {
|
|
141
|
+
return this.health.state === "ready";
|
|
142
|
+
}
|
|
127
143
|
private launch() {
|
|
128
144
|
if (this.closed || this.child) return;
|
|
129
|
-
|
|
130
|
-
this.
|
|
145
|
+
// backoff → starting (the constructor's first launch is already starting).
|
|
146
|
+
if (this.moveTo("starting") === "refused") return;
|
|
131
147
|
this.health.lastProgressAt = null;
|
|
132
148
|
const child =
|
|
133
149
|
this.options.spawnWorker?.() ??
|
|
@@ -154,8 +170,7 @@ export class WorkspaceIo extends EventEmitter {
|
|
|
154
170
|
if (this.child !== child || this.health.state === "stalled") return;
|
|
155
171
|
if (message.event === "ready") {
|
|
156
172
|
clearTimeout(bootTimer);
|
|
157
|
-
this.ready
|
|
158
|
-
this.health.state = "ready";
|
|
173
|
+
if (this.moveTo("ready") !== "moved") return;
|
|
159
174
|
this.health.error = null;
|
|
160
175
|
this.changed();
|
|
161
176
|
for (const item of this.pending.values()) this.send(item.request);
|
|
@@ -193,11 +208,11 @@ export class WorkspaceIo extends EventEmitter {
|
|
|
193
208
|
clearTimeout(bootTimer);
|
|
194
209
|
if (this.child !== child) return;
|
|
195
210
|
this.child = null;
|
|
196
|
-
this.ready = false;
|
|
197
211
|
this.health.pid = null;
|
|
198
212
|
this.rejectPending(new Error("workspace_io_unavailable: worker exited"));
|
|
199
213
|
if (this.closed) return;
|
|
200
|
-
|
|
214
|
+
// The OS confirmed the exit: the only way out of `stalled`.
|
|
215
|
+
this.moveTo("backoff");
|
|
201
216
|
const now = Date.now();
|
|
202
217
|
this.restartTimes = this.restartTimes.filter((at) => now - at < 60_000);
|
|
203
218
|
// At most two replacements per minute, and ONLY after observed exit.
|
|
@@ -245,8 +260,7 @@ export class WorkspaceIo extends EventEmitter {
|
|
|
245
260
|
this.pending.clear();
|
|
246
261
|
}
|
|
247
262
|
private stall(message: string) {
|
|
248
|
-
if (this.closed || this.
|
|
249
|
-
this.health.state = "stalled";
|
|
263
|
+
if (this.closed || this.moveTo("stalled") !== "moved") return;
|
|
250
264
|
this.health.error = message;
|
|
251
265
|
this.rejectPending(new Error(message));
|
|
252
266
|
this.changed();
|
|
@@ -278,22 +292,28 @@ export class WorkspaceIo extends EventEmitter {
|
|
|
278
292
|
const livenessTimeout = stallOnTimeout
|
|
279
293
|
? usedTimeout
|
|
280
294
|
: (this.options.timeoutMs ?? IO_TIMEOUT_MS);
|
|
281
|
-
const timer = setTimeout(
|
|
282
|
-
|
|
283
|
-
this.
|
|
284
|
-
|
|
295
|
+
const timer = setTimeout(
|
|
296
|
+
() => {
|
|
297
|
+
if (this.pending.has(id))
|
|
298
|
+
this.stall("workspace_io_timeout: " + method);
|
|
299
|
+
},
|
|
300
|
+
Math.max(1, livenessTimeout),
|
|
301
|
+
);
|
|
285
302
|
const callerTimer = stallOnTimeout
|
|
286
303
|
? undefined
|
|
287
|
-
: setTimeout(
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
304
|
+
: setTimeout(
|
|
305
|
+
() => {
|
|
306
|
+
const item = this.pending.get(id);
|
|
307
|
+
if (!item) return;
|
|
308
|
+
if (!item.sent) {
|
|
309
|
+
// Expired startup work must never be sent after ready.
|
|
310
|
+
this.pending.delete(id);
|
|
311
|
+
clearTimeout(item.timer);
|
|
312
|
+
}
|
|
313
|
+
item.reject(new Error("workspace_io_timeout: " + method));
|
|
314
|
+
},
|
|
315
|
+
Math.max(1, usedTimeout),
|
|
316
|
+
);
|
|
297
317
|
this.pending.set(id, {
|
|
298
318
|
request,
|
|
299
319
|
resolve: (value) => resolveValue(value as T),
|
|
@@ -340,7 +360,7 @@ export class WorkspaceIo extends EventEmitter {
|
|
|
340
360
|
close() {
|
|
341
361
|
this.closed = true;
|
|
342
362
|
clearTimeout(this.restartTimer);
|
|
343
|
-
this.
|
|
363
|
+
this.moveTo("stopped");
|
|
344
364
|
this.rejectPending(new Error("workspace_io_unavailable: stopped"));
|
|
345
365
|
try {
|
|
346
366
|
this.child?.kill("SIGKILL");
|
package/home-sync-lib.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { mkdir, readdir, rm, stat } from "node:fs/promises";
|
|
2
2
|
import { join, relative } from "node:path";
|
|
3
|
+
import { type HomeSnapshotState, homeSnapshotMachine } from "./lib/machines";
|
|
3
4
|
|
|
4
5
|
export const DEFAULT_LIVE_HOME = "/tmp/.dench-home";
|
|
5
6
|
export const DEFAULT_SNAPSHOT_DIR = "/workspace/.dench/home/snapshots";
|
|
@@ -183,3 +184,133 @@ export async function pruneHomeSnapshots(args: {
|
|
|
183
184
|
await Promise.all(stale.map((path) => rm(path, { force: true })));
|
|
184
185
|
return stale;
|
|
185
186
|
}
|
|
187
|
+
|
|
188
|
+
export type HomeSnapshotStatus = { pending: boolean; inFlight: boolean };
|
|
189
|
+
|
|
190
|
+
export type HomeSnapshotSchedulerOptions = {
|
|
191
|
+
debounceMs: number;
|
|
192
|
+
/** Takes one snapshot and records its own errors. */
|
|
193
|
+
snapshot: (reason: string) => Promise<void>;
|
|
194
|
+
/** Called after every state change (the daemon writes its status file). */
|
|
195
|
+
onChange?: (status: HomeSnapshotStatus) => void;
|
|
196
|
+
setTimer?: (callback: () => void, ms: number) => unknown;
|
|
197
|
+
clearTimer?: (timer: unknown) => void;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* One home snapshot at a time, debounced, moved only through
|
|
202
|
+
* `homeSnapshotMachine`. Replaces the daemon's `pending` / `inFlight` /
|
|
203
|
+
* `pendingTimer` fields and its separately written status copies.
|
|
204
|
+
*/
|
|
205
|
+
export class HomeSnapshotScheduler {
|
|
206
|
+
private state: HomeSnapshotState = "idle";
|
|
207
|
+
private timer: unknown = null;
|
|
208
|
+
private running: Promise<void> | null = null;
|
|
209
|
+
private stopping: Promise<void> | null = null;
|
|
210
|
+
|
|
211
|
+
constructor(private readonly options: HomeSnapshotSchedulerOptions) {}
|
|
212
|
+
|
|
213
|
+
get current(): HomeSnapshotState {
|
|
214
|
+
return this.state;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
status(): HomeSnapshotStatus {
|
|
218
|
+
return {
|
|
219
|
+
pending: this.state === "pending" || this.state === "in_flight_dirty",
|
|
220
|
+
inFlight:
|
|
221
|
+
this.state === "in_flight" ||
|
|
222
|
+
this.state === "in_flight_dirty" ||
|
|
223
|
+
this.running !== null,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The watcher saw a change under the live home. */
|
|
228
|
+
changed(reason: string): void {
|
|
229
|
+
if (this.state === "pending") {
|
|
230
|
+
// Explicit same-state path: a later change restarts the debounce.
|
|
231
|
+
this.arm(reason);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (this.state === "idle") {
|
|
235
|
+
if (this.move("pending")) this.arm(reason);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (this.state === "in_flight") this.move("in_flight_dirty");
|
|
239
|
+
// in_flight_dirty already owes a follow-up; stopping/stopped ignore it.
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Take one snapshot right away (`--once`). */
|
|
243
|
+
async runNow(reason: string): Promise<void> {
|
|
244
|
+
if (!this.move("in_flight")) return;
|
|
245
|
+
this.clearTimer();
|
|
246
|
+
await this.run(reason);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Wait for the running snapshot, take a final one if the tree changed
|
|
251
|
+
* since the last snapshot started, then stop for good. Idempotent.
|
|
252
|
+
*/
|
|
253
|
+
shutdown(): Promise<void> {
|
|
254
|
+
if (this.stopping) return this.stopping;
|
|
255
|
+
const from = this.state;
|
|
256
|
+
this.stopping = (async () => {
|
|
257
|
+
this.clearTimer();
|
|
258
|
+
if (!this.move("stopping")) return;
|
|
259
|
+
if (this.running) await this.running;
|
|
260
|
+
if (from === "pending" || from === "in_flight_dirty") {
|
|
261
|
+
await this.track(this.options.snapshot("shutdown"));
|
|
262
|
+
}
|
|
263
|
+
this.move("stopped");
|
|
264
|
+
})();
|
|
265
|
+
return this.stopping;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
private move(to: HomeSnapshotState): boolean {
|
|
269
|
+
if (homeSnapshotMachine.decide(this.state, to).kind !== "apply") {
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
272
|
+
this.state = to;
|
|
273
|
+
this.options.onChange?.(this.status());
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
private arm(reason: string): void {
|
|
278
|
+
this.clearTimer();
|
|
279
|
+
this.timer = (this.options.setTimer ?? setTimeout)(() => {
|
|
280
|
+
this.timer = null;
|
|
281
|
+
if (this.move("in_flight")) void this.run(reason);
|
|
282
|
+
}, this.options.debounceMs);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private clearTimer(): void {
|
|
286
|
+
if (this.timer === null) return;
|
|
287
|
+
(
|
|
288
|
+
this.options.clearTimer ??
|
|
289
|
+
((timer) => clearTimeout(timer as ReturnType<typeof setTimeout>))
|
|
290
|
+
)(this.timer);
|
|
291
|
+
this.timer = null;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private async track(snapshot: Promise<void>): Promise<void> {
|
|
295
|
+
const running = snapshot.catch(() => undefined);
|
|
296
|
+
this.running = running;
|
|
297
|
+
this.options.onChange?.(this.status());
|
|
298
|
+
try {
|
|
299
|
+
await running;
|
|
300
|
+
} finally {
|
|
301
|
+
this.running = null;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private async run(reason: string): Promise<void> {
|
|
306
|
+
await this.track(this.options.snapshot(reason));
|
|
307
|
+
if (this.state === "in_flight") {
|
|
308
|
+
this.move("idle");
|
|
309
|
+
} else if (this.state === "in_flight_dirty") {
|
|
310
|
+
if (this.move("pending")) this.arm(`queued:${reason}`);
|
|
311
|
+
} else {
|
|
312
|
+
// `stopping`: shutdown() is waiting for this snapshot.
|
|
313
|
+
this.options.onChange?.(this.status());
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
package/home-sync.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
buildSnapshotName,
|
|
19
19
|
buildTarCreateArgs,
|
|
20
20
|
ensureHomeSyncDirs,
|
|
21
|
+
HomeSnapshotScheduler,
|
|
21
22
|
type HomeSyncArgs,
|
|
22
23
|
parseHomeSyncArgs,
|
|
23
24
|
pruneHomeSnapshots,
|
|
@@ -80,11 +81,20 @@ async function writeStatus(
|
|
|
80
81
|
await writeFile(path, `${JSON.stringify(status, null, 2)}\n`);
|
|
81
82
|
}
|
|
82
83
|
|
|
84
|
+
function isAlreadyExists(error: unknown): boolean {
|
|
85
|
+
return (
|
|
86
|
+
typeof error === "object" &&
|
|
87
|
+
error !== null &&
|
|
88
|
+
(error as NodeJS.ErrnoException).code === "EEXIST"
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
83
92
|
class HomeSyncDaemon {
|
|
84
|
-
private pendingTimer: NodeJS.Timeout | null = null;
|
|
85
|
-
private pending = false;
|
|
86
|
-
private inFlight = false;
|
|
87
93
|
private status: HomeSyncStatus;
|
|
94
|
+
/** Snapshot lifecycle (`homeSnapshotMachine` in lib/machines.ts). */
|
|
95
|
+
private readonly scheduler: HomeSnapshotScheduler;
|
|
96
|
+
/** Status writes go out one at a time so the file is never interleaved. */
|
|
97
|
+
private statusWrites: Promise<void> = Promise.resolve();
|
|
88
98
|
|
|
89
99
|
constructor(private readonly args: HomeSyncArgs) {
|
|
90
100
|
this.status = {
|
|
@@ -97,6 +107,23 @@ class HomeSyncDaemon {
|
|
|
97
107
|
pending: false,
|
|
98
108
|
inFlight: false,
|
|
99
109
|
};
|
|
110
|
+
this.scheduler = new HomeSnapshotScheduler({
|
|
111
|
+
debounceMs: args.debounceMs,
|
|
112
|
+
snapshot: (reason) => this.takeSnapshot(reason),
|
|
113
|
+
onChange: ({ pending, inFlight }) => {
|
|
114
|
+
this.status.pending = pending;
|
|
115
|
+
this.status.inFlight = inFlight;
|
|
116
|
+
void this.flushStatus();
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private flushStatus(): Promise<void> {
|
|
122
|
+
const snapshot = { ...this.status };
|
|
123
|
+
this.statusWrites = this.statusWrites
|
|
124
|
+
.then(() => writeStatus(this.args.statusPath, snapshot))
|
|
125
|
+
.catch(() => undefined);
|
|
126
|
+
return this.statusWrites;
|
|
100
127
|
}
|
|
101
128
|
|
|
102
129
|
async start(): Promise<void> {
|
|
@@ -104,7 +131,8 @@ class HomeSyncDaemon {
|
|
|
104
131
|
await writeStatus(this.args.statusPath, this.status);
|
|
105
132
|
|
|
106
133
|
if (this.args.once) {
|
|
107
|
-
await this.
|
|
134
|
+
await this.scheduler.runNow("once");
|
|
135
|
+
await this.statusWrites;
|
|
108
136
|
return;
|
|
109
137
|
}
|
|
110
138
|
|
|
@@ -141,7 +169,7 @@ class HomeSyncDaemon {
|
|
|
141
169
|
watcher.on("error", (error) => {
|
|
142
170
|
console.error(`[dench-home-sync] watcher error: ${String(error)}`);
|
|
143
171
|
this.status.lastError = String(error);
|
|
144
|
-
void
|
|
172
|
+
void this.flushStatus();
|
|
145
173
|
});
|
|
146
174
|
|
|
147
175
|
process.on("SIGTERM", () => {
|
|
@@ -157,40 +185,27 @@ class HomeSyncDaemon {
|
|
|
157
185
|
}
|
|
158
186
|
|
|
159
187
|
private scheduleSnapshot(reason: string): void {
|
|
160
|
-
this.
|
|
161
|
-
this.status.pending = true;
|
|
162
|
-
void writeStatus(this.args.statusPath, this.status);
|
|
163
|
-
|
|
164
|
-
if (this.pendingTimer) clearTimeout(this.pendingTimer);
|
|
165
|
-
this.pendingTimer = setTimeout(() => {
|
|
166
|
-
this.pendingTimer = null;
|
|
167
|
-
void this.snapshotNow(reason);
|
|
168
|
-
}, this.args.debounceMs);
|
|
188
|
+
this.scheduler.changed(reason);
|
|
169
189
|
}
|
|
170
190
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
this.scheduleSnapshot(`queued:${reason}`);
|
|
174
|
-
return;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
this.pending = false;
|
|
178
|
-
this.inFlight = true;
|
|
179
|
-
this.status.pending = false;
|
|
180
|
-
this.status.inFlight = true;
|
|
181
|
-
await writeStatus(this.args.statusPath, this.status);
|
|
182
|
-
|
|
183
|
-
const tempDir = await mkdtemp(join(tmpdir(), "dench-home-sync-"));
|
|
184
|
-
const archivePath = join(tempDir, "home.tar");
|
|
191
|
+
/** One snapshot. Never throws: the scheduler only sequences them. */
|
|
192
|
+
private async takeSnapshot(reason: string): Promise<void> {
|
|
185
193
|
const snapshotName = buildSnapshotName(new Date());
|
|
186
194
|
const durablePath = join(this.args.snapshotDir, snapshotName);
|
|
195
|
+
let tempDir: string | undefined;
|
|
196
|
+
let copyStarted = false;
|
|
197
|
+
let copied = false;
|
|
187
198
|
|
|
188
199
|
try {
|
|
200
|
+
tempDir = await mkdtemp(join(tmpdir(), "dench-home-sync-"));
|
|
201
|
+
const archivePath = join(tempDir, "home.tar");
|
|
189
202
|
await runCommand(
|
|
190
203
|
"tar",
|
|
191
204
|
buildTarCreateArgs({ liveHome: this.args.liveHome, archivePath }),
|
|
192
205
|
);
|
|
206
|
+
copyStarted = true;
|
|
193
207
|
await copyBytesOnly(archivePath, durablePath);
|
|
208
|
+
copied = true;
|
|
194
209
|
await pruneHomeSnapshots({
|
|
195
210
|
snapshotDir: this.args.snapshotDir,
|
|
196
211
|
keepSnapshots: this.args.keepSnapshots,
|
|
@@ -202,28 +217,32 @@ class HomeSyncDaemon {
|
|
|
202
217
|
`[dench-home-sync] snapshotted home (${reason}) -> ${durablePath}`,
|
|
203
218
|
);
|
|
204
219
|
} catch (error) {
|
|
220
|
+
if (copyStarted && !copied && !isAlreadyExists(error)) {
|
|
221
|
+
// A partial archive under a final name would be the newest snapshot,
|
|
222
|
+
// which is the one a new sandbox restores. (The durable volume has no
|
|
223
|
+
// rename, so the copy cannot go to a temporary name first.)
|
|
224
|
+
await rm(durablePath, { force: true }).catch(() => undefined);
|
|
225
|
+
}
|
|
205
226
|
this.status.lastError =
|
|
206
227
|
error instanceof Error ? error.message : String(error);
|
|
207
228
|
console.error(
|
|
208
229
|
`[dench-home-sync] snapshot failed: ${this.status.lastError}`,
|
|
209
230
|
);
|
|
210
231
|
} finally {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
232
|
+
if (tempDir) {
|
|
233
|
+
await rm(tempDir, { recursive: true, force: true }).catch(
|
|
234
|
+
() => undefined,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
216
237
|
}
|
|
217
238
|
}
|
|
218
239
|
|
|
219
240
|
private async shutdown(exitCode: number): Promise<void> {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
await this.snapshotNow("shutdown");
|
|
226
|
-
}
|
|
241
|
+
// Waits for a running snapshot instead of exiting mid-copy. Before, a
|
|
242
|
+
// shutdown during a snapshot only re-armed the debounce timer and exited,
|
|
243
|
+
// leaving a truncated newest snapshot behind.
|
|
244
|
+
await this.scheduler.shutdown();
|
|
245
|
+
await this.flushStatus();
|
|
227
246
|
process.exit(exitCode);
|
|
228
247
|
}
|
|
229
248
|
}
|
package/lib/machines.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process state machines of the CLI daemons, written down once.
|
|
3
|
+
*
|
|
4
|
+
* The CLI is published to npm from `cli/` alone, so it cannot import
|
|
5
|
+
* `convex/lib/stateMachine.ts`; `./state-machine.ts` is a byte-identical copy
|
|
6
|
+
* (cli/__tests__/vendored-state-machine.test.ts fails when it drifts).
|
|
7
|
+
* Inventory and history: docs/agent-notes/state-machines/gateway-workflows.md
|
|
8
|
+
* and docs/agent-notes/state-machines/batch-5.md.
|
|
9
|
+
*/
|
|
10
|
+
import { defineMachine } from "./state-machine";
|
|
11
|
+
|
|
12
|
+
// ── fs-daemon mounted-workspace worker (fs-daemon-workspace.ts) ─────────────
|
|
13
|
+
|
|
14
|
+
export type WorkspaceWorkerState =
|
|
15
|
+
| "starting"
|
|
16
|
+
| "ready"
|
|
17
|
+
| "stalled"
|
|
18
|
+
| "backoff"
|
|
19
|
+
| "stopped";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The child process that does all mounted-workspace I/O.
|
|
23
|
+
*
|
|
24
|
+
* - `stalled` leaves only through the OS-confirmed exit of the child
|
|
25
|
+
* (`→ backoff`) or shutdown. By design: SIGKILL is not proof of exit for a
|
|
26
|
+
* process stuck in an uninterruptible (D-state) FUSE syscall, and a
|
|
27
|
+
* replacement would get stuck on the same mount. A stalled worker makes the
|
|
28
|
+
* daemon unhealthy (`isDaemonHealthy` requires `ready`), so recovery is the
|
|
29
|
+
* supervisor's restart of the daemon or sandbox.
|
|
30
|
+
* - Readiness is this state alone. Before, a separate `ready` boolean was not
|
|
31
|
+
* reset by a stall.
|
|
32
|
+
* - `stopped` is terminal.
|
|
33
|
+
*/
|
|
34
|
+
export const workspaceWorkerMachine = defineMachine<WorkspaceWorkerState>(
|
|
35
|
+
"fs-daemon workspace worker",
|
|
36
|
+
{
|
|
37
|
+
starting: ["ready", "stalled", "backoff", "stopped"],
|
|
38
|
+
ready: ["stalled", "backoff", "stopped"],
|
|
39
|
+
stalled: ["backoff", "stopped"],
|
|
40
|
+
backoff: ["starting", "stopped"],
|
|
41
|
+
stopped: [],
|
|
42
|
+
},
|
|
43
|
+
{ initial: ["starting"] },
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
// ── home-sync snapshots (home-sync-lib.ts HomeSnapshotScheduler) ────────────
|
|
47
|
+
|
|
48
|
+
export type HomeSnapshotState =
|
|
49
|
+
| "idle"
|
|
50
|
+
| "pending"
|
|
51
|
+
| "in_flight"
|
|
52
|
+
| "in_flight_dirty"
|
|
53
|
+
| "stopping"
|
|
54
|
+
| "stopped";
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The home overlay snapshotter: one tar snapshot at a time, debounced.
|
|
58
|
+
*
|
|
59
|
+
* - `in_flight_dirty`: the tree changed while a snapshot was running, so
|
|
60
|
+
* another one follows it (`→ pending`, debounced) instead of a second
|
|
61
|
+
* snapshot racing the first.
|
|
62
|
+
* - `stopping` waits for the running snapshot and then takes one final
|
|
63
|
+
* snapshot if the tree changed since the last one started. Before, shutdown
|
|
64
|
+
* during a snapshot only re-armed the debounce timer and exited mid-copy,
|
|
65
|
+
* leaving a truncated archive as the newest snapshot, which is the one a new
|
|
66
|
+
* sandbox restores.
|
|
67
|
+
* - `stopped` is terminal: no change is scheduled after shutdown.
|
|
68
|
+
*/
|
|
69
|
+
export const homeSnapshotMachine = defineMachine<HomeSnapshotState>(
|
|
70
|
+
"home sync snapshot",
|
|
71
|
+
{
|
|
72
|
+
idle: ["pending", "in_flight", "stopping"],
|
|
73
|
+
pending: ["in_flight", "stopping"],
|
|
74
|
+
in_flight: ["idle", "in_flight_dirty", "stopping"],
|
|
75
|
+
in_flight_dirty: ["pending", "stopping"],
|
|
76
|
+
stopping: ["stopped"],
|
|
77
|
+
stopped: [],
|
|
78
|
+
},
|
|
79
|
+
{ initial: ["idle"] },
|
|
80
|
+
);
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Explicit state machines.
|
|
3
|
+
*
|
|
4
|
+
* A status/state/phase field that many writers move by hand is an implicit
|
|
5
|
+
* state machine: nothing says which moves are legal, so a late webhook, a
|
|
6
|
+
* retry or a sweeper can resurrect a terminal row (canceled → starting,
|
|
7
|
+
* stopped → active, lost → won). Nov 2026 inventory and history:
|
|
8
|
+
* docs/agent-notes/state-machines.md.
|
|
9
|
+
*
|
|
10
|
+
* `defineMachine` writes the legal moves down once. Writers ask the machine
|
|
11
|
+
* before they write (`decide`); `stateMachineDb.ts` does that inside the
|
|
12
|
+
* mutation that patches the row, so the check and the write are one
|
|
13
|
+
* transaction.
|
|
14
|
+
*
|
|
15
|
+
* Pure module: no Convex imports, so the Next app, the gateway and React
|
|
16
|
+
* reducers can share the same tables.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type TransitionTable<S extends string> = {
|
|
20
|
+
readonly [K in S]: readonly S[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** What a writer should do with a requested move. */
|
|
24
|
+
export type TransitionDecision<S extends string> =
|
|
25
|
+
/** Legal move to a different state: write it. */
|
|
26
|
+
| { kind: "apply"; from: S | undefined; to: S }
|
|
27
|
+
/** Already in the target state. The caller decides whether the rest of its
|
|
28
|
+
* patch still applies (for a terminal state it usually must not). */
|
|
29
|
+
| { kind: "same"; from: S; to: S }
|
|
30
|
+
/** Not a legal move from the current state. */
|
|
31
|
+
| { kind: "illegal"; from: S | undefined; to: S }
|
|
32
|
+
/** The caller said which states it expected to move from and the row is
|
|
33
|
+
* elsewhere (compare-and-set miss). */
|
|
34
|
+
| { kind: "unexpected"; from: S | undefined; to: S; expected: readonly S[] };
|
|
35
|
+
|
|
36
|
+
export class IllegalTransitionError extends Error {
|
|
37
|
+
readonly machine: string;
|
|
38
|
+
readonly from: string | undefined;
|
|
39
|
+
readonly to: string;
|
|
40
|
+
readonly reason: "illegal" | "unexpected";
|
|
41
|
+
constructor(
|
|
42
|
+
machine: string,
|
|
43
|
+
from: string | undefined,
|
|
44
|
+
to: string,
|
|
45
|
+
reason: "illegal" | "unexpected",
|
|
46
|
+
) {
|
|
47
|
+
super(
|
|
48
|
+
`${machine}: ${reason === "illegal" ? "illegal transition" : "unexpected state"} ${from ?? "(unset)"} → ${to}`,
|
|
49
|
+
);
|
|
50
|
+
this.name = "IllegalTransitionError";
|
|
51
|
+
this.machine = machine;
|
|
52
|
+
this.from = from;
|
|
53
|
+
this.to = to;
|
|
54
|
+
this.reason = reason;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type ExpectOption<S extends string> = { expect?: S | readonly S[] };
|
|
59
|
+
|
|
60
|
+
export interface Machine<S extends string> {
|
|
61
|
+
readonly name: string;
|
|
62
|
+
readonly states: readonly S[];
|
|
63
|
+
/** States with no outgoing moves. */
|
|
64
|
+
readonly terminal: readonly S[];
|
|
65
|
+
/** States a new row may start in. */
|
|
66
|
+
readonly initial: readonly S[];
|
|
67
|
+
readonly transitions: TransitionTable<S>;
|
|
68
|
+
isState(value: unknown): value is S;
|
|
69
|
+
isTerminal(state: S | undefined): boolean;
|
|
70
|
+
/** `from === undefined` is a row with no value yet (insert, or a legacy row
|
|
71
|
+
* written before the field existed): `initial` and `legacyFrom` states are
|
|
72
|
+
* allowed. */
|
|
73
|
+
can(from: S | undefined, to: S): boolean;
|
|
74
|
+
decide(
|
|
75
|
+
from: S | undefined,
|
|
76
|
+
to: S,
|
|
77
|
+
options?: ExpectOption<S>,
|
|
78
|
+
): TransitionDecision<S>;
|
|
79
|
+
/** Throws IllegalTransitionError unless the decision is `apply` or `same`. */
|
|
80
|
+
assert(from: S | undefined, to: S, options?: ExpectOption<S>): void;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function defineMachine<const S extends string>(
|
|
84
|
+
name: string,
|
|
85
|
+
transitions: TransitionTable<S>,
|
|
86
|
+
options: {
|
|
87
|
+
/** Defaults to every state. */
|
|
88
|
+
initial?: readonly S[];
|
|
89
|
+
/** Extra states reachable from an unset field (legacy rows). */
|
|
90
|
+
legacyFrom?: readonly S[];
|
|
91
|
+
} = {},
|
|
92
|
+
): Machine<S> {
|
|
93
|
+
const states = Object.keys(transitions) as S[];
|
|
94
|
+
const known = new Set<string>(states);
|
|
95
|
+
for (const from of states) {
|
|
96
|
+
for (const to of transitions[from]) {
|
|
97
|
+
if (!known.has(to)) {
|
|
98
|
+
throw new Error(`${name}: ${from} → ${to} targets an unknown state`);
|
|
99
|
+
}
|
|
100
|
+
if (to === from) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
`${name}: ${from} → ${from} is implicit ("same"); do not list it`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const initial = options.initial ?? states;
|
|
108
|
+
for (const s of [...initial, ...(options.legacyFrom ?? [])]) {
|
|
109
|
+
if (!known.has(s)) throw new Error(`${name}: unknown initial state ${s}`);
|
|
110
|
+
}
|
|
111
|
+
const fromUnset = new Set<string>([
|
|
112
|
+
...initial,
|
|
113
|
+
...(options.legacyFrom ?? []),
|
|
114
|
+
]);
|
|
115
|
+
const terminal = states.filter((s) => transitions[s].length === 0);
|
|
116
|
+
const edges = new Map<string, Set<string>>(
|
|
117
|
+
states.map((s) => [s, new Set<string>(transitions[s])]),
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
const can = (from: S | undefined, to: S): boolean =>
|
|
121
|
+
from === undefined
|
|
122
|
+
? fromUnset.has(to)
|
|
123
|
+
: (edges.get(from)?.has(to) ?? false);
|
|
124
|
+
|
|
125
|
+
const decide = (
|
|
126
|
+
from: S | undefined,
|
|
127
|
+
to: S,
|
|
128
|
+
opts?: ExpectOption<S>,
|
|
129
|
+
): TransitionDecision<S> => {
|
|
130
|
+
if (from !== undefined && from === to) return { kind: "same", from, to };
|
|
131
|
+
if (opts?.expect !== undefined) {
|
|
132
|
+
const expected: readonly S[] =
|
|
133
|
+
typeof opts.expect === "string"
|
|
134
|
+
? [opts.expect as S]
|
|
135
|
+
: (opts.expect as readonly S[]);
|
|
136
|
+
if (from === undefined || !expected.includes(from)) {
|
|
137
|
+
return { kind: "unexpected", from, to, expected };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return can(from, to)
|
|
141
|
+
? { kind: "apply", from, to }
|
|
142
|
+
: { kind: "illegal", from, to };
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
name,
|
|
147
|
+
states,
|
|
148
|
+
terminal,
|
|
149
|
+
initial,
|
|
150
|
+
transitions,
|
|
151
|
+
isState: (value: unknown): value is S =>
|
|
152
|
+
typeof value === "string" && known.has(value),
|
|
153
|
+
isTerminal: (state) => state !== undefined && terminal.includes(state),
|
|
154
|
+
can,
|
|
155
|
+
decide,
|
|
156
|
+
assert(from, to, opts) {
|
|
157
|
+
const d = decide(from, to, opts);
|
|
158
|
+
if (d.kind === "illegal" || d.kind === "unexpected") {
|
|
159
|
+
throw new IllegalTransitionError(name, from, to, d.kind);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Every state reachable from `from` in one or more moves. */
|
|
166
|
+
export function reachableFrom<S extends string>(
|
|
167
|
+
machine: Machine<S>,
|
|
168
|
+
from: S,
|
|
169
|
+
): Set<S> {
|
|
170
|
+
const seen = new Set<S>();
|
|
171
|
+
const stack: S[] = [...machine.transitions[from]];
|
|
172
|
+
while (stack.length > 0) {
|
|
173
|
+
const s = stack.pop() as S;
|
|
174
|
+
if (seen.has(s)) continue;
|
|
175
|
+
seen.add(s);
|
|
176
|
+
stack.push(...machine.transitions[s]);
|
|
177
|
+
}
|
|
178
|
+
return seen;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* React-side helper: a reducer that only accepts legal moves. Illegal moves
|
|
183
|
+
* keep the current state (and report through `onIllegal`, default
|
|
184
|
+
* console.warn in development) instead of producing an impossible UI mode.
|
|
185
|
+
*/
|
|
186
|
+
export function machineReducer<S extends string>(
|
|
187
|
+
machine: Machine<S>,
|
|
188
|
+
onIllegal: (from: S, to: S) => void = (from, to) => {
|
|
189
|
+
if (
|
|
190
|
+
typeof process !== "undefined" &&
|
|
191
|
+
process.env?.NODE_ENV !== "production"
|
|
192
|
+
) {
|
|
193
|
+
console.warn(
|
|
194
|
+
`${machine.name}: ignored illegal transition ${from} → ${to}`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
) {
|
|
199
|
+
return (state: S, to: S): S => {
|
|
200
|
+
const d = machine.decide(state, to);
|
|
201
|
+
if (d.kind === "apply") return to;
|
|
202
|
+
if (d.kind !== "same") onIllegal(state, to);
|
|
203
|
+
return state;
|
|
204
|
+
};
|
|
205
|
+
}
|