cursedbelt 2.6.0 → 2.7.0
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/dist/server/sync/alarm.d.ts +35 -0
- package/dist/server/sync/alarm.d.ts.map +1 -0
- package/dist/server/sync/alarm.js +92 -0
- package/dist/server/sync/alarm.js.map +1 -0
- package/dist/server/sync/commands.d.ts +88 -0
- package/dist/server/sync/commands.d.ts.map +1 -0
- package/dist/server/sync/commands.js +242 -0
- package/dist/server/sync/commands.js.map +1 -0
- package/dist/server/sync/engine.d.ts +63 -0
- package/dist/server/sync/engine.d.ts.map +1 -0
- package/dist/server/sync/engine.js +185 -0
- package/dist/server/sync/engine.js.map +1 -0
- package/dist/server/sync/http.d.ts +107 -0
- package/dist/server/sync/http.d.ts.map +1 -0
- package/dist/server/sync/http.js +244 -0
- package/dist/server/sync/http.js.map +1 -0
- package/dist/server/sync/index.d.ts +42 -0
- package/dist/server/sync/index.d.ts.map +1 -0
- package/dist/server/sync/index.js +42 -0
- package/dist/server/sync/index.js.map +1 -0
- package/dist/server/sync/opLog.d.ts +62 -0
- package/dist/server/sync/opLog.d.ts.map +1 -0
- package/dist/server/sync/opLog.js +97 -0
- package/dist/server/sync/opLog.js.map +1 -0
- package/dist/server/sync/planner.d.ts +32 -0
- package/dist/server/sync/planner.d.ts.map +1 -0
- package/dist/server/sync/planner.js +31 -0
- package/dist/server/sync/planner.js.map +1 -0
- package/dist/server/sync/status.d.ts +64 -0
- package/dist/server/sync/status.d.ts.map +1 -0
- package/dist/server/sync/status.js +50 -0
- package/dist/server/sync/status.js.map +1 -0
- package/dist/server/sync/timer.d.ts +53 -0
- package/dist/server/sync/timer.d.ts.map +1 -0
- package/dist/server/sync/timer.js +171 -0
- package/dist/server/sync/timer.js.map +1 -0
- package/dist/server/sync/tokens.d.ts +26 -0
- package/dist/server/sync/tokens.d.ts.map +1 -0
- package/dist/server/sync/tokens.js +52 -0
- package/dist/server/sync/tokens.js.map +1 -0
- package/dist/server/sync/types.d.ts +102 -0
- package/dist/server/sync/types.d.ts.map +1 -0
- package/dist/server/sync/types.js +30 -0
- package/dist/server/sync/types.js.map +1 -0
- package/package.json +19 -7
- package/src/leafSubpathsImportNothing.spec.ts +59 -3
- package/src/server/sync/alarm.spec.ts +149 -0
- package/src/server/sync/alarm.ts +137 -0
- package/src/server/sync/commands.spec.ts +145 -0
- package/src/server/sync/commands.ts +361 -0
- package/src/server/sync/engine.spec.ts +496 -0
- package/src/server/sync/engine.ts +255 -0
- package/src/server/sync/http.ts +316 -0
- package/src/server/sync/httpRemote.spec.ts +158 -0
- package/src/server/sync/index.ts +90 -0
- package/src/server/sync/opLog.spec.ts +110 -0
- package/src/server/sync/opLog.ts +189 -0
- package/src/server/sync/planner.spec.ts +53 -0
- package/src/server/sync/planner.ts +62 -0
- package/src/server/sync/status.spec.ts +92 -0
- package/src/server/sync/status.ts +108 -0
- package/src/server/sync/timer.spec.ts +150 -0
- package/src/server/sync/timer.ts +207 -0
- package/src/server/sync/tokens.spec.ts +38 -0
- package/src/server/sync/tokens.ts +94 -0
- package/src/server/sync/types.ts +108 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { Database } from "bun:sqlite";
|
|
3
|
+
import { Hono } from "hono";
|
|
4
|
+
import {
|
|
5
|
+
createCommandQueue,
|
|
6
|
+
createCommandReceiver,
|
|
7
|
+
createCommandRemote,
|
|
8
|
+
startCommandWorker,
|
|
9
|
+
type SyncCommand,
|
|
10
|
+
} from "./commands";
|
|
11
|
+
|
|
12
|
+
const queue = () => createCommandQueue(new Database(":memory:"));
|
|
13
|
+
|
|
14
|
+
describe("command queue", () => {
|
|
15
|
+
test("enqueue → claim → complete lifecycle", () => {
|
|
16
|
+
const q = queue();
|
|
17
|
+
const cmd = q.enqueue("app.start", { key: "notes" }, "prod-ui");
|
|
18
|
+
expect(cmd.status).toBe("queued");
|
|
19
|
+
expect(q.pendingCount()).toBe(1);
|
|
20
|
+
const claimed = q.claimNext("mac");
|
|
21
|
+
expect(claimed?.uid).toBe(cmd.uid);
|
|
22
|
+
expect(claimed?.status).toBe("claimed");
|
|
23
|
+
// Nothing else to claim while it is held.
|
|
24
|
+
expect(q.claimNext("other")).toBeNull();
|
|
25
|
+
expect(q.complete(cmd.uid, { started: true })).toBe(true);
|
|
26
|
+
expect(q.get(cmd.uid)?.status).toBe("done");
|
|
27
|
+
expect(q.pendingCount()).toBe(0);
|
|
28
|
+
// Completing twice is refused — the row already finished.
|
|
29
|
+
expect(q.complete(cmd.uid, {})).toBe(false);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("claims are ordered oldest-first and atomic across workers", () => {
|
|
33
|
+
const q = queue();
|
|
34
|
+
const first = q.enqueue("a", null, "ui");
|
|
35
|
+
const second = q.enqueue("b", null, "ui");
|
|
36
|
+
expect(q.claimNext("w1")?.uid).toBe(first.uid);
|
|
37
|
+
expect(q.claimNext("w2")?.uid).toBe(second.uid);
|
|
38
|
+
expect(q.claimNext("w3")).toBeNull();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("a stale claim is reclaimable (a dead worker cannot strand the queue)", async () => {
|
|
42
|
+
const q = queue();
|
|
43
|
+
q.enqueue("a", null, "ui");
|
|
44
|
+
expect(q.claimNext("w1", 60_000)).not.toBeNull();
|
|
45
|
+
// Let the claim age past a 1ms stale window, then reclaim it.
|
|
46
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
47
|
+
expect(q.claimNext("w2", 1)?.claimedBy).toBe("w2");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("fail records the error", () => {
|
|
51
|
+
const q = queue();
|
|
52
|
+
const cmd = q.enqueue("a", null, "ui");
|
|
53
|
+
q.claimNext("w");
|
|
54
|
+
expect(q.fail(cmd.uid, "boom")).toBe(true);
|
|
55
|
+
const row = q.get(cmd.uid);
|
|
56
|
+
expect(row?.status).toBe("failed");
|
|
57
|
+
expect(row?.error).toBe("boom");
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe("command receiver + remote + worker", () => {
|
|
62
|
+
function mount(q: ReturnType<typeof createCommandQueue>) {
|
|
63
|
+
const app = new Hono();
|
|
64
|
+
app.route(
|
|
65
|
+
"/api/relay",
|
|
66
|
+
createCommandReceiver({
|
|
67
|
+
queue: q,
|
|
68
|
+
verifyToken: (t) => t === "tok",
|
|
69
|
+
maxHoldMs: 300,
|
|
70
|
+
pollStepMs: 20,
|
|
71
|
+
}),
|
|
72
|
+
);
|
|
73
|
+
const remote = createCommandRemote({
|
|
74
|
+
basePath: "http://peer/api/relay",
|
|
75
|
+
token: "tok",
|
|
76
|
+
fetchImpl: ((input: RequestInfo | URL, init?: RequestInit) =>
|
|
77
|
+
app.request(input as string, init)) as typeof fetch,
|
|
78
|
+
});
|
|
79
|
+
return { app, remote };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
test("held poll returns a queued command immediately, null after the hold", async () => {
|
|
83
|
+
const q = queue();
|
|
84
|
+
const { remote } = mount(q);
|
|
85
|
+
const empty = await remote.poll("mac", 50);
|
|
86
|
+
expect(empty).toBeNull();
|
|
87
|
+
q.enqueue("repo.sync", null, "ui");
|
|
88
|
+
const got = await remote.poll("mac", 50);
|
|
89
|
+
expect(got?.kind).toBe("repo.sync");
|
|
90
|
+
await remote.report(got?.uid ?? "", { ok: true, result: { healed: 3 } });
|
|
91
|
+
expect(q.get(got?.uid ?? "")?.status).toBe("done");
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("a command enqueued DURING the hold is delivered within it", async () => {
|
|
95
|
+
const q = queue();
|
|
96
|
+
const { remote } = mount(q);
|
|
97
|
+
const pending = remote.poll("mac", 250);
|
|
98
|
+
setTimeout(() => q.enqueue("late", null, "ui"), 40);
|
|
99
|
+
const got = await pending;
|
|
100
|
+
expect(got?.kind).toBe("late");
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("the gate refuses a wrong token uniformly", async () => {
|
|
104
|
+
const q = queue();
|
|
105
|
+
const app = new Hono();
|
|
106
|
+
app.route("/api/relay", createCommandReceiver({ queue: q, verifyToken: (t) => t === "tok" }));
|
|
107
|
+
const res = await app.request("http://peer/api/relay/pending?wait=0", {
|
|
108
|
+
headers: { authorization: "Bearer wrong" },
|
|
109
|
+
});
|
|
110
|
+
expect(res.status).toBe(401);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("the worker loop polls, executes, reports, and keeps cycling", async () => {
|
|
114
|
+
const q = queue();
|
|
115
|
+
const { remote } = mount(q);
|
|
116
|
+
const executed: string[] = [];
|
|
117
|
+
const worker = startCommandWorker({
|
|
118
|
+
resolveRemote: () => remote,
|
|
119
|
+
execute: async (command: SyncCommand) => {
|
|
120
|
+
executed.push(command.kind);
|
|
121
|
+
if (command.kind === "explode") throw new Error("kaboom");
|
|
122
|
+
return { ok: true };
|
|
123
|
+
},
|
|
124
|
+
holdMs: 60,
|
|
125
|
+
idleGapMs: 5,
|
|
126
|
+
log: () => {},
|
|
127
|
+
warn: () => {},
|
|
128
|
+
});
|
|
129
|
+
q.enqueue("good", null, "ui");
|
|
130
|
+
q.enqueue("explode", null, "ui");
|
|
131
|
+
const deadline = Date.now() + 3_000;
|
|
132
|
+
while (Date.now() < deadline) {
|
|
133
|
+
const rows = q.list();
|
|
134
|
+
if (rows.length === 2 && rows.every((r) => r.status === "done" || r.status === "failed"))
|
|
135
|
+
break;
|
|
136
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
137
|
+
}
|
|
138
|
+
worker.stop();
|
|
139
|
+
expect(executed.sort()).toEqual(["explode", "good"]);
|
|
140
|
+
const byKind = new Map(q.list().map((r) => [r.kind, r]));
|
|
141
|
+
expect(byKind.get("good")?.status).toBe("done");
|
|
142
|
+
expect(byKind.get("explode")?.status).toBe("failed");
|
|
143
|
+
expect(byKind.get("explode")?.error).toContain("kaboom");
|
|
144
|
+
});
|
|
145
|
+
});
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The command relay — notes' ask-responder shape generalized: the internet-facing
|
|
3
|
+
* instance PARKS an action it cannot perform (it has no Mac powers), and the Mac's
|
|
4
|
+
* resident worker long-polls for it, executes locally, and posts the outcome back.
|
|
5
|
+
* The Mac dials OUT; the receiving instance never reaches into the house.
|
|
6
|
+
*
|
|
7
|
+
* Delivery is a held GET (default hold 25s) — remember the two fleet traps: the
|
|
8
|
+
* host server needs `idleTimeoutSeconds` ABOVE the hold (Bun's 10s default closed
|
|
9
|
+
* notes' 25s poll and nginx reported a bogus 502), and the routes must be mounted
|
|
10
|
+
* BEFORE any browser-session gate.
|
|
11
|
+
*
|
|
12
|
+
* A command left `claimed` past the stale window is reclaimable — a worker that
|
|
13
|
+
* died mid-execution must not strand the queue. Executors must therefore be
|
|
14
|
+
* idempotent or cheap to re-run.
|
|
15
|
+
*/
|
|
16
|
+
import type { Database } from "bun:sqlite";
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { Hono } from "hono";
|
|
19
|
+
|
|
20
|
+
export type CommandStatus = "queued" | "claimed" | "done" | "failed";
|
|
21
|
+
|
|
22
|
+
export interface SyncCommand {
|
|
23
|
+
uid: string;
|
|
24
|
+
kind: string;
|
|
25
|
+
args: unknown;
|
|
26
|
+
status: CommandStatus;
|
|
27
|
+
requestedBy: string;
|
|
28
|
+
createdAt: number;
|
|
29
|
+
claimedAt: number | null;
|
|
30
|
+
claimedBy: string | null;
|
|
31
|
+
finishedAt: number | null;
|
|
32
|
+
result: unknown;
|
|
33
|
+
error: string | null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const STALE_CLAIM_MS = 5 * 60_000;
|
|
37
|
+
|
|
38
|
+
export interface CommandQueue {
|
|
39
|
+
enqueue(kind: string, args: unknown, requestedBy: string): SyncCommand;
|
|
40
|
+
/** Atomically claim the oldest queued (or stale-claimed) command. */
|
|
41
|
+
claimNext(claimedBy: string, staleMs?: number): SyncCommand | null;
|
|
42
|
+
complete(uid: string, result: unknown): boolean;
|
|
43
|
+
fail(uid: string, error: string): boolean;
|
|
44
|
+
get(uid: string): SyncCommand | null;
|
|
45
|
+
list(limit?: number): SyncCommand[];
|
|
46
|
+
pendingCount(): number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface Row {
|
|
50
|
+
uid: string;
|
|
51
|
+
kind: string;
|
|
52
|
+
args: string;
|
|
53
|
+
status: CommandStatus;
|
|
54
|
+
requested_by: string;
|
|
55
|
+
created_at: number;
|
|
56
|
+
claimed_at: number | null;
|
|
57
|
+
claimed_by: string | null;
|
|
58
|
+
finished_at: number | null;
|
|
59
|
+
result: string | null;
|
|
60
|
+
error: string | null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const toCommand = (r: Row): SyncCommand => ({
|
|
64
|
+
uid: r.uid,
|
|
65
|
+
kind: r.kind,
|
|
66
|
+
args: JSON.parse(r.args) as unknown,
|
|
67
|
+
status: r.status,
|
|
68
|
+
requestedBy: r.requested_by,
|
|
69
|
+
createdAt: r.created_at,
|
|
70
|
+
claimedAt: r.claimed_at,
|
|
71
|
+
claimedBy: r.claimed_by,
|
|
72
|
+
finishedAt: r.finished_at,
|
|
73
|
+
result: r.result === null ? null : (JSON.parse(r.result) as unknown),
|
|
74
|
+
error: r.error,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
export function createCommandQueue(db: Database): CommandQueue {
|
|
78
|
+
db.exec(`
|
|
79
|
+
CREATE TABLE IF NOT EXISTS sync_commands (
|
|
80
|
+
uid TEXT PRIMARY KEY,
|
|
81
|
+
kind TEXT NOT NULL,
|
|
82
|
+
args TEXT NOT NULL,
|
|
83
|
+
status TEXT NOT NULL DEFAULT 'queued',
|
|
84
|
+
requested_by TEXT NOT NULL,
|
|
85
|
+
created_at INTEGER NOT NULL,
|
|
86
|
+
claimed_at INTEGER,
|
|
87
|
+
claimed_by TEXT,
|
|
88
|
+
finished_at INTEGER,
|
|
89
|
+
result TEXT,
|
|
90
|
+
error TEXT
|
|
91
|
+
);
|
|
92
|
+
CREATE INDEX IF NOT EXISTS idx_sync_commands_status ON sync_commands(status, created_at);
|
|
93
|
+
`);
|
|
94
|
+
const insert = db.prepare(
|
|
95
|
+
"INSERT INTO sync_commands (uid, kind, args, status, requested_by, created_at) VALUES (?, ?, ?, 'queued', ?, ?)",
|
|
96
|
+
);
|
|
97
|
+
const getStmt = db.prepare("SELECT * FROM sync_commands WHERE uid = ?");
|
|
98
|
+
const listStmt = db.prepare("SELECT * FROM sync_commands ORDER BY created_at DESC LIMIT ?");
|
|
99
|
+
const pendingStmt = db.prepare(
|
|
100
|
+
"SELECT COUNT(*) AS n FROM sync_commands WHERE status IN ('queued','claimed')",
|
|
101
|
+
);
|
|
102
|
+
// The atomic claim: one UPDATE whose WHERE picks the oldest eligible row. sqlite
|
|
103
|
+
// serializes writers, so two workers can never claim the same row.
|
|
104
|
+
const claimStmt = db.prepare(`
|
|
105
|
+
UPDATE sync_commands SET status = 'claimed', claimed_at = ?, claimed_by = ?
|
|
106
|
+
WHERE uid = (
|
|
107
|
+
SELECT uid FROM sync_commands
|
|
108
|
+
WHERE status = 'queued' OR (status = 'claimed' AND claimed_at < ?)
|
|
109
|
+
ORDER BY created_at ASC LIMIT 1
|
|
110
|
+
)
|
|
111
|
+
RETURNING *
|
|
112
|
+
`);
|
|
113
|
+
const finishStmt = db.prepare(
|
|
114
|
+
"UPDATE sync_commands SET status = ?, finished_at = ?, result = ?, error = ? WHERE uid = ? AND status IN ('queued','claimed')",
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
enqueue(kind, args, requestedBy) {
|
|
119
|
+
const uid = `cmd-${randomUUID().slice(0, 18)}`;
|
|
120
|
+
insert.run(uid, kind, JSON.stringify(args ?? null), requestedBy, Date.now());
|
|
121
|
+
return toCommand(getStmt.get(uid) as Row);
|
|
122
|
+
},
|
|
123
|
+
claimNext(claimedBy, staleMs = STALE_CLAIM_MS) {
|
|
124
|
+
const now = Date.now();
|
|
125
|
+
const row = claimStmt.get(now, claimedBy, now - staleMs) as Row | null;
|
|
126
|
+
return row ? toCommand(row) : null;
|
|
127
|
+
},
|
|
128
|
+
complete: (uid, result) =>
|
|
129
|
+
finishStmt.run("done", Date.now(), JSON.stringify(result ?? null), null, uid).changes > 0,
|
|
130
|
+
fail: (uid, error) => finishStmt.run("failed", Date.now(), null, error, uid).changes > 0,
|
|
131
|
+
get: (uid) => {
|
|
132
|
+
const row = getStmt.get(uid) as Row | null;
|
|
133
|
+
return row ? toCommand(row) : null;
|
|
134
|
+
},
|
|
135
|
+
list: (limit = 100) => (listStmt.all(limit) as Row[]).map(toCommand),
|
|
136
|
+
pendingCount: () => (pendingStmt.get() as { n: number }).n,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ── the receiver routes (mount beside the sync receiver, same token gate) ────────
|
|
141
|
+
|
|
142
|
+
const noStore = { "cache-control": "no-store" } as const;
|
|
143
|
+
export const DEFAULT_HOLD_MS = 25_000;
|
|
144
|
+
|
|
145
|
+
export interface CommandRoutesOptions {
|
|
146
|
+
queue: CommandQueue;
|
|
147
|
+
verifyToken: (presented: string) => boolean;
|
|
148
|
+
/** Cap on the held poll. The HOST SERVER's idleTimeout must exceed this. */
|
|
149
|
+
maxHoldMs?: number;
|
|
150
|
+
pollStepMs?: number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** GET /pending (held) + POST /pending/:uid — the worker's two verbs. */
|
|
154
|
+
export function createCommandReceiver(options: CommandRoutesOptions): Hono {
|
|
155
|
+
const maxHold = options.maxHoldMs ?? DEFAULT_HOLD_MS;
|
|
156
|
+
const step = options.pollStepMs ?? 1_000;
|
|
157
|
+
const api = new Hono();
|
|
158
|
+
api.use("*", async (c, next) => {
|
|
159
|
+
const header = c.req.header("authorization") ?? "";
|
|
160
|
+
const presented = header.startsWith("Bearer ") ? header.slice(7) : "";
|
|
161
|
+
if (presented.length === 0 || !options.verifyToken(presented)) {
|
|
162
|
+
return c.json({ error: "unauthorized" }, 401, noStore);
|
|
163
|
+
}
|
|
164
|
+
await next();
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
api.get("/pending", async (c) => {
|
|
168
|
+
const worker = c.req.query("worker") ?? "worker";
|
|
169
|
+
const waitRaw = c.req.query("wait");
|
|
170
|
+
const wait = Math.min(
|
|
171
|
+
maxHold,
|
|
172
|
+
waitRaw !== undefined && /^\d+$/.test(waitRaw) ? Number(waitRaw) : maxHold,
|
|
173
|
+
);
|
|
174
|
+
const deadline = Date.now() + wait;
|
|
175
|
+
for (;;) {
|
|
176
|
+
const command = options.queue.claimNext(worker);
|
|
177
|
+
if (command) return c.json({ command }, 200, noStore);
|
|
178
|
+
if (Date.now() >= deadline) return c.json({ command: null }, 200, noStore);
|
|
179
|
+
await new Promise((resolve) =>
|
|
180
|
+
setTimeout(resolve, Math.min(step, Math.max(1, deadline - Date.now()))),
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
api.post("/pending/:uid", async (c) => {
|
|
186
|
+
const uid = c.req.param("uid");
|
|
187
|
+
let body: unknown;
|
|
188
|
+
try {
|
|
189
|
+
body = await c.req.json();
|
|
190
|
+
} catch {
|
|
191
|
+
return c.json({ error: "bad_request" }, 400, noStore);
|
|
192
|
+
}
|
|
193
|
+
const { ok, result, error } = (body ?? {}) as {
|
|
194
|
+
ok?: unknown;
|
|
195
|
+
result?: unknown;
|
|
196
|
+
error?: unknown;
|
|
197
|
+
};
|
|
198
|
+
if (typeof ok !== "boolean") return c.json({ error: "bad_request" }, 400, noStore);
|
|
199
|
+
const changed = ok
|
|
200
|
+
? options.queue.complete(uid, result ?? null)
|
|
201
|
+
: options.queue.fail(uid, typeof error === "string" ? error : "failed");
|
|
202
|
+
if (!changed) return c.json({ error: "not_found" }, 404, noStore);
|
|
203
|
+
return c.json({ ok: true }, 200, noStore);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
return api;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ── the dialing worker (runs on the Mac, inside the resident daemon) ─────────────
|
|
210
|
+
|
|
211
|
+
export interface CommandRemote {
|
|
212
|
+
poll(worker: string, waitMs: number): Promise<SyncCommand | null>;
|
|
213
|
+
report(uid: string, outcome: { ok: boolean; result?: unknown; error?: string }): Promise<void>;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function createCommandRemote(options: {
|
|
217
|
+
basePath: string;
|
|
218
|
+
token: string;
|
|
219
|
+
fetchImpl?: typeof fetch;
|
|
220
|
+
/** Host-scoped extras for this peer — see `createHttpRemote`'s note. */
|
|
221
|
+
extraHeaders?: Record<string, string>;
|
|
222
|
+
}): CommandRemote {
|
|
223
|
+
const base = options.basePath.replace(/\/$/, "");
|
|
224
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
225
|
+
const headers = (extra?: Record<string, string>) => ({
|
|
226
|
+
authorization: `Bearer ${options.token}`,
|
|
227
|
+
...(options.extraHeaders ?? {}),
|
|
228
|
+
...(extra ?? {}),
|
|
229
|
+
});
|
|
230
|
+
/** 🔴 `redirect: "manual"`, for the reason in `http.ts`'s header: the relay
|
|
231
|
+
* travels the same road as the sync, so a moved peer hostname must fail here
|
|
232
|
+
* with the destination in the message rather than silently landing on a
|
|
233
|
+
* Cloudflare Access login page and reporting a JSON parse error. */
|
|
234
|
+
const refuseRedirect = (r: Response, path: string): void => {
|
|
235
|
+
if (r.status >= 300 && r.status < 400)
|
|
236
|
+
throw new Error(
|
|
237
|
+
`${path}: ${r.status} — the peer address redirects to ` +
|
|
238
|
+
`${r.headers.get("location") ?? "an unnamed destination"}; the relay URL points at a host that has moved.`,
|
|
239
|
+
);
|
|
240
|
+
};
|
|
241
|
+
return {
|
|
242
|
+
async poll(worker, waitMs) {
|
|
243
|
+
const r = await doFetch(
|
|
244
|
+
`${base}/pending?worker=${encodeURIComponent(worker)}&wait=${waitMs}`,
|
|
245
|
+
{
|
|
246
|
+
headers: headers(),
|
|
247
|
+
redirect: "manual",
|
|
248
|
+
// The abort budget must clear the hold plus network slack.
|
|
249
|
+
signal: AbortSignal.timeout(waitMs + 15_000),
|
|
250
|
+
},
|
|
251
|
+
);
|
|
252
|
+
refuseRedirect(r, "commands/pending");
|
|
253
|
+
if (!r.ok) throw new Error(`commands/pending: ${r.status}`);
|
|
254
|
+
const body = (await r.json()) as { command: SyncCommand | null };
|
|
255
|
+
return body.command;
|
|
256
|
+
},
|
|
257
|
+
async report(uid, outcome) {
|
|
258
|
+
const r = await doFetch(`${base}/pending/${encodeURIComponent(uid)}`, {
|
|
259
|
+
method: "POST",
|
|
260
|
+
headers: headers({ "content-type": "application/json" }),
|
|
261
|
+
redirect: "manual",
|
|
262
|
+
body: JSON.stringify(outcome),
|
|
263
|
+
signal: AbortSignal.timeout(30_000),
|
|
264
|
+
});
|
|
265
|
+
refuseRedirect(r, "commands/report");
|
|
266
|
+
if (!r.ok) throw new Error(`commands/report: ${r.status}`);
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export interface CommandWorkerDeps {
|
|
272
|
+
/** Re-read every cycle, like the sync timer's peer — null = not linked. */
|
|
273
|
+
resolveRemote: () => CommandRemote | null;
|
|
274
|
+
execute: (command: SyncCommand) => Promise<unknown>;
|
|
275
|
+
worker?: string;
|
|
276
|
+
holdMs?: number;
|
|
277
|
+
/** Idle gap between an empty poll and the next (on top of the hold). */
|
|
278
|
+
idleGapMs?: number;
|
|
279
|
+
backoffMaxMs?: number;
|
|
280
|
+
log?: (msg: string) => void;
|
|
281
|
+
warn?: (msg: string) => void;
|
|
282
|
+
setTimer?: (fn: () => void, ms: number) => unknown;
|
|
283
|
+
clearTimer?: (handle: unknown) => void;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export interface CommandWorkerHandle {
|
|
287
|
+
stop(): void;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The resident long-poll → execute → report loop. Unreachable remote backs off to
|
|
291
|
+
* `backoffMaxMs` and recovers silently — the nightly window rule. */
|
|
292
|
+
export function startCommandWorker(deps: CommandWorkerDeps): CommandWorkerHandle {
|
|
293
|
+
const worker = deps.worker ?? "mac";
|
|
294
|
+
const holdMs = deps.holdMs ?? DEFAULT_HOLD_MS;
|
|
295
|
+
const idleGapMs = deps.idleGapMs ?? 1_000;
|
|
296
|
+
const backoffMax = deps.backoffMaxMs ?? 10 * 60_000;
|
|
297
|
+
const log = deps.log ?? ((m: string) => console.log(m));
|
|
298
|
+
const warn = deps.warn ?? ((m: string) => console.error(m));
|
|
299
|
+
const setTimer = deps.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
|
300
|
+
const clearTimer = deps.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>));
|
|
301
|
+
|
|
302
|
+
let stopped = false;
|
|
303
|
+
let handle: unknown = null;
|
|
304
|
+
let failures = 0;
|
|
305
|
+
let reportedUnreachable = false;
|
|
306
|
+
|
|
307
|
+
const schedule = (ms: number): void => {
|
|
308
|
+
if (stopped) return;
|
|
309
|
+
if (handle !== null) clearTimer(handle);
|
|
310
|
+
handle = setTimer(cycle, ms);
|
|
311
|
+
(handle as { unref?: () => void })?.unref?.();
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
const cycle = (): void => {
|
|
315
|
+
if (stopped) return;
|
|
316
|
+
const remote = deps.resolveRemote();
|
|
317
|
+
if (remote === null) {
|
|
318
|
+
schedule(60_000);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
void remote
|
|
322
|
+
.poll(worker, holdMs)
|
|
323
|
+
.then(async (command) => {
|
|
324
|
+
failures = 0;
|
|
325
|
+
reportedUnreachable = false;
|
|
326
|
+
if (command === null) return;
|
|
327
|
+
log(`[commands] executing ${command.kind} (${command.uid})`);
|
|
328
|
+
try {
|
|
329
|
+
const result = await deps.execute(command);
|
|
330
|
+
await remote.report(command.uid, { ok: true, result });
|
|
331
|
+
} catch (err) {
|
|
332
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
333
|
+
warn(`[commands] ${command.kind} failed: ${message}`);
|
|
334
|
+
// Best-effort: a failed report leaves the row claimed; the stale-claim
|
|
335
|
+
// window re-serves it, which is why executors must tolerate a re-run.
|
|
336
|
+
await remote.report(command.uid, { ok: false, error: message }).catch(() => {});
|
|
337
|
+
}
|
|
338
|
+
})
|
|
339
|
+
.then(() => {
|
|
340
|
+
if (!stopped) schedule(idleGapMs);
|
|
341
|
+
})
|
|
342
|
+
.catch((err) => {
|
|
343
|
+
failures += 1;
|
|
344
|
+
const wait = Math.min(backoffMax, 5_000 * 2 ** Math.min(failures - 1, 7));
|
|
345
|
+
if (!reportedUnreachable) {
|
|
346
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
347
|
+
log(`[commands] remote unreachable (${message}) — backing off. This is normal offline.`);
|
|
348
|
+
reportedUnreachable = true;
|
|
349
|
+
}
|
|
350
|
+
schedule(wait);
|
|
351
|
+
});
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
schedule(1_000);
|
|
355
|
+
return {
|
|
356
|
+
stop: () => {
|
|
357
|
+
stopped = true;
|
|
358
|
+
if (handle !== null) clearTimer(handle);
|
|
359
|
+
},
|
|
360
|
+
};
|
|
361
|
+
}
|