cursedbelt-server 4.48.1 → 4.49.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/d1/pullD1.d.ts +4 -1
- package/dist/server/d1/pullD1.js +5 -2
- package/dist/server/dropzone/index.d.ts +1 -0
- package/dist/server/dropzone/index.js +1 -0
- package/dist/server/dropzone/report.d.ts +188 -0
- package/dist/server/dropzone/report.js +430 -0
- package/dist/server/dropzone/scan.d.ts +21 -2
- package/dist/server/dropzone/scan.js +46 -1
- package/package.json +1 -1
- package/src/server/d1/pullD1.spec.ts +8 -0
- package/src/server/d1/pullD1.ts +5 -2
- package/src/server/dropzone/index.ts +8 -0
- package/src/server/dropzone/report.spec.ts +275 -0
- package/src/server/dropzone/report.ts +568 -0
- package/src/server/dropzone/scan.ts +67 -4
|
@@ -0,0 +1,568 @@
|
|
|
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
|
+
|
|
39
|
+
export const PROGRESS_VERSION = 1;
|
|
40
|
+
export const PROGRESS_FILE = "progress.json";
|
|
41
|
+
export const FILES_JOURNAL = "files.jsonl";
|
|
42
|
+
export const QUEUE_FILE = "queue.jsonl";
|
|
43
|
+
/** The page polls every few seconds; the file need not be fresher than that. */
|
|
44
|
+
export const WRITE_EVERY_MS = 2_000;
|
|
45
|
+
export const JOURNAL_ROTATE_BYTES = 64 * 1024 ** 2;
|
|
46
|
+
/** A finished source stays listed this long, so "what finished today" is on the page. */
|
|
47
|
+
export const FINISHED_KEPT_MS = 7 * 24 * 60 * 60 * 1000;
|
|
48
|
+
/** The name of the source that holds an account's loose files. */
|
|
49
|
+
export const LOOSE_FILES = "Loose files";
|
|
50
|
+
|
|
51
|
+
/** Where a file is on its way through the sweep. Outcomes leave the queue. */
|
|
52
|
+
/** `copying`: still being written into the dropzone — it goes in on a later sweep. `skipped`: left alone. */
|
|
53
|
+
export type FileState = "queued" | "copying" | "uploading" | "waiting-room" | "waiting-drive" | "skipped" | "failed";
|
|
54
|
+
export type FileOutcome = "added" | "duplicate" | "parked" | "blocked" | "failed";
|
|
55
|
+
|
|
56
|
+
export interface Tally {
|
|
57
|
+
files: number;
|
|
58
|
+
bytes: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface SourceDrive {
|
|
62
|
+
volume: string;
|
|
63
|
+
/** `ok` mounted · `unmounted` the volume is not there (unplugged) · `deleted` mounted, folder gone. */
|
|
64
|
+
state: "ok" | "unmounted" | "deleted";
|
|
65
|
+
/** The volume is a disk image: where its file lives, and whether THAT drive is plugged in. */
|
|
66
|
+
image?: { file: string; hostVolume: string | null; hostMounted: boolean; reattachTried: boolean };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** What the reporter needs of a file: whose it is, where it is, and how big. */
|
|
70
|
+
export interface ReportFile {
|
|
71
|
+
accountId: string;
|
|
72
|
+
/** Absolute path — with the account, what tells two files apart. */
|
|
73
|
+
path: string;
|
|
74
|
+
/** Relative to the account folder: its first segment names the source. */
|
|
75
|
+
relativePath: string;
|
|
76
|
+
size: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A file's outcome, as the journal records it. */
|
|
80
|
+
export type ReportResult = { outcome: FileOutcome; detail?: string; itemId?: string };
|
|
81
|
+
|
|
82
|
+
/** What an earlier run already settled for a file — `found`'s `settled` answers it. */
|
|
83
|
+
export interface SettledFile {
|
|
84
|
+
outcome?: Exclude<FileOutcome, "failed"> | null;
|
|
85
|
+
at: string;
|
|
86
|
+
itemId?: string | null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface ProgressSource {
|
|
90
|
+
id: string;
|
|
91
|
+
account: { id: string; label: string };
|
|
92
|
+
/** The folder or link's own name, or {@link LOOSE_FILES}. */
|
|
93
|
+
label: string;
|
|
94
|
+
kind: "linked" | "folder" | "loose";
|
|
95
|
+
/** Where it is in the dropzone. */
|
|
96
|
+
path: string;
|
|
97
|
+
/** A link's real target. */
|
|
98
|
+
target?: string;
|
|
99
|
+
drive?: SourceDrive;
|
|
100
|
+
startedAt: string;
|
|
101
|
+
/** When nothing was left to do — cleared if more arrives. */
|
|
102
|
+
finishedAt: string | null;
|
|
103
|
+
/** When the last file reached an outcome. */
|
|
104
|
+
lastOutcomeAt: string | null;
|
|
105
|
+
/** Everything it holds: what is left, plus (for a folder that empties as it goes) what was filed. */
|
|
106
|
+
total: Tally;
|
|
107
|
+
done: Tally;
|
|
108
|
+
added: number;
|
|
109
|
+
duplicate: number;
|
|
110
|
+
blocked: number;
|
|
111
|
+
parked: number;
|
|
112
|
+
queued: Tally;
|
|
113
|
+
waitingForRoom: Tally;
|
|
114
|
+
waitingForDrive: Tally;
|
|
115
|
+
skipped: Tally;
|
|
116
|
+
failed: Tally;
|
|
117
|
+
current: { path: string; bytes: number; key: string; startedAt: string } | null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface IngestProgress {
|
|
121
|
+
v: typeof PROGRESS_VERSION;
|
|
122
|
+
app: string;
|
|
123
|
+
/** The launchd job that runs the sweep — station reads its health and can start it. */
|
|
124
|
+
job: string;
|
|
125
|
+
everySeconds: number;
|
|
126
|
+
dropzone: string;
|
|
127
|
+
updatedAt: string;
|
|
128
|
+
sweep: {
|
|
129
|
+
pid: number;
|
|
130
|
+
startedAt: string;
|
|
131
|
+
finishedAt: string | null;
|
|
132
|
+
state: "running" | "finished" | "failed";
|
|
133
|
+
phase: "starting" | "walking" | "filing" | "done";
|
|
134
|
+
error?: string;
|
|
135
|
+
};
|
|
136
|
+
/** The app's accounts — what the `uid` on its web uploads names (`/api/upload/session`). */
|
|
137
|
+
accounts: { id: string; label: string }[];
|
|
138
|
+
/**
|
|
139
|
+
* The store's free space against the floor the sweep keeps, and what recently filed files'
|
|
140
|
+
* derivatives still hold back of it, until when — collections' linked pacing; `null` for a sweep
|
|
141
|
+
* that does not wait for room.
|
|
142
|
+
*/
|
|
143
|
+
room: ReportRoom | null;
|
|
144
|
+
sources: ProgressSource[];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface ReportRoom {
|
|
148
|
+
freeBytes: number | null;
|
|
149
|
+
floorBytes: number;
|
|
150
|
+
spaceFactor: number;
|
|
151
|
+
owedBytes?: number;
|
|
152
|
+
owedUntil?: string | null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface FileLine {
|
|
156
|
+
at: string;
|
|
157
|
+
source: string;
|
|
158
|
+
account: string;
|
|
159
|
+
/** Relative to the account folder. */
|
|
160
|
+
path: string;
|
|
161
|
+
bytes: number;
|
|
162
|
+
outcome: FileOutcome;
|
|
163
|
+
detail?: string;
|
|
164
|
+
itemId?: string;
|
|
165
|
+
/** From `found`'s `settled`, the first time the journal was started — not seen happening. */
|
|
166
|
+
backfilled?: true;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export interface QueueLine {
|
|
170
|
+
source: string;
|
|
171
|
+
path: string;
|
|
172
|
+
bytes: number;
|
|
173
|
+
state: FileState;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const zero = (): Tally => ({ files: 0, bytes: 0 });
|
|
177
|
+
const add = (t: Tally, bytes: number): void => {
|
|
178
|
+
t.files++;
|
|
179
|
+
t.bytes += bytes;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/** The source a file belongs to: its account plus the first segment of its path, or the loose files. */
|
|
183
|
+
export function sourceIdOf(accountId: string, relativePath: string): { id: string; label: string; top: string | null } {
|
|
184
|
+
const slash = relativePath.indexOf("/");
|
|
185
|
+
if (slash < 0) return { id: `${accountId}:`, label: LOOSE_FILES, top: null };
|
|
186
|
+
const top = relativePath.slice(0, slash);
|
|
187
|
+
return { id: `${accountId}:${top}`, label: top, top };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export interface ReporterOptions {
|
|
191
|
+
/** `$FORGE_STATE/state/<app>-ingest` — station finds the report by that name. */
|
|
192
|
+
stateDir: string;
|
|
193
|
+
app: string;
|
|
194
|
+
/** The launchd job that runs the sweep. */
|
|
195
|
+
job: string;
|
|
196
|
+
everySeconds: number;
|
|
197
|
+
dropzone: string;
|
|
198
|
+
/** Each account folder. A one-owner dropzone is one account whose `dir` is the dropzone itself. */
|
|
199
|
+
accounts: readonly { id: string; label: string; dir: string }[];
|
|
200
|
+
/** A linked source's drive: its volume, whether it is plugged in, and for a disk image the drive its file is on. */
|
|
201
|
+
driveOf?: (target: string) => SourceDrive | undefined;
|
|
202
|
+
room?: () => ReportRoom | null;
|
|
203
|
+
now?: () => number;
|
|
204
|
+
warn?: (line: string) => void;
|
|
205
|
+
pid?: number;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
interface Tracked<F extends ReportFile> {
|
|
209
|
+
file: F;
|
|
210
|
+
source: string;
|
|
211
|
+
state: FileState | "done";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* One sweep's reporter. `ingest.ts` makes it before the walk and hands its hooks to `sweepFiles`.
|
|
216
|
+
*/
|
|
217
|
+
export function createIngestReporter<F extends ReportFile = ReportFile>(o: ReporterOptions) {
|
|
218
|
+
const now = o.now ?? Date.now;
|
|
219
|
+
const iso = () => new Date(now()).toISOString();
|
|
220
|
+
const progressPath = join(o.stateDir, PROGRESS_FILE);
|
|
221
|
+
const journalPath = join(o.stateDir, FILES_JOURNAL);
|
|
222
|
+
const queuePath = join(o.stateDir, QUEUE_FILE);
|
|
223
|
+
let warned = false;
|
|
224
|
+
const safely = (what: string, fn: () => void): void => {
|
|
225
|
+
try {
|
|
226
|
+
fn();
|
|
227
|
+
} catch (cause) {
|
|
228
|
+
if (!warned) (o.warn ?? console.warn)(` ? could not write the ${what} station reads (${cause instanceof Error ? cause.message : String(cause)}); the sweep carries on`);
|
|
229
|
+
warned = true;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const previous = readProgress(progressPath);
|
|
234
|
+
const prevSources = new Map((previous?.sources ?? []).map((s) => [s.id, s]));
|
|
235
|
+
const accountLabel = new Map(o.accounts.map((a) => [a.id, a.label]));
|
|
236
|
+
const startedAt = iso();
|
|
237
|
+
const sweep: IngestProgress["sweep"] = { pid: o.pid ?? process.pid, startedAt, finishedAt: null, state: "running", phase: "starting" };
|
|
238
|
+
|
|
239
|
+
const tracked = new Map<string, Tracked<F>>();
|
|
240
|
+
const outcomes = new Map<string, { added: number; duplicate: number; blocked: number; parked: number; failed: Tally; done: Tally; last: string | null }>();
|
|
241
|
+
const current = new Map<string, NonNullable<ProgressSource["current"]>>();
|
|
242
|
+
/** Sources this sweep could not walk at all: their link's drive is not there. */
|
|
243
|
+
const unreachable = new Map<string, { accountId: string; top: string; target: string }>();
|
|
244
|
+
/** The oldest settled date of each source's files — when a linked run really began. */
|
|
245
|
+
const firstSettled = new Map<string, string>();
|
|
246
|
+
/** …and the newest — when a linked run last filed anything, before this sweep. */
|
|
247
|
+
const lastSettled = new Map<string, string>();
|
|
248
|
+
let walked = false;
|
|
249
|
+
let lastWrite = 0;
|
|
250
|
+
const keyOf = (file: F) => `${file.accountId}\0${file.path}`;
|
|
251
|
+
const outcomeOf = (source: string) => {
|
|
252
|
+
let o2 = outcomes.get(source);
|
|
253
|
+
if (!o2) {
|
|
254
|
+
o2 = { added: 0, duplicate: 0, blocked: 0, parked: 0, failed: zero(), done: zero(), last: null };
|
|
255
|
+
outcomes.set(source, o2);
|
|
256
|
+
}
|
|
257
|
+
return o2;
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
/** Each account folder's top-level links: name → real target. */
|
|
261
|
+
const links = new Map<string, string>();
|
|
262
|
+
for (const account of o.accounts) {
|
|
263
|
+
let names: string[] = [];
|
|
264
|
+
try {
|
|
265
|
+
names = readdirSync(account.dir);
|
|
266
|
+
} catch {
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
for (const name of names) {
|
|
270
|
+
const full = join(account.dir, name);
|
|
271
|
+
try {
|
|
272
|
+
links.set(`${account.id}:${name}`, resolve(dirname(full), readlinkSync(full)));
|
|
273
|
+
} catch {
|
|
274
|
+
/* not a link */
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const driveOf = (target: string): SourceDrive | undefined => {
|
|
279
|
+
try {
|
|
280
|
+
return o.driveOf?.(target);
|
|
281
|
+
} catch {
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
function sources(): ProgressSource[] {
|
|
287
|
+
const out = new Map<string, ProgressSource>();
|
|
288
|
+
const base = (id: string, accountId: string, label: string, top: string | null): ProgressSource => {
|
|
289
|
+
const prev = prevSources.get(id);
|
|
290
|
+
const target = top ? links.get(`${accountId}:${top}`) : undefined;
|
|
291
|
+
const account = o.accounts.find((a) => a.id === accountId);
|
|
292
|
+
const drive = target ? driveOf(target) : undefined;
|
|
293
|
+
return {
|
|
294
|
+
id,
|
|
295
|
+
account: { id: accountId, label: accountLabel.get(accountId) ?? accountId },
|
|
296
|
+
label,
|
|
297
|
+
kind: target ? "linked" : top ? "folder" : "loose",
|
|
298
|
+
path: account ? (top ? join(account.dir, top) : account.dir) : (prev?.path ?? ""),
|
|
299
|
+
...(target ? { target, ...(drive ? { drive } : {}) } : {}),
|
|
300
|
+
startedAt: prev && (prev.finishedAt === null || target) ? prev.startedAt : (firstSettled.get(id) ?? startedAt),
|
|
301
|
+
finishedAt: null,
|
|
302
|
+
lastOutcomeAt: prev?.lastOutcomeAt ?? lastSettled.get(id) ?? null,
|
|
303
|
+
total: zero(),
|
|
304
|
+
done: zero(),
|
|
305
|
+
added: 0,
|
|
306
|
+
duplicate: 0,
|
|
307
|
+
blocked: 0,
|
|
308
|
+
parked: 0,
|
|
309
|
+
queued: zero(),
|
|
310
|
+
waitingForRoom: zero(),
|
|
311
|
+
waitingForDrive: zero(),
|
|
312
|
+
skipped: zero(),
|
|
313
|
+
failed: zero(),
|
|
314
|
+
current: null,
|
|
315
|
+
};
|
|
316
|
+
};
|
|
317
|
+
for (const t of tracked.values()) {
|
|
318
|
+
let s = out.get(t.source);
|
|
319
|
+
if (!s) {
|
|
320
|
+
const { label, top } = sourceIdOf(t.file.accountId, t.file.relativePath);
|
|
321
|
+
s = base(t.source, t.file.accountId, label, top);
|
|
322
|
+
out.set(t.source, s);
|
|
323
|
+
}
|
|
324
|
+
add(s.total, t.file.size);
|
|
325
|
+
if (t.state === "done") add(s.done, t.file.size);
|
|
326
|
+
else if (t.state === "queued" || t.state === "uploading" || t.state === "copying") add(s.queued, t.file.size);
|
|
327
|
+
else if (t.state === "waiting-room") add(s.waitingForRoom, t.file.size);
|
|
328
|
+
else if (t.state === "waiting-drive") add(s.waitingForDrive, t.file.size);
|
|
329
|
+
else if (t.state === "skipped") add(s.skipped, t.file.size);
|
|
330
|
+
else if (t.state === "failed") add(s.failed, t.file.size);
|
|
331
|
+
}
|
|
332
|
+
// A source whose drive is not there could not be walked: it keeps what it last knew, all waiting.
|
|
333
|
+
for (const [id, u] of unreachable) {
|
|
334
|
+
if (out.has(id)) continue;
|
|
335
|
+
const s = base(id, u.accountId, u.top, u.top);
|
|
336
|
+
const prev = prevSources.get(id);
|
|
337
|
+
if (prev) {
|
|
338
|
+
s.total = { ...prev.total };
|
|
339
|
+
s.done = { ...prev.done };
|
|
340
|
+
s.added = prev.added;
|
|
341
|
+
s.duplicate = prev.duplicate;
|
|
342
|
+
s.blocked = prev.blocked;
|
|
343
|
+
s.parked = prev.parked;
|
|
344
|
+
s.failed = { ...prev.failed };
|
|
345
|
+
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) };
|
|
346
|
+
}
|
|
347
|
+
out.set(id, s);
|
|
348
|
+
}
|
|
349
|
+
for (const s of out.values()) {
|
|
350
|
+
const o2 = outcomes.get(s.id);
|
|
351
|
+
const prev = prevSources.get(s.id);
|
|
352
|
+
// A folder that is not a link EMPTIES as it is filed: what an unfinished run filed before
|
|
353
|
+
// this sweep is gone from the walk, so it is carried. A link's files stay and are counted.
|
|
354
|
+
if (s.kind !== "linked" && prev && prev.finishedAt === null && !unreachable.has(s.id)) {
|
|
355
|
+
s.total.files += prev.done.files;
|
|
356
|
+
s.total.bytes += prev.done.bytes;
|
|
357
|
+
s.done.files += prev.done.files;
|
|
358
|
+
s.done.bytes += prev.done.bytes;
|
|
359
|
+
s.added += prev.added;
|
|
360
|
+
s.duplicate += prev.duplicate;
|
|
361
|
+
s.blocked += prev.blocked;
|
|
362
|
+
s.parked += prev.parked;
|
|
363
|
+
}
|
|
364
|
+
if (o2) {
|
|
365
|
+
s.added += o2.added;
|
|
366
|
+
s.duplicate += o2.duplicate;
|
|
367
|
+
s.blocked += o2.blocked;
|
|
368
|
+
s.parked += o2.parked;
|
|
369
|
+
if (o2.last) s.lastOutcomeAt = o2.last;
|
|
370
|
+
}
|
|
371
|
+
s.current = current.get(s.id) ?? null;
|
|
372
|
+
// Skipped files (an unfinished download, an alias with no target) are shown but do not hold a run open.
|
|
373
|
+
const left = s.queued.files + s.waitingForRoom.files + s.waitingForDrive.files;
|
|
374
|
+
if (walked && left === 0 && !unreachable.has(s.id)) s.finishedAt = prev?.finishedAt && s.done.files === prev.done.files ? prev.finishedAt : (s.lastOutcomeAt ?? iso());
|
|
375
|
+
}
|
|
376
|
+
// A source that is no longer there (a folder filed to the last file, an unlinked link) keeps its
|
|
377
|
+
// row as finished for a week; one this sweep did not reach yet (the walk is not done) keeps its row as is.
|
|
378
|
+
for (const prev of prevSources.values()) {
|
|
379
|
+
if (out.has(prev.id)) continue;
|
|
380
|
+
if (!walked) {
|
|
381
|
+
out.set(prev.id, prev);
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
const finishedAt = prev.finishedAt ?? prev.lastOutcomeAt ?? iso();
|
|
385
|
+
if (now() - Date.parse(finishedAt) > FINISHED_KEPT_MS) continue;
|
|
386
|
+
out.set(prev.id, {
|
|
387
|
+
...prev,
|
|
388
|
+
finishedAt,
|
|
389
|
+
queued: zero(),
|
|
390
|
+
waitingForRoom: zero(),
|
|
391
|
+
waitingForDrive: zero(),
|
|
392
|
+
skipped: zero(),
|
|
393
|
+
current: null,
|
|
394
|
+
// What was left when it went is not done — a folder the owner took back out reads as such.
|
|
395
|
+
total: prev.finishedAt ? prev.total : { files: prev.done.files + prev.failed.files, bytes: prev.done.bytes + prev.failed.bytes },
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
return [...out.values()].sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function writeProgress(force = false): void {
|
|
402
|
+
if (!force && now() - lastWrite < WRITE_EVERY_MS) return;
|
|
403
|
+
lastWrite = now();
|
|
404
|
+
const record: IngestProgress = {
|
|
405
|
+
v: PROGRESS_VERSION,
|
|
406
|
+
app: o.app,
|
|
407
|
+
job: o.job,
|
|
408
|
+
everySeconds: o.everySeconds,
|
|
409
|
+
dropzone: o.dropzone,
|
|
410
|
+
updatedAt: iso(),
|
|
411
|
+
sweep,
|
|
412
|
+
accounts: o.accounts.length ? o.accounts.map((a) => ({ id: a.id, label: a.label })) : (previous?.accounts ?? []),
|
|
413
|
+
room: o.room?.() ?? null,
|
|
414
|
+
sources: sources(),
|
|
415
|
+
};
|
|
416
|
+
safely("progress", () => {
|
|
417
|
+
mkdirSync(o.stateDir, { recursive: true });
|
|
418
|
+
writeFileSync(`${progressPath}.tmp`, `${JSON.stringify(record)}\n`);
|
|
419
|
+
renameSync(`${progressPath}.tmp`, progressPath);
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function writeQueue(): void {
|
|
424
|
+
const lines: string[] = [];
|
|
425
|
+
for (const t of tracked.values())
|
|
426
|
+
if (t.state !== "done") lines.push(JSON.stringify({ source: t.source, path: t.file.relativePath, bytes: t.file.size, state: t.state } satisfies QueueLine));
|
|
427
|
+
safely("queue", () => {
|
|
428
|
+
mkdirSync(o.stateDir, { recursive: true });
|
|
429
|
+
writeFileSync(`${queuePath}.tmp`, lines.length ? `${lines.join("\n")}\n` : "");
|
|
430
|
+
renameSync(`${queuePath}.tmp`, queuePath);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function journal(line: FileLine): void {
|
|
435
|
+
safely("file journal", () => {
|
|
436
|
+
mkdirSync(o.stateDir, { recursive: true });
|
|
437
|
+
appendFileSync(journalPath, `${JSON.stringify(line)}\n`);
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const set = (file: F, state: FileState | "done", force = false): void => {
|
|
442
|
+
const t = tracked.get(keyOf(file));
|
|
443
|
+
if (t) t.state = state;
|
|
444
|
+
writeProgress(force);
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
safely("file journal", () => {
|
|
448
|
+
if (existsSync(journalPath) && statSync(journalPath).size > JOURNAL_ROTATE_BYTES) renameSync(journalPath, join(o.stateDir, `${basename(FILES_JOURNAL, ".jsonl")}.1.jsonl`));
|
|
449
|
+
});
|
|
450
|
+
const startJournal = !existsSync(journalPath) && !existsSync(join(o.stateDir, `${basename(FILES_JOURNAL, ".jsonl")}.1.jsonl`));
|
|
451
|
+
safely("progress", () => writeProgress(true));
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* 🔴 Every hook is GUARDED: the reporter runs inside the live sweep, and nothing it gets wrong may
|
|
455
|
+
* cost a file its import. A throw is logged once and the page goes stale; the sweep carries on.
|
|
456
|
+
*/
|
|
457
|
+
const guarded = <A extends unknown[]>(what: string, fn: (...args: A) => void) =>
|
|
458
|
+
(...args: A): void => safely(what, () => fn(...args));
|
|
459
|
+
|
|
460
|
+
const hooks = {
|
|
461
|
+
/** The walk is about to start. */
|
|
462
|
+
walking(): void {
|
|
463
|
+
sweep.phase = "walking";
|
|
464
|
+
writeProgress(true);
|
|
465
|
+
},
|
|
466
|
+
/** A link whose target cannot be reached right now. */
|
|
467
|
+
unreachable(accountId: string, relativePath: string, target: string): void {
|
|
468
|
+
// The link itself — at the account folder's top, so its path IS its first segment.
|
|
469
|
+
const top = relativePath.split("/")[0];
|
|
470
|
+
if (top) unreachable.set(`${accountId}:${top}`, { accountId, top, target });
|
|
471
|
+
},
|
|
472
|
+
/**
|
|
473
|
+
* Everything the walk found. A file `settled` says an earlier run filed is `done`; the first time
|
|
474
|
+
* the journal is started, those settled files are written into it, at their own dates.
|
|
475
|
+
*/
|
|
476
|
+
found(files: readonly F[], settled?: (file: F) => SettledFile | undefined): void {
|
|
477
|
+
const backfill: FileLine[] = [];
|
|
478
|
+
for (const file of files) {
|
|
479
|
+
const { id } = sourceIdOf(file.accountId, file.relativePath);
|
|
480
|
+
const entry = settled?.(file);
|
|
481
|
+
tracked.set(keyOf(file), { file, source: id, state: entry?.outcome ? "done" : "queued" });
|
|
482
|
+
if (entry?.outcome && (!firstSettled.has(id) || Date.parse(entry.at) < Date.parse(firstSettled.get(id) ?? ""))) firstSettled.set(id, entry.at);
|
|
483
|
+
if (entry?.outcome && (!lastSettled.has(id) || Date.parse(entry.at) > Date.parse(lastSettled.get(id) ?? ""))) lastSettled.set(id, entry.at);
|
|
484
|
+
if (entry?.outcome && startJournal)
|
|
485
|
+
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 });
|
|
486
|
+
}
|
|
487
|
+
if (backfill.length > 0) {
|
|
488
|
+
backfill.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
|
|
489
|
+
safely("file journal", () => {
|
|
490
|
+
mkdirSync(o.stateDir, { recursive: true });
|
|
491
|
+
appendFileSync(journalPath, `${backfill.map((l) => JSON.stringify(l)).join("\n")}\n`);
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
walked = true;
|
|
495
|
+
sweep.phase = "filing";
|
|
496
|
+
writeQueue();
|
|
497
|
+
writeProgress(true);
|
|
498
|
+
},
|
|
499
|
+
/** `SweepDeps.progress` — what the sweep decided about a file before (or instead of) filing it. */
|
|
500
|
+
progress: {
|
|
501
|
+
waiting(file: F, why: "done" | "room" | "drive" | "copying" | "skipped"): void {
|
|
502
|
+
set(file, why === "done" ? "done" : why === "room" ? "waiting-room" : why === "drive" ? "waiting-drive" : why);
|
|
503
|
+
},
|
|
504
|
+
uploading(file: F, key: string): void {
|
|
505
|
+
const { id } = sourceIdOf(file.accountId, file.relativePath);
|
|
506
|
+
current.set(id, { path: file.relativePath, bytes: file.size, key, startedAt: iso() });
|
|
507
|
+
// Forced: the file going in is the line the page leads with.
|
|
508
|
+
set(file, "uploading", true);
|
|
509
|
+
},
|
|
510
|
+
},
|
|
511
|
+
/** `SweepDeps.onResult` — a file reached its outcome. */
|
|
512
|
+
result(file: F, result: ReportResult): void {
|
|
513
|
+
const { id } = sourceIdOf(file.accountId, file.relativePath);
|
|
514
|
+
const o2 = outcomeOf(id);
|
|
515
|
+
const at = iso();
|
|
516
|
+
o2.last = at;
|
|
517
|
+
if (current.get(id)?.path === file.relativePath) current.delete(id);
|
|
518
|
+
if (result.outcome === "failed") {
|
|
519
|
+
add(o2.failed, file.size);
|
|
520
|
+
set(file, "failed");
|
|
521
|
+
} else {
|
|
522
|
+
o2[result.outcome]++;
|
|
523
|
+
add(o2.done, file.size);
|
|
524
|
+
set(file, "done");
|
|
525
|
+
}
|
|
526
|
+
journal({
|
|
527
|
+
at,
|
|
528
|
+
source: id,
|
|
529
|
+
account: file.accountId,
|
|
530
|
+
path: file.relativePath,
|
|
531
|
+
bytes: file.size,
|
|
532
|
+
outcome: result.outcome,
|
|
533
|
+
...("detail" in result && result.detail ? { detail: result.detail.slice(0, 400) } : {}),
|
|
534
|
+
...("itemId" in result && result.itemId ? { itemId: result.itemId } : {}),
|
|
535
|
+
});
|
|
536
|
+
},
|
|
537
|
+
/** The sweep is over — `error` when it stopped on one. Only the first call counts. */
|
|
538
|
+
finish(error?: string): void {
|
|
539
|
+
if (sweep.finishedAt) return;
|
|
540
|
+
sweep.phase = "done";
|
|
541
|
+
sweep.finishedAt = iso();
|
|
542
|
+
sweep.state = error ? "failed" : "finished";
|
|
543
|
+
if (error) sweep.error = error.slice(0, 600);
|
|
544
|
+
current.clear();
|
|
545
|
+
if (walked) writeQueue();
|
|
546
|
+
writeProgress(true);
|
|
547
|
+
},
|
|
548
|
+
};
|
|
549
|
+
return {
|
|
550
|
+
walking: guarded("progress", hooks.walking),
|
|
551
|
+
unreachable: guarded("progress", hooks.unreachable),
|
|
552
|
+
found: guarded("progress", hooks.found),
|
|
553
|
+
progress: { waiting: guarded("progress", hooks.progress.waiting), uploading: guarded("progress", hooks.progress.uploading) },
|
|
554
|
+
result: guarded("file journal", hooks.result),
|
|
555
|
+
finish: guarded("progress", hooks.finish),
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export type IngestReporter<F extends ReportFile = ReportFile> = ReturnType<typeof createIngestReporter<F>>;
|
|
560
|
+
|
|
561
|
+
export function readProgress(path: string): IngestProgress | null {
|
|
562
|
+
try {
|
|
563
|
+
const raw = JSON.parse(readFileSync(path, "utf8")) as IngestProgress;
|
|
564
|
+
return raw && raw.v === PROGRESS_VERSION && Array.isArray(raw.sources) ? raw : null;
|
|
565
|
+
} catch {
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
import type { Dirent } from "node:fs";
|
|
36
36
|
import { readdir, rm, rmdir, stat } from "node:fs/promises";
|
|
37
37
|
import { join, relative } from "node:path";
|
|
38
|
+
import type { IngestReporter, ReportFile, ReportResult } from "./report.js";
|
|
38
39
|
|
|
39
40
|
/** A file the sweep found, with everything a handler needs to decide about it. */
|
|
40
41
|
export interface DroppedFile {
|
|
@@ -246,8 +247,34 @@ export async function pruneEmptyDirs(root: string, dir = root): Promise<number>
|
|
|
246
247
|
}
|
|
247
248
|
}
|
|
248
249
|
|
|
249
|
-
/**
|
|
250
|
-
|
|
250
|
+
/**
|
|
251
|
+
* What the app supplies: what to do with one file. `uploading(key)` names the binary-server key its
|
|
252
|
+
* bytes stage under, once the handler knows it — station's Uploads page shows that transfer's own
|
|
253
|
+
* progress on the file's row.
|
|
254
|
+
*/
|
|
255
|
+
export type DropHandler = (file: DroppedFile, ctx: { uploading(key: string): void }) => Promise<DropOutcome>;
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* A sweep's outcome in the words station's Uploads page reads (`report.ts`) — `null` for `held`, which
|
|
259
|
+
* is a standing state rather than an event: the file stays where it is and every sweep meets it
|
|
260
|
+
* again, so it is shown as left alone (`skipped`) instead of journaled every five minutes.
|
|
261
|
+
*/
|
|
262
|
+
export function reportResultOf(outcome: DropOutcome): ReportResult | null {
|
|
263
|
+
const detail = outcome.detail ? { detail: outcome.detail } : {};
|
|
264
|
+
switch (outcome.kind) {
|
|
265
|
+
case "stored":
|
|
266
|
+
return { outcome: "added", ...detail };
|
|
267
|
+
case "duplicate":
|
|
268
|
+
return { outcome: "duplicate", ...detail };
|
|
269
|
+
// Refused by the app's own rule (a format it does not take) — not filed, and not a failure.
|
|
270
|
+
case "discard":
|
|
271
|
+
return { outcome: "blocked", detail: outcome.detail ?? "not something this app files" };
|
|
272
|
+
case "held":
|
|
273
|
+
return null;
|
|
274
|
+
case "failed":
|
|
275
|
+
return { outcome: "failed", detail: outcome.detail };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
251
278
|
|
|
252
279
|
/**
|
|
253
280
|
* Walk a dropzone, hand every file to `handle`, and leave nothing behind that was dealt with.
|
|
@@ -259,8 +286,35 @@ export type DropHandler = (file: DroppedFile) => Promise<DropOutcome>;
|
|
|
259
286
|
export async function sweepDropzone(
|
|
260
287
|
root: string,
|
|
261
288
|
handle: DropHandler,
|
|
262
|
-
opts: ScanOptions & {
|
|
289
|
+
opts: ScanOptions & {
|
|
290
|
+
dryRun?: boolean;
|
|
291
|
+
onProgress?: (done: number, total: number) => void;
|
|
292
|
+
/**
|
|
293
|
+
* Write what the sweep is doing for station's Uploads page (`createIngestReporter`). The dropzone
|
|
294
|
+
* is ONE account, id `""`: each top-level folder is a source, loose files one more. Never on a
|
|
295
|
+
* dry run, which files nothing. Every hook is guarded — a reporter fault never costs a file.
|
|
296
|
+
*/
|
|
297
|
+
report?: IngestReporter;
|
|
298
|
+
} = {},
|
|
299
|
+
): Promise<SweepReport> {
|
|
300
|
+
const reporter = opts.dryRun ? undefined : opts.report;
|
|
301
|
+
try {
|
|
302
|
+
const report = await sweep(root, handle, opts, reporter);
|
|
303
|
+
reporter?.finish();
|
|
304
|
+
return report;
|
|
305
|
+
} catch (error) {
|
|
306
|
+
reporter?.finish(error instanceof Error ? error.message : String(error));
|
|
307
|
+
throw error;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async function sweep(
|
|
312
|
+
root: string,
|
|
313
|
+
handle: DropHandler,
|
|
314
|
+
opts: ScanOptions & { dryRun?: boolean; onProgress?: (done: number, total: number) => void },
|
|
315
|
+
reporter: IngestReporter | undefined,
|
|
263
316
|
): Promise<SweepReport> {
|
|
317
|
+
const as = (file: DroppedFile): ReportFile => ({ accountId: "", path: file.path, relativePath: file.relativePath, size: file.size });
|
|
264
318
|
const report: SweepReport = {
|
|
265
319
|
scanned: 0,
|
|
266
320
|
stored: 0,
|
|
@@ -274,19 +328,25 @@ export async function sweepDropzone(
|
|
|
274
328
|
remaining: 0,
|
|
275
329
|
};
|
|
276
330
|
|
|
331
|
+
reporter?.walking();
|
|
277
332
|
const files = await scanDropzone(root, opts);
|
|
333
|
+
reporter?.found(files.map(as));
|
|
278
334
|
for (const [index, file] of files.entries()) {
|
|
279
335
|
report.scanned++;
|
|
280
336
|
opts.onProgress?.(index + 1, files.length);
|
|
281
337
|
|
|
282
338
|
if (!(await isStable(file, opts.stabilityMs))) {
|
|
283
339
|
report.unstable.push(file.relativePath);
|
|
340
|
+
reporter?.progress.waiting(as(file), "copying");
|
|
284
341
|
continue;
|
|
285
342
|
}
|
|
286
343
|
|
|
287
344
|
let outcome: DropOutcome;
|
|
345
|
+
reporter?.progress.uploading(as(file), "");
|
|
288
346
|
try {
|
|
289
|
-
outcome = opts.dryRun
|
|
347
|
+
outcome = opts.dryRun
|
|
348
|
+
? { kind: "held", detail: "dry run" }
|
|
349
|
+
: await handle(file, { uploading: (key) => reporter?.progress.uploading(as(file), key) });
|
|
290
350
|
} catch (error) {
|
|
291
351
|
// Rule 3: a handler that throws costs one file, never the sweep.
|
|
292
352
|
outcome = {
|
|
@@ -295,6 +355,9 @@ export async function sweepDropzone(
|
|
|
295
355
|
};
|
|
296
356
|
}
|
|
297
357
|
|
|
358
|
+
const result = reportResultOf(outcome);
|
|
359
|
+
if (result) reporter?.result(as(file), result);
|
|
360
|
+
else reporter?.progress.waiting(as(file), "skipped");
|
|
298
361
|
switch (outcome.kind) {
|
|
299
362
|
case "stored":
|
|
300
363
|
case "duplicate":
|