agent-cleandrive 0.0.0-stage → 0.2.2
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/LICENSE +21 -0
- package/README.md +272 -2
- package/bin/cleandrive.js +190 -0
- package/config.example.json +33 -0
- package/docs/offload-strategy.md +132 -0
- package/lib/actions.js +215 -0
- package/lib/offload.js +472 -0
- package/lib/scan.js +253 -0
- package/lib/server.js +208 -0
- package/lib/util.js +118 -0
- package/package.json +60 -4
- package/ui/index.html +489 -0
package/lib/offload.js
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
// offload / fetch: iCloud-style switch between a local file and a verified copy on
|
|
2
|
+
// the remote archive drive. No daemon anywhere: every step runs
|
|
3
|
+
// inside one command over on-demand ssh/rsync. Design + invariants:
|
|
4
|
+
// docs/offload-strategy.md. The rule that matters most: the local file is only
|
|
5
|
+
// unlinked after the remote copy's sha256 matches AND the local file is unchanged.
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import {
|
|
8
|
+
createReadStream, lstatSync, statSync, realpathSync, readdirSync, readFileSync, existsSync,
|
|
9
|
+
unlinkSync, renameSync, utimesSync, statfsSync,
|
|
10
|
+
} from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import {
|
|
13
|
+
HOME, DATA_DIR, loadConfig, readJson, writeJson, writeFileAtomic, run, ensureDataDir, expandHome,
|
|
14
|
+
} from './util.js';
|
|
15
|
+
import { checkRemoteDrive, sshOpts, log } from './actions.js';
|
|
16
|
+
|
|
17
|
+
export const STUB_EXT = '.cloud';
|
|
18
|
+
const INDEX_FILE = path.join(DATA_DIR, 'offloaded.json');
|
|
19
|
+
const CANDIDATES_FILE = path.join(DATA_DIR, 'offload-candidates.json');
|
|
20
|
+
const LOCK_FILE = path.join(DATA_DIR, 'offload.lock');
|
|
21
|
+
|
|
22
|
+
// Never offload from here: app data, libraries other software owns, VCS internals.
|
|
23
|
+
const NEVER_SEGMENTS = new Set(['.git', 'node_modules', '.Trash', '.venv']);
|
|
24
|
+
const NEVER_SUFFIXES = ['.photoslibrary', '.fcpbundle', '.imovielibrary', '.musiclibrary', '.tvlibrary', '.app'];
|
|
25
|
+
const MEDIA_EXT = new Set([
|
|
26
|
+
'mp4', 'mov', 'm4v', 'mkv', 'avi', 'webm', 'mts', 'm2ts', 'mpg', 'mpeg', 'wmv', 'flv', '3gp', 'braw', 'r3d',
|
|
27
|
+
'wav', 'aif', 'aiff', 'flac', 'm4a', 'caf',
|
|
28
|
+
'dmg', 'iso', 'img', 'zip', 'tar', 'gz', 'tgz', 'xz', 'bz2', '7z', 'rar',
|
|
29
|
+
'psd', 'psb', 'tif', 'tiff', 'cr2', 'cr3', 'nef', 'arw', 'dng',
|
|
30
|
+
]);
|
|
31
|
+
const DEFAULT_ROOTS = ['~/Movies', '~/Documents', '~/Desktop', '~/Downloads', '~/Pictures'];
|
|
32
|
+
|
|
33
|
+
// ---------- small helpers ----------
|
|
34
|
+
|
|
35
|
+
const opt = (cfg) => ({ retries: 5, timeoutSec: 120, ...(cfg.offload || {}) });
|
|
36
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
37
|
+
const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
38
|
+
const short = (p) => p.replace(HOME, '~');
|
|
39
|
+
|
|
40
|
+
export function sha256File(p) {
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
const h = createHash('sha256');
|
|
43
|
+
createReadStream(p).on('data', (d) => h.update(d)).on('error', reject).on('end', () => resolve(h.digest('hex')));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function remoteBase(cfg) {
|
|
48
|
+
const rpath = cfg.remote?.path;
|
|
49
|
+
if (!cfg.remote?.host || !rpath) throw new Error('remote not configured (config.remote.host/path)');
|
|
50
|
+
return rpath.replace(/\/$/, '') + '/offload';
|
|
51
|
+
}
|
|
52
|
+
const objectRel = (sha) => `objects/${sha.slice(0, 2)}/${sha}`;
|
|
53
|
+
const remoteDest = (cfg) => `${cfg.remote.user ? cfg.remote.user + '@' : ''}${cfg.remote.host}`;
|
|
54
|
+
// Keepalives make a hung Tailscale link fail fast instead of blocking forever.
|
|
55
|
+
const sshBase = (cfg) => ['-o', 'ConnectTimeout=10', '-o', 'BatchMode=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=4', ...sshOpts(cfg)];
|
|
56
|
+
|
|
57
|
+
function ssh(cfg, cmd) {
|
|
58
|
+
return run('ssh', [...sshBase(cfg), remoteDest(cfg), cmd]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function rsyncArgs(cfg) {
|
|
62
|
+
return ['--partial', `--timeout=${opt(cfg).timeoutSec}`, '-e', ['ssh', ...sshBase(cfg)].join(' ')];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function withRetry(cfg, label, fn, onData) {
|
|
66
|
+
const n = Math.max(1, opt(cfg).retries);
|
|
67
|
+
let last;
|
|
68
|
+
for (let i = 1; i <= n; i++) {
|
|
69
|
+
last = await fn();
|
|
70
|
+
if (last.code === 0) return last;
|
|
71
|
+
const why = (last.err || last.out || '').trim().split('\n').pop();
|
|
72
|
+
onData?.(` ${label}: attempt ${i}/${n} failed (exit ${last.code}) ${why}\n`);
|
|
73
|
+
if (i < n) await sleep(Math.min(60000, 5000 * 2 ** (i - 1)));
|
|
74
|
+
}
|
|
75
|
+
return last;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function remoteSha(cfg, rel) {
|
|
79
|
+
const r = await ssh(cfg, `test -f ${q(remoteBase(cfg) + '/' + rel)} && sha256sum -- ${q(remoteBase(cfg) + '/' + rel)}`);
|
|
80
|
+
if (r.code === 255) throw new Error('remote unreachable: ' + (r.err || '').trim().split('\n').pop());
|
|
81
|
+
if (r.code !== 0) return null; // missing
|
|
82
|
+
return r.out.trim().split(/\s+/)[0] || null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---------- index + pins ----------
|
|
86
|
+
|
|
87
|
+
export function loadIndex() {
|
|
88
|
+
return readJson(INDEX_FILE, { version: 1, files: {}, pins: [] });
|
|
89
|
+
}
|
|
90
|
+
function saveIndex(idx) {
|
|
91
|
+
ensureDataDir();
|
|
92
|
+
writeJson(INDEX_FILE, idx);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function setPin(p, pinned) {
|
|
96
|
+
const abs = path.resolve(expandHome(p));
|
|
97
|
+
const idx = loadIndex();
|
|
98
|
+
idx.pins = (idx.pins || []).filter((x) => x !== abs);
|
|
99
|
+
if (pinned) idx.pins.push(abs);
|
|
100
|
+
saveIndex(idx);
|
|
101
|
+
return abs;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const isPinned = (abs, pins) => pins.some((pp) => abs === pp || abs.startsWith(pp + path.sep));
|
|
105
|
+
|
|
106
|
+
// ---------- lock: one offload/fetch run at a time ----------
|
|
107
|
+
|
|
108
|
+
function acquireLock() {
|
|
109
|
+
ensureDataDir();
|
|
110
|
+
const cur = readJson(LOCK_FILE);
|
|
111
|
+
if (cur?.pid && cur.pid !== process.pid) {
|
|
112
|
+
let alive = true;
|
|
113
|
+
try { process.kill(cur.pid, 0); } catch { alive = false; }
|
|
114
|
+
if (alive) throw new Error(`another offload/fetch run is active (pid ${cur.pid})`);
|
|
115
|
+
}
|
|
116
|
+
writeJson(LOCK_FILE, { pid: process.pid, ts: new Date().toISOString() });
|
|
117
|
+
}
|
|
118
|
+
function releaseLock() {
|
|
119
|
+
const cur = readJson(LOCK_FILE);
|
|
120
|
+
if (cur?.pid === process.pid) { try { unlinkSync(LOCK_FILE); } catch { /* gone */ } }
|
|
121
|
+
}
|
|
122
|
+
async function locked(fn) {
|
|
123
|
+
acquireLock();
|
|
124
|
+
try { return await fn(); } finally { releaseLock(); }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ---------- validation ----------
|
|
128
|
+
|
|
129
|
+
function protectedPaths(cfg) {
|
|
130
|
+
return (cfg.protected || []).map((x) => path.resolve(expandHome(x)));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Throws with a human reason if `abs` must not be offloaded. Returns lstat.
|
|
134
|
+
export function validateSource(abs, cfg, pins = []) {
|
|
135
|
+
const st = lstatSync(abs);
|
|
136
|
+
if (st.isSymbolicLink()) throw new Error('is a symlink');
|
|
137
|
+
if (!st.isFile()) throw new Error('not a regular file');
|
|
138
|
+
const real = realpathSync(abs);
|
|
139
|
+
if (!real.startsWith(HOME + path.sep)) throw new Error(`outside ${HOME}`);
|
|
140
|
+
if (abs.endsWith(STUB_EXT)) throw new Error('is already an offload stub');
|
|
141
|
+
if (st.nlink > 1) throw new Error('has hard links — removing it would not free space');
|
|
142
|
+
if (real.startsWith(path.join(HOME, 'Library') + path.sep)) throw new Error('inside ~/Library (app data)');
|
|
143
|
+
if (real.startsWith(DATA_DIR + path.sep)) throw new Error("is cleandrive's own data");
|
|
144
|
+
const segs = real.split(path.sep);
|
|
145
|
+
if (segs.some((s) => NEVER_SEGMENTS.has(s))) throw new Error('inside .git/node_modules/.venv/.Trash');
|
|
146
|
+
if (segs.some((s) => NEVER_SUFFIXES.some((x) => s.endsWith(x)))) throw new Error('inside an app/media library package');
|
|
147
|
+
if (protectedPaths(cfg).some((pp) => real === pp || real.startsWith(pp + path.sep))) throw new Error('user-protected (config.protected)');
|
|
148
|
+
if (isPinned(real, pins)) throw new Error('pinned (keep local)');
|
|
149
|
+
return st;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function inUse(abs) {
|
|
153
|
+
const r = await run('lsof', ['-t', '--', abs]);
|
|
154
|
+
return r.code === 0 && r.out.trim().length > 0;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Expand dirs to files >= minMB (recursive, pruned like validateSource).
|
|
158
|
+
function expandPaths(inputs, minMB) {
|
|
159
|
+
const out = [];
|
|
160
|
+
const walk = (d) => {
|
|
161
|
+
let ents;
|
|
162
|
+
try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
163
|
+
for (const e of ents) {
|
|
164
|
+
const p = path.join(d, e.name);
|
|
165
|
+
if (e.isDirectory()) {
|
|
166
|
+
if (NEVER_SEGMENTS.has(e.name) || NEVER_SUFFIXES.some((x) => e.name.endsWith(x))) continue;
|
|
167
|
+
walk(p);
|
|
168
|
+
} else if (e.isFile() && !e.name.endsWith(STUB_EXT)) {
|
|
169
|
+
try { if (statSync(p).size >= minMB * 1048576) out.push(p); } catch { /* vanished */ }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
for (const raw of inputs) {
|
|
174
|
+
const abs = path.resolve(expandHome(raw));
|
|
175
|
+
let st;
|
|
176
|
+
try { st = lstatSync(abs); } catch { out.push(abs); continue; } // reported later as missing
|
|
177
|
+
if (st.isDirectory()) walk(abs); else out.push(abs);
|
|
178
|
+
}
|
|
179
|
+
return [...new Set(out)];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ---------- stub ----------
|
|
183
|
+
|
|
184
|
+
export function readStub(stubPath) {
|
|
185
|
+
let j;
|
|
186
|
+
try { j = JSON.parse(readFileSync(stubPath, 'utf8')); } catch { return null; }
|
|
187
|
+
return j && j.cleandrive === 'offload-stub' && /^[0-9a-f]{64}$/.test(j.sha256 || '') ? j : null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function writeStub(abs, meta, cfg) {
|
|
191
|
+
const base = remoteBase(cfg);
|
|
192
|
+
const stub = {
|
|
193
|
+
cleandrive: 'offload-stub',
|
|
194
|
+
v: 1,
|
|
195
|
+
name: path.basename(abs),
|
|
196
|
+
path: abs,
|
|
197
|
+
size: meta.size,
|
|
198
|
+
sha256: meta.sha256,
|
|
199
|
+
mtimeMs: meta.mtimeMs,
|
|
200
|
+
object: objectRel(meta.sha256),
|
|
201
|
+
remote: { host: cfg.remote.host, user: cfg.remote.user, path: base, uuid: cfg.remote.uuid },
|
|
202
|
+
offloadedAt: new Date().toISOString(),
|
|
203
|
+
howToRestore: `cleandrive fetch ${q(abs + STUB_EXT)} — or by hand: rsync ${remoteDest(cfg)}:${base}/${objectRel(meta.sha256)} ${q(abs)}`,
|
|
204
|
+
};
|
|
205
|
+
writeFileAtomic(abs + STUB_EXT, JSON.stringify(stub, null, 2) + '\n');
|
|
206
|
+
return stub;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------- offload ----------
|
|
210
|
+
|
|
211
|
+
async function offloadOne(abs, cfg, idx, { dryRun, onData }) {
|
|
212
|
+
const st = validateSource(abs, cfg, idx.pins || []);
|
|
213
|
+
if (await inUse(abs)) throw new Error('open in another process (lsof) — close it first');
|
|
214
|
+
onData?.(` hashing ${short(abs)} (${(st.size / 1048576).toFixed(0)} MB)…\n`);
|
|
215
|
+
const sha = await sha256File(abs);
|
|
216
|
+
const rel = objectRel(sha);
|
|
217
|
+
const base = remoteBase(cfg);
|
|
218
|
+
|
|
219
|
+
// Always prove the UUID-pinned drive is mounted first: an unmounted drive
|
|
220
|
+
// leaves an empty mount point on the remote's root fs that must never be used.
|
|
221
|
+
const drive = await checkRemoteDrive(cfg, Math.ceil(st.size / 1024));
|
|
222
|
+
if (!drive.ok) throw new Error(`refusing: ${drive.msg}`);
|
|
223
|
+
const existing = await remoteSha(cfg, rel);
|
|
224
|
+
const dedupe = existing === sha;
|
|
225
|
+
if (existing && !dedupe) onData?.(` ⚠ remote object ${rel} is corrupt (hash ${existing.slice(0, 12)}…) — re-uploading\n`);
|
|
226
|
+
if (dryRun) return { path: abs, sha256: sha, size: st.size, dryRun: true, upload: !dedupe };
|
|
227
|
+
|
|
228
|
+
if (!dedupe) {
|
|
229
|
+
const mk = await ssh(cfg, `mkdir -p ${q(path.posix.dirname(base + '/' + rel))}`);
|
|
230
|
+
if (mk.code !== 0) throw new Error('remote mkdir failed: ' + mk.err.trim());
|
|
231
|
+
const part = `${base}/${rel}.part`;
|
|
232
|
+
onData?.(` ↑ uploading to ${cfg.remote.host}…\n`);
|
|
233
|
+
const up = await withRetry(cfg, 'upload', () => run('rsync', [...rsyncArgs(cfg), abs, `${remoteDest(cfg)}:${part}`]), onData);
|
|
234
|
+
if (up.code !== 0) throw new Error(`upload failed after ${opt(cfg).retries} attempts — local file kept`);
|
|
235
|
+
const got = await remoteSha(cfg, `${rel}.part`);
|
|
236
|
+
if (got !== sha) {
|
|
237
|
+
await ssh(cfg, `rm -f -- ${q(part)}`);
|
|
238
|
+
throw new Error(`remote checksum mismatch (${(got || 'missing').slice(0, 12)}…) — local file kept`);
|
|
239
|
+
}
|
|
240
|
+
const mv = await ssh(cfg, `mv -f -- ${q(part)} ${q(base + '/' + rel)}`);
|
|
241
|
+
if (mv.code !== 0) throw new Error('remote rename failed: ' + mv.err.trim());
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// The file must not have changed while we hashed/uploaded.
|
|
245
|
+
const now = lstatSync(abs);
|
|
246
|
+
if (now.size !== st.size || now.mtimeMs !== st.mtimeMs) throw new Error('file changed during offload — local file kept');
|
|
247
|
+
|
|
248
|
+
const stub = writeStub(abs, { size: st.size, sha256: sha, mtimeMs: st.mtimeMs }, cfg);
|
|
249
|
+
const entry = { path: abs, size: st.size, sha256: sha, mtimeMs: st.mtimeMs, object: rel, state: 'offloaded', offloadedAt: stub.offloadedAt };
|
|
250
|
+
const line = Buffer.from(JSON.stringify({ event: 'offload', ...entry, mac: process.env.USER }) + '\n').toString('base64');
|
|
251
|
+
const man = await ssh(cfg, `echo ${line} | base64 -d >> ${q(base + '/manifest.jsonl')}`);
|
|
252
|
+
if (man.code !== 0) onData?.(' ⚠ remote manifest append failed (stub + local index still hold the record)\n');
|
|
253
|
+
idx.files[abs] = entry;
|
|
254
|
+
saveIndex(idx);
|
|
255
|
+
unlinkSync(abs);
|
|
256
|
+
log({ event: 'offload', path: abs, sha256: sha, kb: Math.round(st.size / 1024), dedupe, ok: true, verified: true });
|
|
257
|
+
return { path: abs, sha256: sha, size: st.size, dedupe, ok: true };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export async function offloadPaths(inputs, { dryRun = false, minMB = 50, onData } = {}) {
|
|
261
|
+
const cfg = loadConfig();
|
|
262
|
+
const files = expandPaths(inputs, minMB);
|
|
263
|
+
const run1 = async () => {
|
|
264
|
+
const idx = loadIndex();
|
|
265
|
+
const results = [];
|
|
266
|
+
for (const abs of files) {
|
|
267
|
+
onData?.(`${dryRun ? '[dry-run] ' : '▶ '}offload ${short(abs)}\n`);
|
|
268
|
+
try {
|
|
269
|
+
const r = await offloadOne(abs, cfg, idx, { dryRun, onData });
|
|
270
|
+
onData?.(dryRun
|
|
271
|
+
? ` would ${r.upload ? 'upload' : 'reuse existing remote copy of'} ${(r.size / 1048576).toFixed(0)} MB\n`
|
|
272
|
+
: ` ✓ offloaded${r.dedupe ? ' (already on remote — dedupe)' : ''}, stub ${path.basename(abs)}${STUB_EXT}\n`);
|
|
273
|
+
results.push({ ...r, ok: true });
|
|
274
|
+
} catch (e) {
|
|
275
|
+
onData?.(` ✗ ${e.message}\n`);
|
|
276
|
+
if (!dryRun) log({ event: 'offload', path: abs, ok: false, error: e.message });
|
|
277
|
+
results.push({ path: abs, ok: false, error: e.message });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return results;
|
|
281
|
+
};
|
|
282
|
+
return dryRun ? run1() : locked(run1);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// ---------- fetch ----------
|
|
286
|
+
|
|
287
|
+
function stubFor(p) {
|
|
288
|
+
const abs = path.resolve(expandHome(p));
|
|
289
|
+
return abs.endsWith(STUB_EXT) ? abs : abs + STUB_EXT;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function expandStubs(inputs) {
|
|
293
|
+
const out = [];
|
|
294
|
+
const walk = (d) => {
|
|
295
|
+
let ents;
|
|
296
|
+
try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
297
|
+
for (const e of ents) {
|
|
298
|
+
const p = path.join(d, e.name);
|
|
299
|
+
if (e.isDirectory()) walk(p);
|
|
300
|
+
else if (e.isFile() && e.name.endsWith(STUB_EXT)) out.push(p);
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
for (const raw of inputs) {
|
|
304
|
+
const abs = path.resolve(expandHome(raw));
|
|
305
|
+
try { if (lstatSync(abs).isDirectory()) { walk(abs); continue; } } catch { /* not a dir */ }
|
|
306
|
+
out.push(stubFor(abs));
|
|
307
|
+
}
|
|
308
|
+
return [...new Set(out)];
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async function fetchOne(stubPath, cfg, idx, { dryRun, onData }) {
|
|
312
|
+
const stub = readStub(stubPath);
|
|
313
|
+
if (!stub) throw new Error(`${short(stubPath)} is not a cleandrive stub`);
|
|
314
|
+
const target = stubPath.slice(0, -STUB_EXT.length);
|
|
315
|
+
if (!target.startsWith(HOME + path.sep)) throw new Error(`outside ${HOME}`);
|
|
316
|
+
|
|
317
|
+
if (existsSync(target)) {
|
|
318
|
+
// Crash between "stub written" and "original unlinked", or fetched by hand.
|
|
319
|
+
const h = await sha256File(target);
|
|
320
|
+
if (h !== stub.sha256) throw new Error(`${short(target)} exists with different content — resolve by hand, nothing changed`);
|
|
321
|
+
if (!dryRun) unlinkSync(stubPath);
|
|
322
|
+
return { path: target, ok: true, already: true };
|
|
323
|
+
}
|
|
324
|
+
const free = statfsSync(path.dirname(target));
|
|
325
|
+
const freeBytes = free.bavail * free.bsize;
|
|
326
|
+
if (freeBytes < stub.size + 1073741824) throw new Error(`not enough local space: ${(freeBytes / 1073741824).toFixed(1)} GB free, need ${(stub.size / 1073741824 + 1).toFixed(1)} GB`);
|
|
327
|
+
const drive = await checkRemoteDrive(cfg);
|
|
328
|
+
if (!drive.ok) throw new Error(drive.msg);
|
|
329
|
+
const remoteHash = await remoteSha(cfg, stub.object);
|
|
330
|
+
if (!remoteHash) throw new Error(`remote object ${stub.object} missing — see ${remoteBase(cfg)}/manifest.jsonl`);
|
|
331
|
+
if (remoteHash !== stub.sha256) throw new Error(`remote copy corrupt (hash ${remoteHash.slice(0, 12)}…) — stub kept`);
|
|
332
|
+
if (dryRun) return { path: target, size: stub.size, dryRun: true };
|
|
333
|
+
|
|
334
|
+
const tmp = path.join(path.dirname(target), `.${path.basename(target)}.cleandrive-fetch`);
|
|
335
|
+
onData?.(` ↓ downloading ${(stub.size / 1048576).toFixed(0)} MB…\n`);
|
|
336
|
+
const dl = await withRetry(cfg, 'download', () => run('rsync', [...rsyncArgs(cfg), `${remoteDest(cfg)}:${remoteBase(cfg)}/${stub.object}`, tmp]), onData);
|
|
337
|
+
if (dl.code !== 0) throw new Error(`download failed after ${opt(cfg).retries} attempts — stub kept (partial ${path.basename(tmp)} resumes next time)`);
|
|
338
|
+
const h = await sha256File(tmp);
|
|
339
|
+
if (h !== stub.sha256) {
|
|
340
|
+
unlinkSync(tmp);
|
|
341
|
+
throw new Error('downloaded file checksum mismatch — discarded, stub kept');
|
|
342
|
+
}
|
|
343
|
+
renameSync(tmp, target);
|
|
344
|
+
if (stub.mtimeMs) { const t = new Date(stub.mtimeMs); utimesSync(target, t, t); }
|
|
345
|
+
unlinkSync(stubPath);
|
|
346
|
+
const prev = idx.files[target] || {};
|
|
347
|
+
idx.files[target] = { ...prev, path: target, size: stub.size, sha256: stub.sha256, object: stub.object, state: 'local', fetchedAt: new Date().toISOString() };
|
|
348
|
+
saveIndex(idx);
|
|
349
|
+
log({ event: 'fetch', path: target, sha256: stub.sha256, kb: Math.round(stub.size / 1024), ok: true, verified: true });
|
|
350
|
+
return { path: target, size: stub.size, ok: true };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export async function fetchPaths(inputs, { dryRun = false, onData } = {}) {
|
|
354
|
+
const cfg = loadConfig();
|
|
355
|
+
const stubs = expandStubs(inputs);
|
|
356
|
+
const run1 = async () => {
|
|
357
|
+
const idx = loadIndex();
|
|
358
|
+
const results = [];
|
|
359
|
+
for (const s of stubs) {
|
|
360
|
+
onData?.(`${dryRun ? '[dry-run] ' : '▶ '}fetch ${short(s.slice(0, -STUB_EXT.length))}\n`);
|
|
361
|
+
try {
|
|
362
|
+
const r = await fetchOne(s, cfg, idx, { dryRun, onData });
|
|
363
|
+
onData?.(r.already ? ' ✓ already local (same content) — stub removed\n' : dryRun ? ' would download, remote copy verified\n' : ' ✓ fetched and verified\n');
|
|
364
|
+
results.push({ ...r, ok: true });
|
|
365
|
+
} catch (e) {
|
|
366
|
+
onData?.(` ✗ ${e.message}\n`);
|
|
367
|
+
if (!dryRun) log({ event: 'fetch', path: s, ok: false, error: e.message });
|
|
368
|
+
results.push({ path: s, ok: false, error: e.message });
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return results;
|
|
372
|
+
};
|
|
373
|
+
return dryRun ? run1() : locked(run1);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ---------- list / verify ----------
|
|
377
|
+
|
|
378
|
+
// Index entries, reconciled with what is actually on disk right now.
|
|
379
|
+
export function listOffloaded() {
|
|
380
|
+
const idx = loadIndex();
|
|
381
|
+
const files = Object.values(idx.files).map((f) => {
|
|
382
|
+
const stub = existsSync(f.path + STUB_EXT);
|
|
383
|
+
const local = existsSync(f.path);
|
|
384
|
+
return { ...f, state: stub && !local ? 'offloaded' : local ? 'local' : 'missing' };
|
|
385
|
+
}).sort((a, b) => b.size - a.size);
|
|
386
|
+
return { files, pins: idx.pins || [] };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export async function verifyRemote({ onData } = {}) {
|
|
390
|
+
const cfg = loadConfig();
|
|
391
|
+
const drive = await checkRemoteDrive(cfg);
|
|
392
|
+
if (!drive.ok) throw new Error(drive.msg);
|
|
393
|
+
const { files } = listOffloaded();
|
|
394
|
+
const objs = new Map();
|
|
395
|
+
for (const f of files) if (f.object) objs.set(f.object, f);
|
|
396
|
+
const bad = [];
|
|
397
|
+
for (const [rel, f] of objs) {
|
|
398
|
+
const h = await remoteSha(cfg, rel);
|
|
399
|
+
const ok = h === f.sha256;
|
|
400
|
+
onData?.(`${ok ? '✓' : '✗'} ${short(f.path)}${ok ? '' : h ? ' — CORRUPT on remote' : ' — MISSING on remote'}\n`);
|
|
401
|
+
if (!ok) bad.push({ ...f, remoteSha: h });
|
|
402
|
+
}
|
|
403
|
+
log({ event: 'offload-verify', checked: objs.size, bad: bad.length, ok: bad.length === 0 });
|
|
404
|
+
return { checked: objs.size, bad };
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// ---------- candidates (read-only strategy) ----------
|
|
408
|
+
|
|
409
|
+
// mtime + Spotlight's "last opened". Not atime: hashing, Quick Look and
|
|
410
|
+
// Spotlight indexing all bump it, so a candidate would never look idle again.
|
|
411
|
+
async function lastUsedMs(p, st) {
|
|
412
|
+
let t = st.mtimeMs;
|
|
413
|
+
const r = await run('mdls', ['-raw', '-name', 'kMDItemLastUsedDate', p]);
|
|
414
|
+
const d = Date.parse(r.out.trim());
|
|
415
|
+
if (Number.isFinite(d)) t = Math.max(t, d);
|
|
416
|
+
return t;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export async function findCandidates({ minMB = 200, days = 30, allTypes = false, dupes = true, onData } = {}) {
|
|
420
|
+
const cfg = loadConfig();
|
|
421
|
+
const idx = loadIndex();
|
|
422
|
+
const pins = idx.pins || [];
|
|
423
|
+
const roots = [...DEFAULT_ROOTS, ...(cfg.extraDirs || []), ...(cfg.offload?.roots || [])]
|
|
424
|
+
.map((r) => path.resolve(expandHome(r))).filter(existsSync);
|
|
425
|
+
const found = new Map();
|
|
426
|
+
let unreadable = 0;
|
|
427
|
+
for (const root of roots) {
|
|
428
|
+
onData?.(` searching ${short(root)}…\n`);
|
|
429
|
+
const prune = ['(', '-name', 'Library', '-o', '-name', '.git', '-o', '-name', 'node_modules', '-o', '-name', '.venv', '-o', '-name', '.Trash',
|
|
430
|
+
...NEVER_SUFFIXES.flatMap((s) => ['-o', '-name', `*${s}`]), ')', '-prune'];
|
|
431
|
+
const r = await run('find', [root, ...prune, '-o', '-type', 'f', '-size', `+${minMB}M`, '-print0']);
|
|
432
|
+
unreadable += (r.err.match(/Operation not permitted|Permission denied/g) || []).length;
|
|
433
|
+
for (const p of r.out.split('\0').filter(Boolean)) found.set(p, true);
|
|
434
|
+
}
|
|
435
|
+
const cutoff = Date.now() - days * 864e5;
|
|
436
|
+
const all = [];
|
|
437
|
+
for (const p of found.keys()) {
|
|
438
|
+
const ext = path.extname(p).slice(1).toLowerCase();
|
|
439
|
+
if (!allTypes && !MEDIA_EXT.has(ext)) continue;
|
|
440
|
+
let st;
|
|
441
|
+
try { st = validateSource(p, cfg, pins); } catch { continue; }
|
|
442
|
+
all.push({ path: p, size: st.size, kb: Math.round(st.size / 1024), lastUsed: await lastUsedMs(p, st), st });
|
|
443
|
+
}
|
|
444
|
+
// duplicates: same size → sha256
|
|
445
|
+
if (dupes) {
|
|
446
|
+
const bySize = new Map();
|
|
447
|
+
for (const c of all) bySize.set(c.size, [...(bySize.get(c.size) || []), c]);
|
|
448
|
+
for (const group of bySize.values()) {
|
|
449
|
+
if (group.length < 2) continue;
|
|
450
|
+
for (const c of group) { onData?.(` hashing possible duplicate ${short(c.path)}…\n`); c.sha256 = await sha256File(c.path); }
|
|
451
|
+
const byHash = new Map();
|
|
452
|
+
for (const c of group) byHash.set(c.sha256, [...(byHash.get(c.sha256) || []), c]);
|
|
453
|
+
for (const same of byHash.values()) {
|
|
454
|
+
if (same.length < 2) continue;
|
|
455
|
+
same.sort((a, b) => b.lastUsed - a.lastUsed);
|
|
456
|
+
for (const c of same.slice(1)) c.duplicateOf = same[0].path;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
const out = all
|
|
461
|
+
.filter((c) => c.duplicateOf || c.lastUsed < cutoff)
|
|
462
|
+
.map(({ st, ...c }) => ({ ...c, idleDays: Math.floor((Date.now() - c.lastUsed) / 864e5) }))
|
|
463
|
+
.sort((a, b) => (!!b.duplicateOf - !!a.duplicateOf) || b.size - a.size);
|
|
464
|
+
const res = { ts: new Date().toISOString(), minMB, days, roots: roots.map(short), unreadable, candidates: out };
|
|
465
|
+
ensureDataDir();
|
|
466
|
+
writeJson(CANDIDATES_FILE, res);
|
|
467
|
+
return res;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export function loadCandidates() {
|
|
471
|
+
return readJson(CANDIDATES_FILE);
|
|
472
|
+
}
|