cursedbelt-server 4.48.1 → 4.50.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.
@@ -168,7 +168,10 @@ export interface PullD1Options {
168
168
  export declare const TRANSIENT_WAITS_MS: readonly number[];
169
169
  /**
170
170
  * A failure of the WIRE between this Mac and Cloudflare, not an answer from D1 — which asking
171
- * again a little later fixes. Only these are waited out — a refusal D1 actually made (a page too
171
+ * again a little later fixes. `setTypeOfService EINVAL` is one in disguise: undici sets the socket's
172
+ * TOS before every request, and macOS answers `setsockopt` on a connection the peer already reset
173
+ * with EINVAL — so under Bun a dropped connection crashes wrangler with it instead of ECONNRESET
174
+ * (vault's and auth's nightly pulls, 2026-10-23, both under the background clamp's starved handshakes). Only these are waited out — a refusal D1 actually made (a page too
172
175
  * large, bad SQL, auth) is never retried here, so a page refused for its size still halves at
173
176
  * once instead of sleeping ~1.5 minutes per halving.
174
177
  */
@@ -196,11 +196,14 @@ export function backupTables(rows) {
196
196
  export const TRANSIENT_WAITS_MS = [5_000, 20_000, 60_000];
197
197
  /**
198
198
  * A failure of the WIRE between this Mac and Cloudflare, not an answer from D1 — which asking
199
- * again a little later fixes. Only these are waited out — a refusal D1 actually made (a page too
199
+ * again a little later fixes. `setTypeOfService EINVAL` is one in disguise: undici sets the socket's
200
+ * TOS before every request, and macOS answers `setsockopt` on a connection the peer already reset
201
+ * with EINVAL — so under Bun a dropped connection crashes wrangler with it instead of ECONNRESET
202
+ * (vault's and auth's nightly pulls, 2026-10-23, both under the background clamp's starved handshakes). Only these are waited out — a refusal D1 actually made (a page too
200
203
  * large, bad SQL, auth) is never retried here, so a page refused for its size still halves at
201
204
  * once instead of sleeping ~1.5 minutes per halving.
202
205
  */
203
- export const isTransient = (message) => /fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up|network connection was lost/i.test(message);
206
+ export const isTransient = (message) => /fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up|network connection was lost|setTypeOfService EINVAL/i.test(message);
204
207
  const sqlIdent = (name) => `"${name.replaceAll('"', '""')}"`;
205
208
  const sqlText = (text) => `'${text.replaceAll("'", "''")}'`;
206
209
  /**
@@ -11,3 +11,4 @@
11
11
  */
12
12
  export { describeSweep, isJunkName, isStable, pruneEmptyDirs, scanDropzone, sweepDropzone, type DropHandler, type DropOutcome, type DroppedFile, type ScanOptions, type SweepReport, } from "./scan.js";
13
13
  export { askBinaryServerAboutDuplicate, hashFile, type DuplicateVerdict, type DuplicateQuestion, } from "./duplicates.js";
14
+ export { createIngestReporter, FILES_JOURNAL, type FileOutcome, type IngestReporter, type ReportFile, type SourceDrive, } from "./report.js";
@@ -11,3 +11,4 @@
11
11
  */
12
12
  export { describeSweep, isJunkName, isStable, pruneEmptyDirs, scanDropzone, sweepDropzone, } from "./scan.js";
13
13
  export { askBinaryServerAboutDuplicate, hashFile, } from "./duplicates.js";
14
+ export { createIngestReporter, FILES_JOURNAL, } from "./report.js";
@@ -0,0 +1,188 @@
1
+ export declare const PROGRESS_VERSION = 1;
2
+ export declare const PROGRESS_FILE = "progress.json";
3
+ export declare const FILES_JOURNAL = "files.jsonl";
4
+ export declare const QUEUE_FILE = "queue.jsonl";
5
+ /** The page polls every few seconds; the file need not be fresher than that. */
6
+ export declare const WRITE_EVERY_MS = 2000;
7
+ export declare const JOURNAL_ROTATE_BYTES: number;
8
+ /** A finished source stays listed this long, so "what finished today" is on the page. */
9
+ export declare const FINISHED_KEPT_MS: number;
10
+ /** The name of the source that holds an account's loose files. */
11
+ export declare const LOOSE_FILES = "Loose files";
12
+ /** Where a file is on its way through the sweep. Outcomes leave the queue. */
13
+ /** `copying`: still being written into the dropzone — it goes in on a later sweep. `skipped`: left alone. */
14
+ export type FileState = "queued" | "copying" | "uploading" | "waiting-room" | "waiting-drive" | "skipped" | "failed";
15
+ export type FileOutcome = "added" | "duplicate" | "parked" | "blocked" | "failed";
16
+ export interface Tally {
17
+ files: number;
18
+ bytes: number;
19
+ }
20
+ export interface SourceDrive {
21
+ volume: string;
22
+ /** `ok` mounted · `unmounted` the volume is not there (unplugged) · `deleted` mounted, folder gone. */
23
+ state: "ok" | "unmounted" | "deleted";
24
+ /** The volume is a disk image: where its file lives, and whether THAT drive is plugged in. */
25
+ image?: {
26
+ file: string;
27
+ hostVolume: string | null;
28
+ hostMounted: boolean;
29
+ reattachTried: boolean;
30
+ };
31
+ }
32
+ /** What the reporter needs of a file: whose it is, where it is, and how big. */
33
+ export interface ReportFile {
34
+ accountId: string;
35
+ /** Absolute path — with the account, what tells two files apart. */
36
+ path: string;
37
+ /** Relative to the account folder: its first segment names the source. */
38
+ relativePath: string;
39
+ size: number;
40
+ }
41
+ /** A file's outcome, as the journal records it. */
42
+ export type ReportResult = {
43
+ outcome: FileOutcome;
44
+ detail?: string;
45
+ itemId?: string;
46
+ };
47
+ /** What an earlier run already settled for a file — `found`'s `settled` answers it. */
48
+ export interface SettledFile {
49
+ outcome?: Exclude<FileOutcome, "failed"> | null;
50
+ at: string;
51
+ itemId?: string | null;
52
+ }
53
+ export interface ProgressSource {
54
+ id: string;
55
+ account: {
56
+ id: string;
57
+ label: string;
58
+ };
59
+ /** The folder or link's own name, or {@link LOOSE_FILES}. */
60
+ label: string;
61
+ kind: "linked" | "folder" | "loose";
62
+ /** Where it is in the dropzone. */
63
+ path: string;
64
+ /** A link's real target. */
65
+ target?: string;
66
+ drive?: SourceDrive;
67
+ startedAt: string;
68
+ /** When nothing was left to do — cleared if more arrives. */
69
+ finishedAt: string | null;
70
+ /** When the last file reached an outcome. */
71
+ lastOutcomeAt: string | null;
72
+ /** Everything it holds: what is left, plus (for a folder that empties as it goes) what was filed. */
73
+ total: Tally;
74
+ done: Tally;
75
+ added: number;
76
+ duplicate: number;
77
+ blocked: number;
78
+ parked: number;
79
+ queued: Tally;
80
+ waitingForRoom: Tally;
81
+ waitingForDrive: Tally;
82
+ skipped: Tally;
83
+ failed: Tally;
84
+ current: {
85
+ path: string;
86
+ bytes: number;
87
+ key: string;
88
+ startedAt: string;
89
+ } | null;
90
+ }
91
+ export interface IngestProgress {
92
+ v: typeof PROGRESS_VERSION;
93
+ app: string;
94
+ /** The launchd job that runs the sweep — station reads its health and can start it. */
95
+ job: string;
96
+ everySeconds: number;
97
+ dropzone: string;
98
+ updatedAt: string;
99
+ sweep: {
100
+ pid: number;
101
+ startedAt: string;
102
+ finishedAt: string | null;
103
+ state: "running" | "finished" | "failed";
104
+ phase: "starting" | "walking" | "filing" | "done";
105
+ error?: string;
106
+ };
107
+ /** The app's accounts — what the `uid` on its web uploads names (`/api/upload/session`). */
108
+ accounts: {
109
+ id: string;
110
+ label: string;
111
+ }[];
112
+ /**
113
+ * The store's free space against the floor the sweep keeps, and what recently filed files'
114
+ * derivatives still hold back of it, until when — collections' linked pacing; `null` for a sweep
115
+ * that does not wait for room.
116
+ */
117
+ room: ReportRoom | null;
118
+ sources: ProgressSource[];
119
+ }
120
+ export interface ReportRoom {
121
+ freeBytes: number | null;
122
+ floorBytes: number;
123
+ spaceFactor: number;
124
+ owedBytes?: number;
125
+ owedUntil?: string | null;
126
+ }
127
+ export interface FileLine {
128
+ at: string;
129
+ source: string;
130
+ account: string;
131
+ /** Relative to the account folder. */
132
+ path: string;
133
+ bytes: number;
134
+ outcome: FileOutcome;
135
+ detail?: string;
136
+ itemId?: string;
137
+ /** From `found`'s `settled`, the first time the journal was started — not seen happening. */
138
+ backfilled?: true;
139
+ }
140
+ export interface QueueLine {
141
+ source: string;
142
+ path: string;
143
+ bytes: number;
144
+ state: FileState;
145
+ }
146
+ /** The source a file belongs to: its account plus the first segment of its path, or the loose files. */
147
+ export declare function sourceIdOf(accountId: string, relativePath: string): {
148
+ id: string;
149
+ label: string;
150
+ top: string | null;
151
+ };
152
+ export interface ReporterOptions {
153
+ /** `$FORGE_STATE/state/<app>-ingest` — station finds the report by that name. */
154
+ stateDir: string;
155
+ app: string;
156
+ /** The launchd job that runs the sweep. */
157
+ job: string;
158
+ everySeconds: number;
159
+ dropzone: string;
160
+ /** Each account folder. A one-owner dropzone is one account whose `dir` is the dropzone itself. */
161
+ accounts: readonly {
162
+ id: string;
163
+ label: string;
164
+ dir: string;
165
+ }[];
166
+ /** A linked source's drive: its volume, whether it is plugged in, and for a disk image the drive its file is on. */
167
+ driveOf?: (target: string) => SourceDrive | undefined;
168
+ room?: () => ReportRoom | null;
169
+ now?: () => number;
170
+ warn?: (line: string) => void;
171
+ pid?: number;
172
+ }
173
+ /**
174
+ * One sweep's reporter. `ingest.ts` makes it before the walk and hands its hooks to `sweepFiles`.
175
+ */
176
+ export declare function createIngestReporter<F extends ReportFile = ReportFile>(o: ReporterOptions): {
177
+ walking: () => void;
178
+ unreachable: (accountId: string, relativePath: string, target: string) => void;
179
+ found: (files: readonly F[], settled?: ((file: F) => SettledFile | undefined) | undefined) => void;
180
+ progress: {
181
+ waiting: (file: F, why: "done" | "room" | "copying" | "skipped" | "drive") => void;
182
+ uploading: (file: F, key: string) => void;
183
+ };
184
+ result: (file: F, result: ReportResult) => void;
185
+ finish: (error?: string | undefined) => void;
186
+ };
187
+ export type IngestReporter<F extends ReportFile = ReportFile> = ReturnType<typeof createIngestReporter<F>>;
188
+ export declare function readProgress(path: string): IngestProgress | null;
@@ -0,0 +1,430 @@
1
+ /**
2
+ * What a dropzone sweep is doing, written down for station's Uploads page (forge task 3588; family's and music's sweeps since its follow-up).
3
+ *
4
+ * > *"I need station or binaries to show me in progress info about ingestions such as dropzone work
5
+ * > … status, size, file counts, time started/ended, duration, estimated completion time … If there
6
+ * > are file lists they should be paginated in cases where there are huge upload sets like I have
7
+ * > ongoing from databundle volume right now. If there's an issue or something needs to be plugged in
8
+ * > or set back up it should make it clear to me."* — the owner, 2026-10-22
9
+ *
10
+ * The sweep is the only thing that knows what "waiting for room" or "the drive is not plugged in"
11
+ * means for a file, so it says so here rather than leaving a reader to re-derive it from the log.
12
+ * Three files in the sweep's own state folder (`$FORGE_STATE/state/<app>-ingest/`) — station lists
13
+ * every app that writes them, with no list of apps:
14
+ *
15
+ * · **`progress.json`** — the sweep (running or how it ended) and every SOURCE: each top-level
16
+ * folder or link in an account folder is one (a linked drive folder, a dropped `Vacation 2024/`),
17
+ * and loose files at an account's root are one more. Per source: what it holds, what is done, what
18
+ * waits for room or for its drive, what failed, the file going in now (with the binary-server key
19
+ * its parts stage under, so station can show that file's own progress), and its drive. Rewritten
20
+ * whole (temp + rename) at most every {@link WRITE_EVERY_MS}, and always at a sweep's end.
21
+ * · **`files.jsonl`** — one line per file that reached an outcome (added, duplicate, parked,
22
+ * blocked, failed), appended as it happens: the paginated "done" list and the throughput curve.
23
+ * The first time, a caller's `settled` answer backfills what an earlier run already filed.
24
+ * Moved aside to `files.1.jsonl` past {@link JOURNAL_ROTATE_BYTES}.
25
+ * · **`queue.jsonl`** — every file found this sweep that has NOT reached an outcome, with its state;
26
+ * rewritten whole when the walk is done and at the end. The paginated "still to go" list.
27
+ *
28
+ * 🔴 Only the sweep writes them, and only a reader reads them: nothing here decides anything about a
29
+ * file. A write that fails is logged once and costs the page its freshness, never the sweep its run —
30
+ * every hook is guarded. `UPLOADS_CONTRACT` in station's `src/uploads.ts` is the reader's copy of the
31
+ * shape; `v` changes when a field changes meaning.
32
+ *
33
+ * `sweepDropzone` drives one by itself (its `report` option); a sweep of its own (collections') calls
34
+ * the hooks where it decides.
35
+ */
36
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, statSync, writeFileSync } from "node:fs";
37
+ import { basename, dirname, join, resolve } from "node:path";
38
+ export const PROGRESS_VERSION = 1;
39
+ export const PROGRESS_FILE = "progress.json";
40
+ export const FILES_JOURNAL = "files.jsonl";
41
+ export const QUEUE_FILE = "queue.jsonl";
42
+ /** The page polls every few seconds; the file need not be fresher than that. */
43
+ export const WRITE_EVERY_MS = 2_000;
44
+ export const JOURNAL_ROTATE_BYTES = 64 * 1024 ** 2;
45
+ /** A finished source stays listed this long, so "what finished today" is on the page. */
46
+ export const FINISHED_KEPT_MS = 7 * 24 * 60 * 60 * 1000;
47
+ /** The name of the source that holds an account's loose files. */
48
+ export const LOOSE_FILES = "Loose files";
49
+ const zero = () => ({ files: 0, bytes: 0 });
50
+ const add = (t, bytes) => {
51
+ t.files++;
52
+ t.bytes += bytes;
53
+ };
54
+ /** The source a file belongs to: its account plus the first segment of its path, or the loose files. */
55
+ export function sourceIdOf(accountId, relativePath) {
56
+ const slash = relativePath.indexOf("/");
57
+ if (slash < 0)
58
+ return { id: `${accountId}:`, label: LOOSE_FILES, top: null };
59
+ const top = relativePath.slice(0, slash);
60
+ return { id: `${accountId}:${top}`, label: top, top };
61
+ }
62
+ /**
63
+ * One sweep's reporter. `ingest.ts` makes it before the walk and hands its hooks to `sweepFiles`.
64
+ */
65
+ export function createIngestReporter(o) {
66
+ const now = o.now ?? Date.now;
67
+ const iso = () => new Date(now()).toISOString();
68
+ const progressPath = join(o.stateDir, PROGRESS_FILE);
69
+ const journalPath = join(o.stateDir, FILES_JOURNAL);
70
+ const queuePath = join(o.stateDir, QUEUE_FILE);
71
+ let warned = false;
72
+ const safely = (what, fn) => {
73
+ try {
74
+ fn();
75
+ }
76
+ catch (cause) {
77
+ if (!warned)
78
+ (o.warn ?? console.warn)(` ? could not write the ${what} station reads (${cause instanceof Error ? cause.message : String(cause)}); the sweep carries on`);
79
+ warned = true;
80
+ }
81
+ };
82
+ const previous = readProgress(progressPath);
83
+ const prevSources = new Map((previous?.sources ?? []).map((s) => [s.id, s]));
84
+ const accountLabel = new Map(o.accounts.map((a) => [a.id, a.label]));
85
+ const startedAt = iso();
86
+ const sweep = { pid: o.pid ?? process.pid, startedAt, finishedAt: null, state: "running", phase: "starting" };
87
+ const tracked = new Map();
88
+ const outcomes = new Map();
89
+ const current = new Map();
90
+ /** Sources this sweep could not walk at all: their link's drive is not there. */
91
+ const unreachable = new Map();
92
+ /** The oldest settled date of each source's files — when a linked run really began. */
93
+ const firstSettled = new Map();
94
+ /** …and the newest — when a linked run last filed anything, before this sweep. */
95
+ const lastSettled = new Map();
96
+ let walked = false;
97
+ let lastWrite = 0;
98
+ const keyOf = (file) => `${file.accountId}\0${file.path}`;
99
+ const outcomeOf = (source) => {
100
+ let o2 = outcomes.get(source);
101
+ if (!o2) {
102
+ o2 = { added: 0, duplicate: 0, blocked: 0, parked: 0, failed: zero(), done: zero(), last: null };
103
+ outcomes.set(source, o2);
104
+ }
105
+ return o2;
106
+ };
107
+ /** Each account folder's top-level links: name → real target. */
108
+ const links = new Map();
109
+ for (const account of o.accounts) {
110
+ let names = [];
111
+ try {
112
+ names = readdirSync(account.dir);
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ for (const name of names) {
118
+ const full = join(account.dir, name);
119
+ try {
120
+ links.set(`${account.id}:${name}`, resolve(dirname(full), readlinkSync(full)));
121
+ }
122
+ catch {
123
+ /* not a link */
124
+ }
125
+ }
126
+ }
127
+ const driveOf = (target) => {
128
+ try {
129
+ return o.driveOf?.(target);
130
+ }
131
+ catch {
132
+ return undefined;
133
+ }
134
+ };
135
+ function sources() {
136
+ const out = new Map();
137
+ const base = (id, accountId, label, top) => {
138
+ const prev = prevSources.get(id);
139
+ const target = top ? links.get(`${accountId}:${top}`) : undefined;
140
+ const account = o.accounts.find((a) => a.id === accountId);
141
+ const drive = target ? driveOf(target) : undefined;
142
+ return {
143
+ id,
144
+ account: { id: accountId, label: accountLabel.get(accountId) ?? accountId },
145
+ label,
146
+ kind: target ? "linked" : top ? "folder" : "loose",
147
+ path: account ? (top ? join(account.dir, top) : account.dir) : (prev?.path ?? ""),
148
+ ...(target ? { target, ...(drive ? { drive } : {}) } : {}),
149
+ startedAt: prev && (prev.finishedAt === null || target) ? prev.startedAt : (firstSettled.get(id) ?? startedAt),
150
+ finishedAt: null,
151
+ lastOutcomeAt: prev?.lastOutcomeAt ?? lastSettled.get(id) ?? null,
152
+ total: zero(),
153
+ done: zero(),
154
+ added: 0,
155
+ duplicate: 0,
156
+ blocked: 0,
157
+ parked: 0,
158
+ queued: zero(),
159
+ waitingForRoom: zero(),
160
+ waitingForDrive: zero(),
161
+ skipped: zero(),
162
+ failed: zero(),
163
+ current: null,
164
+ };
165
+ };
166
+ for (const t of tracked.values()) {
167
+ let s = out.get(t.source);
168
+ if (!s) {
169
+ const { label, top } = sourceIdOf(t.file.accountId, t.file.relativePath);
170
+ s = base(t.source, t.file.accountId, label, top);
171
+ out.set(t.source, s);
172
+ }
173
+ add(s.total, t.file.size);
174
+ if (t.state === "done")
175
+ add(s.done, t.file.size);
176
+ else if (t.state === "queued" || t.state === "uploading" || t.state === "copying")
177
+ add(s.queued, t.file.size);
178
+ else if (t.state === "waiting-room")
179
+ add(s.waitingForRoom, t.file.size);
180
+ else if (t.state === "waiting-drive")
181
+ add(s.waitingForDrive, t.file.size);
182
+ else if (t.state === "skipped")
183
+ add(s.skipped, t.file.size);
184
+ else if (t.state === "failed")
185
+ add(s.failed, t.file.size);
186
+ }
187
+ // A source whose drive is not there could not be walked: it keeps what it last knew, all waiting.
188
+ for (const [id, u] of unreachable) {
189
+ if (out.has(id))
190
+ continue;
191
+ const s = base(id, u.accountId, u.top, u.top);
192
+ const prev = prevSources.get(id);
193
+ if (prev) {
194
+ s.total = { ...prev.total };
195
+ s.done = { ...prev.done };
196
+ s.added = prev.added;
197
+ s.duplicate = prev.duplicate;
198
+ s.blocked = prev.blocked;
199
+ s.parked = prev.parked;
200
+ s.failed = { ...prev.failed };
201
+ s.waitingForDrive = { files: Math.max(0, prev.total.files - prev.done.files - prev.failed.files), bytes: Math.max(0, prev.total.bytes - prev.done.bytes - prev.failed.bytes) };
202
+ }
203
+ out.set(id, s);
204
+ }
205
+ for (const s of out.values()) {
206
+ const o2 = outcomes.get(s.id);
207
+ const prev = prevSources.get(s.id);
208
+ // A folder that is not a link EMPTIES as it is filed: what an unfinished run filed before
209
+ // this sweep is gone from the walk, so it is carried. A link's files stay and are counted.
210
+ if (s.kind !== "linked" && prev && prev.finishedAt === null && !unreachable.has(s.id)) {
211
+ s.total.files += prev.done.files;
212
+ s.total.bytes += prev.done.bytes;
213
+ s.done.files += prev.done.files;
214
+ s.done.bytes += prev.done.bytes;
215
+ s.added += prev.added;
216
+ s.duplicate += prev.duplicate;
217
+ s.blocked += prev.blocked;
218
+ s.parked += prev.parked;
219
+ }
220
+ if (o2) {
221
+ s.added += o2.added;
222
+ s.duplicate += o2.duplicate;
223
+ s.blocked += o2.blocked;
224
+ s.parked += o2.parked;
225
+ if (o2.last)
226
+ s.lastOutcomeAt = o2.last;
227
+ }
228
+ s.current = current.get(s.id) ?? null;
229
+ // Skipped files (an unfinished download, an alias with no target) are shown but do not hold a run open.
230
+ const left = s.queued.files + s.waitingForRoom.files + s.waitingForDrive.files;
231
+ if (walked && left === 0 && !unreachable.has(s.id))
232
+ s.finishedAt = prev?.finishedAt && s.done.files === prev.done.files ? prev.finishedAt : (s.lastOutcomeAt ?? iso());
233
+ }
234
+ // A source that is no longer there (a folder filed to the last file, an unlinked link) keeps its
235
+ // row as finished for a week; one this sweep did not reach yet (the walk is not done) keeps its row as is.
236
+ for (const prev of prevSources.values()) {
237
+ if (out.has(prev.id))
238
+ continue;
239
+ if (!walked) {
240
+ out.set(prev.id, prev);
241
+ continue;
242
+ }
243
+ const finishedAt = prev.finishedAt ?? prev.lastOutcomeAt ?? iso();
244
+ if (now() - Date.parse(finishedAt) > FINISHED_KEPT_MS)
245
+ continue;
246
+ out.set(prev.id, {
247
+ ...prev,
248
+ finishedAt,
249
+ queued: zero(),
250
+ waitingForRoom: zero(),
251
+ waitingForDrive: zero(),
252
+ skipped: zero(),
253
+ current: null,
254
+ // What was left when it went is not done — a folder the owner took back out reads as such.
255
+ total: prev.finishedAt ? prev.total : { files: prev.done.files + prev.failed.files, bytes: prev.done.bytes + prev.failed.bytes },
256
+ });
257
+ }
258
+ return [...out.values()].sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));
259
+ }
260
+ function writeProgress(force = false) {
261
+ if (!force && now() - lastWrite < WRITE_EVERY_MS)
262
+ return;
263
+ lastWrite = now();
264
+ const record = {
265
+ v: PROGRESS_VERSION,
266
+ app: o.app,
267
+ job: o.job,
268
+ everySeconds: o.everySeconds,
269
+ dropzone: o.dropzone,
270
+ updatedAt: iso(),
271
+ sweep,
272
+ accounts: o.accounts.length ? o.accounts.map((a) => ({ id: a.id, label: a.label })) : (previous?.accounts ?? []),
273
+ room: o.room?.() ?? null,
274
+ sources: sources(),
275
+ };
276
+ safely("progress", () => {
277
+ mkdirSync(o.stateDir, { recursive: true });
278
+ writeFileSync(`${progressPath}.tmp`, `${JSON.stringify(record)}\n`);
279
+ renameSync(`${progressPath}.tmp`, progressPath);
280
+ });
281
+ }
282
+ function writeQueue() {
283
+ const lines = [];
284
+ for (const t of tracked.values())
285
+ if (t.state !== "done")
286
+ lines.push(JSON.stringify({ source: t.source, path: t.file.relativePath, bytes: t.file.size, state: t.state }));
287
+ safely("queue", () => {
288
+ mkdirSync(o.stateDir, { recursive: true });
289
+ writeFileSync(`${queuePath}.tmp`, lines.length ? `${lines.join("\n")}\n` : "");
290
+ renameSync(`${queuePath}.tmp`, queuePath);
291
+ });
292
+ }
293
+ function journal(line) {
294
+ safely("file journal", () => {
295
+ mkdirSync(o.stateDir, { recursive: true });
296
+ appendFileSync(journalPath, `${JSON.stringify(line)}\n`);
297
+ });
298
+ }
299
+ const set = (file, state, force = false) => {
300
+ const t = tracked.get(keyOf(file));
301
+ if (t)
302
+ t.state = state;
303
+ writeProgress(force);
304
+ };
305
+ safely("file journal", () => {
306
+ if (existsSync(journalPath) && statSync(journalPath).size > JOURNAL_ROTATE_BYTES)
307
+ renameSync(journalPath, join(o.stateDir, `${basename(FILES_JOURNAL, ".jsonl")}.1.jsonl`));
308
+ });
309
+ const startJournal = !existsSync(journalPath) && !existsSync(join(o.stateDir, `${basename(FILES_JOURNAL, ".jsonl")}.1.jsonl`));
310
+ safely("progress", () => writeProgress(true));
311
+ /**
312
+ * 🔴 Every hook is GUARDED: the reporter runs inside the live sweep, and nothing it gets wrong may
313
+ * cost a file its import. A throw is logged once and the page goes stale; the sweep carries on.
314
+ */
315
+ const guarded = (what, fn) => (...args) => safely(what, () => fn(...args));
316
+ const hooks = {
317
+ /** The walk is about to start. */
318
+ walking() {
319
+ sweep.phase = "walking";
320
+ writeProgress(true);
321
+ },
322
+ /** A link whose target cannot be reached right now. */
323
+ unreachable(accountId, relativePath, target) {
324
+ // The link itself — at the account folder's top, so its path IS its first segment.
325
+ const top = relativePath.split("/")[0];
326
+ if (top)
327
+ unreachable.set(`${accountId}:${top}`, { accountId, top, target });
328
+ },
329
+ /**
330
+ * Everything the walk found. A file `settled` says an earlier run filed is `done`; the first time
331
+ * the journal is started, those settled files are written into it, at their own dates.
332
+ */
333
+ found(files, settled) {
334
+ const backfill = [];
335
+ for (const file of files) {
336
+ const { id } = sourceIdOf(file.accountId, file.relativePath);
337
+ const entry = settled?.(file);
338
+ tracked.set(keyOf(file), { file, source: id, state: entry?.outcome ? "done" : "queued" });
339
+ if (entry?.outcome && (!firstSettled.has(id) || Date.parse(entry.at) < Date.parse(firstSettled.get(id) ?? "")))
340
+ firstSettled.set(id, entry.at);
341
+ if (entry?.outcome && (!lastSettled.has(id) || Date.parse(entry.at) > Date.parse(lastSettled.get(id) ?? "")))
342
+ lastSettled.set(id, entry.at);
343
+ if (entry?.outcome && startJournal)
344
+ backfill.push({ at: entry.at, source: id, account: file.accountId, path: file.relativePath, bytes: file.size, outcome: entry.outcome, ...(entry.itemId ? { itemId: entry.itemId } : {}), backfilled: true });
345
+ }
346
+ if (backfill.length > 0) {
347
+ backfill.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
348
+ safely("file journal", () => {
349
+ mkdirSync(o.stateDir, { recursive: true });
350
+ appendFileSync(journalPath, `${backfill.map((l) => JSON.stringify(l)).join("\n")}\n`);
351
+ });
352
+ }
353
+ walked = true;
354
+ sweep.phase = "filing";
355
+ writeQueue();
356
+ writeProgress(true);
357
+ },
358
+ /** `SweepDeps.progress` — what the sweep decided about a file before (or instead of) filing it. */
359
+ progress: {
360
+ waiting(file, why) {
361
+ set(file, why === "done" ? "done" : why === "room" ? "waiting-room" : why === "drive" ? "waiting-drive" : why);
362
+ },
363
+ uploading(file, key) {
364
+ const { id } = sourceIdOf(file.accountId, file.relativePath);
365
+ current.set(id, { path: file.relativePath, bytes: file.size, key, startedAt: iso() });
366
+ // Forced: the file going in is the line the page leads with.
367
+ set(file, "uploading", true);
368
+ },
369
+ },
370
+ /** `SweepDeps.onResult` — a file reached its outcome. */
371
+ result(file, result) {
372
+ const { id } = sourceIdOf(file.accountId, file.relativePath);
373
+ const o2 = outcomeOf(id);
374
+ const at = iso();
375
+ o2.last = at;
376
+ if (current.get(id)?.path === file.relativePath)
377
+ current.delete(id);
378
+ if (result.outcome === "failed") {
379
+ add(o2.failed, file.size);
380
+ set(file, "failed");
381
+ }
382
+ else {
383
+ o2[result.outcome]++;
384
+ add(o2.done, file.size);
385
+ set(file, "done");
386
+ }
387
+ journal({
388
+ at,
389
+ source: id,
390
+ account: file.accountId,
391
+ path: file.relativePath,
392
+ bytes: file.size,
393
+ outcome: result.outcome,
394
+ ...("detail" in result && result.detail ? { detail: result.detail.slice(0, 400) } : {}),
395
+ ...("itemId" in result && result.itemId ? { itemId: result.itemId } : {}),
396
+ });
397
+ },
398
+ /** The sweep is over — `error` when it stopped on one. Only the first call counts. */
399
+ finish(error) {
400
+ if (sweep.finishedAt)
401
+ return;
402
+ sweep.phase = "done";
403
+ sweep.finishedAt = iso();
404
+ sweep.state = error ? "failed" : "finished";
405
+ if (error)
406
+ sweep.error = error.slice(0, 600);
407
+ current.clear();
408
+ if (walked)
409
+ writeQueue();
410
+ writeProgress(true);
411
+ },
412
+ };
413
+ return {
414
+ walking: guarded("progress", hooks.walking),
415
+ unreachable: guarded("progress", hooks.unreachable),
416
+ found: guarded("progress", hooks.found),
417
+ progress: { waiting: guarded("progress", hooks.progress.waiting), uploading: guarded("progress", hooks.progress.uploading) },
418
+ result: guarded("file journal", hooks.result),
419
+ finish: guarded("progress", hooks.finish),
420
+ };
421
+ }
422
+ export function readProgress(path) {
423
+ try {
424
+ const raw = JSON.parse(readFileSync(path, "utf8"));
425
+ return raw && raw.v === PROGRESS_VERSION && Array.isArray(raw.sources) ? raw : null;
426
+ }
427
+ catch {
428
+ return null;
429
+ }
430
+ }