cursedbelt-server 4.49.0 → 4.51.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/dropzone/index.d.ts +5 -1
- package/dist/server/dropzone/index.js +5 -1
- package/dist/server/dropzone/links.d.ts +79 -0
- package/dist/server/dropzone/links.js +190 -0
- package/dist/server/dropzone/scan.d.ts +63 -3
- package/dist/server/dropzone/scan.js +105 -30
- package/dist/server/maps-budget/mapsBudget.d.ts +20 -0
- package/dist/server/maps-budget/mapsBudget.js +57 -0
- package/dist/server/maps-static/staticMap.d.ts +103 -0
- package/dist/server/maps-static/staticMap.js +171 -0
- package/package.json +7 -1
- package/src/server/dropzone/index.ts +21 -0
- package/src/server/dropzone/links.spec.ts +176 -0
- package/src/server/dropzone/links.ts +219 -0
- package/src/server/dropzone/scan.spec.ts +32 -1
- package/src/server/dropzone/scan.ts +142 -30
- package/src/server/maps-budget/mapsBudget.ts +76 -0
- package/src/server/maps-budget/metaTableBudget.spec.ts +34 -0
- package/src/server/maps-static/staticMap.spec.ts +47 -0
- package/src/server/maps-static/staticMap.ts +197 -0
- package/src/server/serveBunOverload.spec.ts +24 -10
- package/src/specsWriteNothingIntoSrc.spec.ts +146 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LINKED sources in a drop folder — a symlink (or a Finder alias) the owner puts there so a
|
|
3
|
+
* folder on another drive is ingested IN PLACE, never moved and never deleted.
|
|
4
|
+
*
|
|
5
|
+
* Owner, 2026-10-21 (collections): *"I want to copy all the files in /Volumes/databundle/tod to
|
|
6
|
+
* collections app account 1, and not delete the copies at that path. Can I make a symlink to it …
|
|
7
|
+
* without copying the files from the volume into that folder?"* — and 2026-10-25 (photos): *"Make a
|
|
8
|
+
* dropzone in photos app for me to symlink to folders to ingest like we do in collections app."*
|
|
9
|
+
* Both apps wrote this file's contents for themselves, byte for byte (forge task 3752); it lives
|
|
10
|
+
* here so the third app that takes a link does not fork a third copy.
|
|
11
|
+
*
|
|
12
|
+
* What {@link scanDropzone} does with a link is in `scan.ts` (`followLinks`). This file is what it
|
|
13
|
+
* leans on, and what an app's own walk can use: telling an UNPLUGGED drive from a DELETED folder,
|
|
14
|
+
* turning Finder's aliases into symlinks, the link beside the app's code, and pacing a linked
|
|
15
|
+
* folder against the disk the bytes land on.
|
|
16
|
+
*/
|
|
17
|
+
import { existsSync, statSync, statfsSync } from "node:fs";
|
|
18
|
+
import { lstat, mkdir, open, readdir, readlink, rm, symlink } from "node:fs/promises";
|
|
19
|
+
import { dirname, join, relative } from "node:path";
|
|
20
|
+
|
|
21
|
+
// ── A drive that went away ───────────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
/*
|
|
24
|
+
* Owner, 2026-10-21: *"ensure there is graceful handling if the drive gets ejected early and
|
|
25
|
+
* plugged back in later. It should start from where it left off unless the source folder was
|
|
26
|
+
* deleted."* A link whose target is not there is one of two things, and they want opposite
|
|
27
|
+
* answers: the drive is unplugged (wait, quietly) or the folder is gone (say so).
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** Where a link points and why it cannot be followed right now. */
|
|
31
|
+
export type LinkSource =
|
|
32
|
+
| { state: "ok"; target: string }
|
|
33
|
+
| { state: "unmounted"; target: string; volume: string }
|
|
34
|
+
| { state: "deleted"; target: string };
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Is `dir` a mounted volume rather than the empty folder macOS can leave in `/Volumes` after an
|
|
38
|
+
* unclean eject? A mount point lives on a different device than the folder holding it.
|
|
39
|
+
*/
|
|
40
|
+
export function isMountPoint(dir: string): boolean {
|
|
41
|
+
try {
|
|
42
|
+
return statSync(dir).dev !== statSync(dirname(dir)).dev;
|
|
43
|
+
} catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Why a link's target is not there: its volume is not mounted (the drive is unplugged — wait), or
|
|
50
|
+
* the volume is there and the folder is not (it was deleted or moved — stop). A target outside
|
|
51
|
+
* `/Volumes` is on the boot disk, so missing means deleted.
|
|
52
|
+
*/
|
|
53
|
+
export function linkSource(target: string, mounted: (dir: string) => boolean = isMountPoint): LinkSource {
|
|
54
|
+
if (existsSync(target)) return { state: "ok", target };
|
|
55
|
+
const parts = target.split("/");
|
|
56
|
+
if (parts[1] === "Volumes" && parts[2]) {
|
|
57
|
+
const volume = `/Volumes/${parts[2]}`;
|
|
58
|
+
if (!mounted(volume)) return { state: "unmounted", target, volume };
|
|
59
|
+
}
|
|
60
|
+
return { state: "deleted", target };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A link's target as an absolute path (a relative link is relative to its own folder), or `null` when it is not a link. */
|
|
64
|
+
export async function linkTarget(path: string): Promise<string | null> {
|
|
65
|
+
const to = await readlink(path).catch(() => null);
|
|
66
|
+
if (to === null) return null;
|
|
67
|
+
return to.startsWith("/") ? to : join(dirname(path), to);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ── Finder aliases ───────────────────────────────────────────────────────────────────────
|
|
71
|
+
|
|
72
|
+
/** Every alias file (bookmark data) starts with these 16 bytes. Checked on this Mac, 2026-10-21. */
|
|
73
|
+
const ALIAS_MAGIC = "book\0\0\0\0mark\0\0\0\0";
|
|
74
|
+
/** Alias files are a few KB; nothing bigger is read to find out. */
|
|
75
|
+
const ALIAS_MAX_BYTES = 4 * 1024 * 1024;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Is this file a Finder alias rather than content? Finder's "Make Alias" (⌘⌥-drag) does not make
|
|
79
|
+
* a symlink: it makes an ordinary FILE of bookmark data, which a sweep would otherwise upload as
|
|
80
|
+
* content and delete.
|
|
81
|
+
*/
|
|
82
|
+
export async function isFinderAlias(path: string, size: number): Promise<boolean> {
|
|
83
|
+
if (size < ALIAS_MAGIC.length || size > ALIAS_MAX_BYTES) return false;
|
|
84
|
+
const handle = await open(path, "r").catch(() => null);
|
|
85
|
+
if (!handle) return false;
|
|
86
|
+
try {
|
|
87
|
+
const head = Buffer.alloc(ALIAS_MAGIC.length);
|
|
88
|
+
await handle.read(head, 0, head.length, 0);
|
|
89
|
+
return head.toString("latin1") === ALIAS_MAGIC;
|
|
90
|
+
} finally {
|
|
91
|
+
await handle.close();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Resolve an alias to the path it points at, or `null`. Foundation through JXA: no Finder, no
|
|
97
|
+
* Apple Events permission, no UI, and it never mounts a volume (a launchd job must not).
|
|
98
|
+
*/
|
|
99
|
+
export function resolveFinderAlias(path: string): string | null {
|
|
100
|
+
const script =
|
|
101
|
+
'function run(argv){ObjC.import("Foundation");' +
|
|
102
|
+
"const u=$.NSURL.URLByResolvingAliasFileAtURLOptionsError($.NSURL.fileURLWithPath(argv[0]),(1<<8)|(1<<9),null);" +
|
|
103
|
+
'return u.isNil()?"":u.path.js;}';
|
|
104
|
+
const proc = Bun.spawnSync(["osascript", "-l", "JavaScript", "-e", script, path], { stdout: "pipe", stderr: "pipe" });
|
|
105
|
+
const target = proc.exitCode === 0 ? proc.stdout.toString().trim() : "";
|
|
106
|
+
return target && target !== path ? target : null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface AliasAdoption {
|
|
110
|
+
/** `<relative path> → <target>` for each alias now a symlink. */
|
|
111
|
+
linked: string[];
|
|
112
|
+
/** Aliases that could not be resolved (the drive is not mounted) — left as they are; a walk must not ingest them. */
|
|
113
|
+
unresolved: string[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Is `name` one of `names`, as APFS compares — a dropped `Dups/` IS `dups/`? */
|
|
117
|
+
export const namedIn = (names: readonly string[] | undefined, name: string): boolean =>
|
|
118
|
+
names?.some((n) => n.toLowerCase() === name.toLowerCase()) ?? false;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Swap each Finder alias under `root` for a symlink to its target, so a walk with `followLinks`
|
|
122
|
+
* takes it as a linked source. Never looks in a hidden folder, through an existing link, or in a
|
|
123
|
+
* folder `skipTopDirs` names directly under `root` (an app's quarantine, its `done/`).
|
|
124
|
+
*/
|
|
125
|
+
export async function adoptFinderAliases(
|
|
126
|
+
root: string,
|
|
127
|
+
opts: { dryRun?: boolean; resolve?: (path: string) => string | null; skipTopDirs?: readonly string[] } = {},
|
|
128
|
+
): Promise<AliasAdoption> {
|
|
129
|
+
const resolve = opts.resolve ?? resolveFinderAlias;
|
|
130
|
+
const result: AliasAdoption = { linked: [], unresolved: [] };
|
|
131
|
+
const walk = async (dir: string): Promise<void> => {
|
|
132
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
133
|
+
for (const entry of entries) {
|
|
134
|
+
const full = join(dir, entry.name);
|
|
135
|
+
if (entry.name.startsWith(".")) continue;
|
|
136
|
+
if (entry.isDirectory()) {
|
|
137
|
+
if (dir === root && namedIn(opts.skipTopDirs, entry.name)) continue;
|
|
138
|
+
await walk(full);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (!entry.isFile()) continue;
|
|
142
|
+
const info = await lstat(full).catch(() => null);
|
|
143
|
+
if (!info || !(await isFinderAlias(full, info.size))) continue;
|
|
144
|
+
const rel = relative(root, full);
|
|
145
|
+
const target = resolve(full);
|
|
146
|
+
if (!target) {
|
|
147
|
+
result.unresolved.push(rel);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (!opts.dryRun) {
|
|
151
|
+
await rm(full);
|
|
152
|
+
await symlink(target, full);
|
|
153
|
+
}
|
|
154
|
+
result.linked.push(`${rel} → ${target}`);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
await walk(root);
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ── The link beside the app's code ───────────────────────────────────────────────────────
|
|
162
|
+
|
|
163
|
+
/** What the owner opens next to an app's code — a link to its drop folder, never the files. */
|
|
164
|
+
export const DROPZONE_LINK = "dropzone";
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The link next to the app's code that opens the drop folder — the place the owner will look.
|
|
168
|
+
*
|
|
169
|
+
* 🔴 A LINK, and the files stay in `$FORGE_STATE`. A drop is data, often gigabytes of it, and a
|
|
170
|
+
* code tree is walked by every check, bundler and test its repo runs; the link is gitignored, and
|
|
171
|
+
* `tools/check-paths.ts` never follows a link into a directory. Something real already at that
|
|
172
|
+
* name is left alone and said. Returns what it did, or `null` when the link was already right.
|
|
173
|
+
*/
|
|
174
|
+
export async function ensureDropzoneLink(appDir: string, root: string): Promise<string | null> {
|
|
175
|
+
const at = join(appDir, DROPZONE_LINK);
|
|
176
|
+
const info = await lstat(at).catch(() => null);
|
|
177
|
+
if (info && !info.isSymbolicLink()) return `${at} exists and is not a link — left alone`;
|
|
178
|
+
if (info && (await readlink(at)) === root) return null;
|
|
179
|
+
if (info) await rm(at);
|
|
180
|
+
await mkdir(root, { recursive: true });
|
|
181
|
+
await symlink(root, at);
|
|
182
|
+
return `linked ${at} → ${root}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ── Pacing: the store is the boot disk ───────────────────────────────────────────────────
|
|
186
|
+
|
|
187
|
+
/*
|
|
188
|
+
* A link can put far more behind it than the Mac has room for. Measured 2026-10-21: collections'
|
|
189
|
+
* `tod` folder was 196 GiB with 212 GiB free on the boot volume, while binary-server's bytes land
|
|
190
|
+
* on this Mac and leave for B2 at most 50 GB a day (binary-server `src/b2Sweep.ts`). A linked file
|
|
191
|
+
* is only taken while the store would keep {@link LINKED_FREE_FLOOR_BYTES} free after it and its
|
|
192
|
+
* derivatives — and derivatives are built AFTER the upload, so free space alone lies for a while:
|
|
193
|
+
* what was linked in the last {@link LINKED_OWED_WINDOW_MS} counts as still owing them. Dropped
|
|
194
|
+
* files are not paced: they are already on this disk.
|
|
195
|
+
*/
|
|
196
|
+
|
|
197
|
+
/** The store keeps at least this much free after a linked file and its derivatives land. */
|
|
198
|
+
export const LINKED_FREE_FLOOR_BYTES = 40 * 1024 ** 3;
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* How long a linked file is assumed to still owe its derivatives after it was filed. A day: the
|
|
202
|
+
* ladders for a ~50 GB batch took ~17 h at the measured 3.2 GB an hour, and past that they are on
|
|
203
|
+
* the disk, where free space already counts them — a longer window counts them twice.
|
|
204
|
+
*/
|
|
205
|
+
export const LINKED_OWED_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Bytes a linked file may still use on the store's volume, or `null` when it cannot be told
|
|
209
|
+
* (which holds nothing back — binary-server keeps its own floor). `owedBytes` is what the
|
|
210
|
+
* derivatives of recently linked files still have to take.
|
|
211
|
+
*/
|
|
212
|
+
export function linkedRoomBytes(storeDir: string, owedBytes = 0): number | null {
|
|
213
|
+
try {
|
|
214
|
+
const fs = statfsSync(storeDir);
|
|
215
|
+
return Number(fs.bavail) * Number(fs.bsize) - LINKED_FREE_FLOOR_BYTES - owedBytes;
|
|
216
|
+
} catch {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
|
2
|
-
import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import {
|
|
@@ -253,3 +253,34 @@ describe("pruneEmptyDirs", () => {
|
|
|
253
253
|
expect(existsSync(join(root, "a/b/keep.txt"))).toBe(true);
|
|
254
254
|
});
|
|
255
255
|
});
|
|
256
|
+
|
|
257
|
+
describe("pruneEmptyDirs never enters a link (forge task 3752)", () => {
|
|
258
|
+
let drive: string;
|
|
259
|
+
beforeEach(() => {
|
|
260
|
+
drive = mkdtempSync(join(tmpdir(), "dropzone-spec-drive-"));
|
|
261
|
+
});
|
|
262
|
+
afterEach(() => rmSync(drive, { recursive: true, force: true }));
|
|
263
|
+
|
|
264
|
+
test("🔴 an empty folder behind a link survives a prune", async () => {
|
|
265
|
+
mkdirSync(join(drive, "Empty Album", "Disc 2"), { recursive: true });
|
|
266
|
+
symlinkSync(drive, join(root, "linked"));
|
|
267
|
+
mkdirSync(join(root, "dropped", "empty"), { recursive: true });
|
|
268
|
+
|
|
269
|
+
await pruneEmptyDirs(root);
|
|
270
|
+
|
|
271
|
+
expect(existsSync(join(drive, "Empty Album", "Disc 2"))).toBe(true);
|
|
272
|
+
expect(lstatSync(join(root, "linked")).isSymbolicLink()).toBe(true);
|
|
273
|
+
expect(existsSync(join(root, "dropped"))).toBe(false); // the drop folder's own empties still go
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
test("a folder holding only Finder's bookkeeping is empty, and goes", async () => {
|
|
277
|
+
write("watched/.DS_Store");
|
|
278
|
+
write("watched/._a.jpg");
|
|
279
|
+
write("kept/.DS_Store");
|
|
280
|
+
write("kept/held.mp3");
|
|
281
|
+
await pruneEmptyDirs(root);
|
|
282
|
+
expect(existsSync(join(root, "watched"))).toBe(false);
|
|
283
|
+
expect(existsSync(join(root, "kept", "held.mp3"))).toBe(true);
|
|
284
|
+
expect(existsSync(join(root, "kept", ".DS_Store"))).toBe(true);
|
|
285
|
+
});
|
|
286
|
+
});
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
* 1. **A file is deleted only after the destination CONFIRMS it.** The dropzone is the one
|
|
20
20
|
* place the owner's copy may be the only copy: they dragged it in expecting it to be taken.
|
|
21
21
|
* A sweep that deletes on "the upload didn't throw" turns any catalog failure into data
|
|
22
|
-
* loss. The handler returns `stored`/`duplicate` and only then does the original go.
|
|
22
|
+
* loss. The handler returns `stored`/`duplicate` and only then does the original go. A file
|
|
23
|
+
* reached through a LINK is never deleted at all: it is the owner's copy where it lives.
|
|
23
24
|
*
|
|
24
25
|
* 2. **A file must measure the same size twice before it is touched.** Dropping a 4 GB video
|
|
25
26
|
* into a folder is not atomic. Without this the sweep ingests a truncated file, reports
|
|
@@ -33,8 +34,9 @@
|
|
|
33
34
|
*/
|
|
34
35
|
|
|
35
36
|
import type { Dirent } from "node:fs";
|
|
36
|
-
import { readdir, rm, rmdir, stat } from "node:fs/promises";
|
|
37
|
+
import { lstat, readdir, realpath, rm, rmdir, stat } from "node:fs/promises";
|
|
37
38
|
import { join, relative } from "node:path";
|
|
39
|
+
import { type LinkSource, linkSource, linkTarget, namedIn } from "./links.js";
|
|
38
40
|
import type { IngestReporter, ReportFile, ReportResult } from "./report.js";
|
|
39
41
|
|
|
40
42
|
/** A file the sweep found, with everything a handler needs to decide about it. */
|
|
@@ -51,10 +53,16 @@ export interface DroppedFile {
|
|
|
51
53
|
mtimeMs: number;
|
|
52
54
|
/** Every other FILE name in the same directory — see {@link ScanOptions.captureSiblings}. */
|
|
53
55
|
siblings: string[];
|
|
56
|
+
/**
|
|
57
|
+
* Reached through a symlink (`followLinks`): the owner's own copy, where it lives. A sweep
|
|
58
|
+
* never deletes one, whatever the handler answers — see rule 1. `realPath` is what an app keys
|
|
59
|
+
* it on, so renaming the link neither re-reads the drive nor files anything twice.
|
|
60
|
+
*/
|
|
61
|
+
linked?: { realPath: string };
|
|
54
62
|
}
|
|
55
63
|
|
|
56
64
|
export type DropOutcome =
|
|
57
|
-
/** Filed successfully. The original is deleted. */
|
|
65
|
+
/** Filed successfully. The original is deleted — unless it is `linked`, which stays where it is. */
|
|
58
66
|
| { kind: "stored"; detail?: string }
|
|
59
67
|
/** Already present at the destination. The original is deleted — that is the point. */
|
|
60
68
|
| { kind: "duplicate"; detail?: string }
|
|
@@ -76,7 +84,11 @@ export interface SweepReport {
|
|
|
76
84
|
unstable: string[];
|
|
77
85
|
bytesRemoved: number;
|
|
78
86
|
emptyDirsRemoved: number;
|
|
79
|
-
/**
|
|
87
|
+
/** Linked files dealt with and LEFT IN PLACE — the owner's copy on their own drive (`followLinks`). */
|
|
88
|
+
leftInPlace: number;
|
|
89
|
+
/** Links whose target is not there this sweep — a drive unplugged, or a folder gone (`followLinks`). */
|
|
90
|
+
unreachable: UnreachableLink[];
|
|
91
|
+
/** Anything left in the root when the sweep finished, links not followed. Empty is the goal. */
|
|
80
92
|
remaining: number;
|
|
81
93
|
}
|
|
82
94
|
|
|
@@ -97,6 +109,16 @@ export interface ScanOptions {
|
|
|
97
109
|
captureSiblings?: boolean;
|
|
98
110
|
/** Directory names to skip entirely at any depth (another app's queue, our own state). */
|
|
99
111
|
skipDirs?: string[];
|
|
112
|
+
/**
|
|
113
|
+
* Directory names skipped only directly under the root, compared as APFS does (case-insensitive)
|
|
114
|
+
* — an app's quarantine or `done/`, a name that is the owner's own inside a linked folder.
|
|
115
|
+
*/
|
|
116
|
+
skipTopDirs?: readonly string[];
|
|
117
|
+
/**
|
|
118
|
+
* Walk THROUGH symlinks: a linked folder is ingested in place (`links.ts`). Off by default, so
|
|
119
|
+
* no consumer changes behavior unasked. See {@link walkDropzone}.
|
|
120
|
+
*/
|
|
121
|
+
followLinks?: boolean;
|
|
100
122
|
/** Stop after this many files. Absent means everything. */
|
|
101
123
|
limit?: number;
|
|
102
124
|
}
|
|
@@ -128,6 +150,26 @@ const extOf = (name: string): string => {
|
|
|
128
150
|
return dot > 0 ? name.slice(dot).toLowerCase() : "";
|
|
129
151
|
};
|
|
130
152
|
|
|
153
|
+
/** A symlink the walk met whose target is not there this pass. */
|
|
154
|
+
export interface UnreachableLink {
|
|
155
|
+
/** The link, relative to the dropzone root. */
|
|
156
|
+
relativePath: string;
|
|
157
|
+
/** The link, absolute. */
|
|
158
|
+
path: string;
|
|
159
|
+
/**
|
|
160
|
+
* The link is in the dropzone's OWN tree (the owner put it there), not one met inside a linked
|
|
161
|
+
* folder on the owner's drive. Only an app's own link is ever its to act on.
|
|
162
|
+
*/
|
|
163
|
+
inDropzone: boolean;
|
|
164
|
+
source: Exclude<LinkSource, { state: "ok" }>;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** One walk: the files, and — with `followLinks` — the links that could not be followed. */
|
|
168
|
+
export interface DropzoneScan {
|
|
169
|
+
files: DroppedFile[];
|
|
170
|
+
unreachable: UnreachableLink[];
|
|
171
|
+
}
|
|
172
|
+
|
|
131
173
|
/**
|
|
132
174
|
* Every candidate file under `root`, deepest-last, with each one's sibling listing.
|
|
133
175
|
*
|
|
@@ -136,11 +178,55 @@ const extOf = (name: string): string => {
|
|
|
136
178
|
* {@link isJunkName} is exported so a handler can classify without re-deriving the list.
|
|
137
179
|
*/
|
|
138
180
|
export async function scanDropzone(root: string, opts: ScanOptions = {}): Promise<DroppedFile[]> {
|
|
181
|
+
return (await walkDropzone(root, opts)).files;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* {@link scanDropzone}, with the links it could not follow.
|
|
186
|
+
*
|
|
187
|
+
* Without `followLinks` a symlink is skipped, as it always was. With it, a link to a directory is
|
|
188
|
+
* walked — once per REAL path, so a loop, or two links to one folder, or a link back into the
|
|
189
|
+
* dropzone, is not walked twice — and a link to a file is one file; everything reached through a
|
|
190
|
+
* link carries `linked`. A link whose target is missing is returned under `unreachable`, told
|
|
191
|
+
* apart by {@link linkSource}: `unmounted` (wait) or `deleted` (say so). A dangling link INSIDE a
|
|
192
|
+
* linked folder is the owner's drive's business; it is returned too, with `inDropzone: false`.
|
|
193
|
+
*/
|
|
194
|
+
export async function walkDropzone(root: string, opts: ScanOptions = {}): Promise<DropzoneScan> {
|
|
139
195
|
const skip = new Set(opts.skipDirs ?? []);
|
|
140
196
|
const out: DroppedFile[] = [];
|
|
197
|
+
const unreachable: UnreachableLink[] = [];
|
|
198
|
+
const walked = new Set<string>();
|
|
199
|
+
const full = (n: number): boolean => opts.limit !== undefined && n >= opts.limit;
|
|
200
|
+
|
|
201
|
+
const push = async (path: string, name: string, siblings: string[], linked: boolean): Promise<void> => {
|
|
202
|
+
try {
|
|
203
|
+
const info = await stat(path);
|
|
204
|
+
out.push({
|
|
205
|
+
path,
|
|
206
|
+
relativePath: relative(root, path),
|
|
207
|
+
name,
|
|
208
|
+
ext: extOf(name),
|
|
209
|
+
size: info.size,
|
|
210
|
+
mtimeMs: info.mtimeMs,
|
|
211
|
+
siblings,
|
|
212
|
+
...(linked ? { linked: { realPath: await realpath(path) } } : {}),
|
|
213
|
+
});
|
|
214
|
+
} catch {
|
|
215
|
+
/* gone between readdir and stat */
|
|
216
|
+
}
|
|
217
|
+
};
|
|
141
218
|
|
|
142
|
-
|
|
143
|
-
|
|
219
|
+
/** `false` when this directory's real path was already walked — the one way a link loops. */
|
|
220
|
+
const firstVisit = async (dir: string): Promise<boolean> => {
|
|
221
|
+
if (!opts.followLinks) return true;
|
|
222
|
+
const real = await realpath(dir).catch(() => null);
|
|
223
|
+
if (!real || walked.has(real)) return false;
|
|
224
|
+
walked.add(real);
|
|
225
|
+
return true;
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const walk = async (dir: string, linked: boolean): Promise<void> => {
|
|
229
|
+
if (full(out.length)) return;
|
|
144
230
|
let entries: Dirent[];
|
|
145
231
|
try {
|
|
146
232
|
entries = await readdir(dir, { withFileTypes: true });
|
|
@@ -152,33 +238,38 @@ export async function scanDropzone(root: string, opts: ScanOptions = {}): Promis
|
|
|
152
238
|
: [];
|
|
153
239
|
|
|
154
240
|
for (const entry of entries) {
|
|
155
|
-
if (
|
|
156
|
-
const
|
|
157
|
-
|
|
241
|
+
if (full(out.length)) return;
|
|
242
|
+
const path = join(dir, entry.name);
|
|
243
|
+
let isDir = entry.isDirectory();
|
|
244
|
+
let isFile = entry.isFile();
|
|
245
|
+
let viaLink = linked;
|
|
246
|
+
if (entry.isSymbolicLink()) {
|
|
247
|
+
if (!opts.followLinks) continue;
|
|
248
|
+
const target = await stat(path).catch(() => null);
|
|
249
|
+
if (!target) {
|
|
250
|
+
const source = linkSource((await linkTarget(path)) ?? path);
|
|
251
|
+
if (source.state !== "ok")
|
|
252
|
+
unreachable.push({ relativePath: relative(root, path), path, inDropzone: !linked, source });
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
isDir = target.isDirectory();
|
|
256
|
+
isFile = target.isFile();
|
|
257
|
+
viaLink = true;
|
|
258
|
+
}
|
|
259
|
+
if (isDir) {
|
|
158
260
|
if (skip.has(entry.name)) continue;
|
|
159
|
-
|
|
261
|
+
if (dir === root && namedIn(opts.skipTopDirs, entry.name)) continue;
|
|
262
|
+
if (!(await firstVisit(path))) continue;
|
|
263
|
+
await walk(path, viaLink);
|
|
160
264
|
continue;
|
|
161
265
|
}
|
|
162
|
-
if (
|
|
163
|
-
try {
|
|
164
|
-
const info = await stat(full);
|
|
165
|
-
out.push({
|
|
166
|
-
path: full,
|
|
167
|
-
relativePath: relative(root, full),
|
|
168
|
-
name: entry.name,
|
|
169
|
-
ext: extOf(entry.name),
|
|
170
|
-
size: info.size,
|
|
171
|
-
mtimeMs: info.mtimeMs,
|
|
172
|
-
siblings,
|
|
173
|
-
});
|
|
174
|
-
} catch {
|
|
175
|
-
/* gone between readdir and stat */
|
|
176
|
-
}
|
|
266
|
+
if (isFile) await push(path, entry.name, siblings, viaLink);
|
|
177
267
|
}
|
|
178
268
|
};
|
|
179
269
|
|
|
180
|
-
await
|
|
181
|
-
|
|
270
|
+
if (opts.followLinks) await firstVisit(root);
|
|
271
|
+
await walk(root, false);
|
|
272
|
+
return { files: out, unreachable };
|
|
182
273
|
}
|
|
183
274
|
|
|
184
275
|
/**
|
|
@@ -221,6 +312,11 @@ export async function isStable(file: DroppedFile, stabilityMs = 750): Promise<bo
|
|
|
221
312
|
* recursive delete here would take a file the sweep deliberately chose not to ingest — a held
|
|
222
313
|
* duplicate, a failure left in place for the owner to look at — which is precisely the set of
|
|
223
314
|
* files that must survive.
|
|
315
|
+
*
|
|
316
|
+
* 🔴 `lstat`, never `stat`: a symlink is a linked source, and following it would `rmdir` every
|
|
317
|
+
* empty folder on the owner's own drive (collections met exactly this, 2026-10-21). The one thing
|
|
318
|
+
* removed first is Finder's bookkeeping (`.DS_Store`, `._*`): Finder writes one into every folder
|
|
319
|
+
* the owner LOOKS at, and without this a tree they watched go in stays behind as empty shells.
|
|
224
320
|
*/
|
|
225
321
|
export async function pruneEmptyDirs(root: string, dir = root): Promise<number> {
|
|
226
322
|
let removed = 0;
|
|
@@ -233,13 +329,16 @@ export async function pruneEmptyDirs(root: string, dir = root): Promise<number>
|
|
|
233
329
|
for (const name of entries) {
|
|
234
330
|
const full = join(dir, name);
|
|
235
331
|
try {
|
|
236
|
-
if ((await
|
|
332
|
+
if ((await lstat(full)).isDirectory()) removed += await pruneEmptyDirs(root, full);
|
|
237
333
|
} catch {
|
|
238
334
|
/* gone */
|
|
239
335
|
}
|
|
240
336
|
}
|
|
241
337
|
if (dir === root) return removed;
|
|
242
338
|
try {
|
|
339
|
+
const left = await readdir(dir);
|
|
340
|
+
if (left.length > 0 && left.every(isFinderBookkeeping))
|
|
341
|
+
for (const name of left) await rm(join(dir, name)).catch(() => undefined);
|
|
243
342
|
await rmdir(dir);
|
|
244
343
|
return removed + 1;
|
|
245
344
|
} catch {
|
|
@@ -247,6 +346,8 @@ export async function pruneEmptyDirs(root: string, dir = root): Promise<number>
|
|
|
247
346
|
}
|
|
248
347
|
}
|
|
249
348
|
|
|
349
|
+
const isFinderBookkeeping = (name: string): boolean => name === ".DS_Store" || name.startsWith("._");
|
|
350
|
+
|
|
250
351
|
/**
|
|
251
352
|
* What the app supplies: what to do with one file. `uploading(key)` names the binary-server key its
|
|
252
353
|
* bytes stage under, once the handler knows it — station's Uploads page shows that transfer's own
|
|
@@ -325,11 +426,14 @@ async function sweep(
|
|
|
325
426
|
unstable: [],
|
|
326
427
|
bytesRemoved: 0,
|
|
327
428
|
emptyDirsRemoved: 0,
|
|
429
|
+
leftInPlace: 0,
|
|
430
|
+
unreachable: [],
|
|
328
431
|
remaining: 0,
|
|
329
432
|
};
|
|
330
433
|
|
|
331
434
|
reporter?.walking();
|
|
332
|
-
const files = await
|
|
435
|
+
const { files, unreachable } = await walkDropzone(root, opts);
|
|
436
|
+
report.unreachable = unreachable;
|
|
333
437
|
reporter?.found(files.map(as));
|
|
334
438
|
for (const [index, file] of files.entries()) {
|
|
335
439
|
report.scanned++;
|
|
@@ -366,6 +470,12 @@ async function sweep(
|
|
|
366
470
|
else if (outcome.kind === "duplicate") report.duplicate++;
|
|
367
471
|
else report.discarded++;
|
|
368
472
|
if (opts.dryRun) break;
|
|
473
|
+
// Rule 1, for a link: the destination confirming it is not permission to delete the
|
|
474
|
+
// owner's copy on their own drive. Stored, and left where it lives.
|
|
475
|
+
if (file.linked) {
|
|
476
|
+
report.leftInPlace++;
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
369
479
|
try {
|
|
370
480
|
await rm(file.path);
|
|
371
481
|
report.bytesRemoved += file.size;
|
|
@@ -391,7 +501,7 @@ async function sweep(
|
|
|
391
501
|
}
|
|
392
502
|
|
|
393
503
|
if (!opts.dryRun) report.emptyDirsRemoved = await pruneEmptyDirs(root);
|
|
394
|
-
report.remaining = (await scanDropzone(root, { skipDirs: opts.skipDirs })).length;
|
|
504
|
+
report.remaining = (await scanDropzone(root, { skipDirs: opts.skipDirs, skipTopDirs: opts.skipTopDirs })).length;
|
|
395
505
|
return report;
|
|
396
506
|
}
|
|
397
507
|
|
|
@@ -399,6 +509,8 @@ async function sweep(
|
|
|
399
509
|
export const describeSweep = (report: SweepReport): string =>
|
|
400
510
|
`${report.stored} added, ${report.duplicate} already had, ${report.discarded} discarded, ` +
|
|
401
511
|
`${report.held} held, ${report.failed.length} failed, ${report.unstable.length} still copying` +
|
|
512
|
+
(report.leftInPlace > 0 ? ` · ${report.leftInPlace} linked file(s) left in place` : "") +
|
|
513
|
+
(report.unreachable.length > 0 ? ` · ${report.unreachable.length} link(s) not reachable` : "") +
|
|
402
514
|
(report.bytesRemoved > 0
|
|
403
515
|
? ` · ${(report.bytesRemoved / 1024 ** 3).toFixed(2)} GB freed from the queue`
|
|
404
516
|
: "") +
|
|
@@ -76,6 +76,8 @@
|
|
|
76
76
|
* a test that scans for Google hosts outside it) and both doors consume this.
|
|
77
77
|
*/
|
|
78
78
|
|
|
79
|
+
import type { D1LikeDatabase } from '../d1/types.js';
|
|
80
|
+
|
|
79
81
|
/** Where the counter lives. A tiny KV, so an app can back it with whatever
|
|
80
82
|
* durable store it already has — `apps/orch` uses its own settings store,
|
|
81
83
|
* `apps/family` uses the `meta` table of the database it already opens. */
|
|
@@ -302,3 +304,77 @@ export function createMapsBudget<Api extends string>(
|
|
|
302
304
|
},
|
|
303
305
|
};
|
|
304
306
|
}
|
|
307
|
+
|
|
308
|
+
/** What {@link createMetaTableBudget} hands back: the same check-and-count, awaited. */
|
|
309
|
+
export interface AsyncMapsBudget<Api extends string> {
|
|
310
|
+
consume(api: Api, calls?: number): Promise<BudgetVerdict>;
|
|
311
|
+
/** Every API in the ceilings, for a health surface — a roster read, so an API added to
|
|
312
|
+
* the ceilings cannot be missed by a surface that asks for each one by name. */
|
|
313
|
+
usage(): Promise<ReturnType<MapsBudget<Api>['usage']>[]>;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The ceiling over an app's own two-column `meta (key, value)` table on D1 or bun:sqlite —
|
|
318
|
+
* family's adapter, lifted when photos became the second app to need it (forge task 3700).
|
|
319
|
+
*
|
|
320
|
+
* 🔴 The package's store is SYNCHRONOUS by contract and D1 is not. So the counters are read
|
|
321
|
+
* into a snapshot before each decision (one query for every `maps-budget.*` row) and the
|
|
322
|
+
* ceiling decides over the snapshot. The write goes back as a DELTA (`value + n`), never the
|
|
323
|
+
* absolute number: two requests in two isolates each read 10 and each count one, and an
|
|
324
|
+
* absolute write would leave 11 where 12 is true. A spend ceiling that can lose increments
|
|
325
|
+
* under load is the one kind that cannot be trusted.
|
|
326
|
+
*/
|
|
327
|
+
export function createMetaTableBudget<Api extends string>(
|
|
328
|
+
db: Pick<D1LikeDatabase, 'prepare' | 'batch'>,
|
|
329
|
+
options: Omit<MapsBudgetOptions<Api>, 'store'>,
|
|
330
|
+
): AsyncMapsBudget<Api> {
|
|
331
|
+
const snapshot = new Map<string, string>();
|
|
332
|
+
const loaded = new Map<string, number>();
|
|
333
|
+
const sync = async (): Promise<void> => {
|
|
334
|
+
snapshot.clear();
|
|
335
|
+
loaded.clear();
|
|
336
|
+
const rows = await db.prepare("SELECT key, value FROM meta WHERE key LIKE 'maps-budget.%'").all<{ key: string; value: string }>();
|
|
337
|
+
for (const row of rows.results) {
|
|
338
|
+
snapshot.set(row.key, row.value);
|
|
339
|
+
loaded.set(row.key, Number(row.value) || 0);
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
const flush = async (): Promise<void> => {
|
|
343
|
+
const writes = [...snapshot]
|
|
344
|
+
.map(([key, value]) => ({ key, delta: (Number(value) || 0) - (loaded.get(key) ?? 0) }))
|
|
345
|
+
.filter((entry) => entry.delta !== 0);
|
|
346
|
+
if (writes.length === 0) return;
|
|
347
|
+
await db.batch(
|
|
348
|
+
writes.map(({ key, delta }) =>
|
|
349
|
+
db
|
|
350
|
+
.prepare(
|
|
351
|
+
`INSERT INTO meta (key, value) VALUES (?1, CAST(?2 AS TEXT))
|
|
352
|
+
ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + ?2 AS TEXT)`,
|
|
353
|
+
)
|
|
354
|
+
.bind(key, delta),
|
|
355
|
+
),
|
|
356
|
+
);
|
|
357
|
+
};
|
|
358
|
+
const budget = createMapsBudget<Api>({
|
|
359
|
+
...options,
|
|
360
|
+
store: {
|
|
361
|
+
read: (key) => snapshot.get(key) ?? null,
|
|
362
|
+
write: (key, value) => {
|
|
363
|
+
snapshot.set(key, value);
|
|
364
|
+
},
|
|
365
|
+
},
|
|
366
|
+
});
|
|
367
|
+
const apis = Object.keys(options.ceilings) as Api[];
|
|
368
|
+
return {
|
|
369
|
+
consume: async (api, calls) => {
|
|
370
|
+
await sync();
|
|
371
|
+
const verdict = budget.consume(api, calls);
|
|
372
|
+
await flush();
|
|
373
|
+
return verdict;
|
|
374
|
+
},
|
|
375
|
+
usage: async () => {
|
|
376
|
+
await sync();
|
|
377
|
+
return apis.map((api) => budget.usage(api));
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import { describe, expect, it } from 'bun:test';
|
|
3
|
+
import { createLocalD1 } from '../d1/local.js';
|
|
4
|
+
import { createMetaTableBudget } from './mapsBudget.js';
|
|
5
|
+
|
|
6
|
+
const open = () => {
|
|
7
|
+
const sqlite = new Database(':memory:');
|
|
8
|
+
sqlite.run('CREATE TABLE meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL )');
|
|
9
|
+
return { sqlite, db: createLocalD1(sqlite) };
|
|
10
|
+
};
|
|
11
|
+
const AT = Date.UTC(2026, 9, 15, 12);
|
|
12
|
+
const options = { ceilings: { staticmap: 20 }, refusal: () => ({ reason: 'over' }), now: () => AT };
|
|
13
|
+
|
|
14
|
+
describe('createMetaTableBudget — the ceiling over an app meta table', () => {
|
|
15
|
+
it('counts in the table, and a refusal counts nothing', async () => {
|
|
16
|
+
const { db } = open();
|
|
17
|
+
const budget = createMetaTableBudget<'staticmap'>(db, options);
|
|
18
|
+
for (let i = 0; i < 2; i++) expect((await budget.consume('staticmap')).allowed).toBe(true);
|
|
19
|
+
// The daily line is a tenth of the month's: 2 of 2 used, so the third is refused.
|
|
20
|
+
expect((await budget.consume('staticmap')).allowed).toBe(false);
|
|
21
|
+
const [usage] = await budget.usage();
|
|
22
|
+
expect(usage?.used).toBe(2);
|
|
23
|
+
expect(usage?.day.used).toBe(2);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('🔴 writes a DELTA, so two isolates counting at once lose nothing', async () => {
|
|
27
|
+
const { db, sqlite } = open();
|
|
28
|
+
const one = createMetaTableBudget<'staticmap'>(db, options);
|
|
29
|
+
const two = createMetaTableBudget<'staticmap'>(db, options);
|
|
30
|
+
await Promise.all([one.consume('staticmap'), two.consume('staticmap')]);
|
|
31
|
+
const rows = sqlite.query("SELECT value FROM meta WHERE key LIKE 'maps-budget.staticmap.%'").all() as { value: string }[];
|
|
32
|
+
expect(rows.map((row) => Number(row.value))).toEqual([2, 2]);
|
|
33
|
+
});
|
|
34
|
+
});
|