@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-10
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/CHANGELOG.md +92 -0
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/client.js +3791 -0
- package/cordis.patch.yml +4 -0
- package/host/engine/archive.js +150 -0
- package/host/engine/atomic.js +27 -0
- package/host/engine/attachments.js +102 -0
- package/host/engine/config.js +214 -0
- package/host/engine/index.js +355 -0
- package/host/engine/ledger.js +108 -0
- package/host/engine/paths.js +81 -0
- package/host/engine/pluginlist.js +81 -0
- package/host/engine/projcache.js +202 -0
- package/host/engine/prune.js +187 -0
- package/host/engine/scan.js +177 -0
- package/host/engine/session.js +138 -0
- package/host/engine/sessions.js +395 -0
- package/host/engine/workspace.js +255 -0
- package/host/engine/zstd.js +91 -0
- package/host/envcheck.js +289 -0
- package/host/mirror.js +502 -0
- package/host/move.js +196 -0
- package/host/overwrite.js +305 -0
- package/host/restart.js +158 -0
- package/host/schedule.js +315 -0
- package/host/search.js +250 -0
- package/host/sync.js +608 -0
- package/host/trash.js +738 -0
- package/host/trashsync.js +204 -0
- package/host/webdav.js +429 -0
- package/icon.svg +1 -0
- package/index.js +376 -0
- package/locale/en.json +68 -0
- package/locale/zh.json +68 -0
- package/package.json +79 -4
package/host/mirror.js
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebDAV mirror layer for DSH增强.
|
|
3
|
+
*
|
|
4
|
+
* The sync engine is filesystem-bound, so WebDAV mode needs a real local folder
|
|
5
|
+
* that mirrors the share: pull remote changes into it, run the engine against it,
|
|
6
|
+
* then push the differences back. This module starts with the read-only half —
|
|
7
|
+
* a diff preview — so the comparison can be trusted before anything is uploaded.
|
|
8
|
+
*/
|
|
9
|
+
import { promises as fsp } from 'node:fs';
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import {
|
|
13
|
+
deleteEmptyRemoteDir,
|
|
14
|
+
deleteRemoteFile,
|
|
15
|
+
fetchRemoteFile,
|
|
16
|
+
listRemoteTree,
|
|
17
|
+
readRemoteManifest,
|
|
18
|
+
uploadRemoteFile,
|
|
19
|
+
writeRemoteManifest,
|
|
20
|
+
} from './webdav.js';
|
|
21
|
+
|
|
22
|
+
const IGNORED = new Set(['_sync-manifest.json']);
|
|
23
|
+
// Bookkeeping the engine rewrites every run: still transferred, never counted as
|
|
24
|
+
// user content on the settings page.
|
|
25
|
+
const INTERNAL_PREFIX = 'config/sync-state/';
|
|
26
|
+
const MAX_FILE_BYTES = 200 * 1024 * 1024;
|
|
27
|
+
const MTIME_TOLERANCE_MS = 2000;
|
|
28
|
+
|
|
29
|
+
function isInternal(rel) {
|
|
30
|
+
return IGNORED.has(rel) || rel.startsWith(INTERNAL_PREFIX);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function readJson(file) {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Walk one local folder, keyed by the relative path with forward slashes. */
|
|
42
|
+
export async function scanLocalTree(root) {
|
|
43
|
+
const files = new Map();
|
|
44
|
+
async function walk(dir, prefix) {
|
|
45
|
+
let entries;
|
|
46
|
+
try {
|
|
47
|
+
entries = await fsp.readdir(dir, { withFileTypes: true });
|
|
48
|
+
} catch {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
|
53
|
+
const target = path.join(dir, entry.name);
|
|
54
|
+
if (entry.isDirectory()) {
|
|
55
|
+
await walk(target, rel);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const stat = await fsp.stat(target);
|
|
60
|
+
files.set(rel, { size: stat.size, mtime: stat.mtimeMs });
|
|
61
|
+
} catch {
|
|
62
|
+
// A file that vanished mid-walk is simply absent.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
await walk(root, '');
|
|
67
|
+
return files;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function differs(remote, local) {
|
|
71
|
+
if (remote.size !== local.size) return true;
|
|
72
|
+
return Math.abs((remote.mtime || 0) - (local.mtime || 0)) > MTIME_TOLERANCE_MS;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function localPathFor(mirror, rel) {
|
|
76
|
+
return path.join(mirror, ...rel.split('/'));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Bucket one relative path into the category shown in the log. */
|
|
80
|
+
function categoryOf(rel) {
|
|
81
|
+
if (rel.startsWith('sessions/')) return 'sessions';
|
|
82
|
+
if (rel.includes('session_projcache')) return 'titles';
|
|
83
|
+
if (rel.startsWith('trash/')) return 'trash';
|
|
84
|
+
if (rel.startsWith('attachments/')) return 'attachments';
|
|
85
|
+
if (rel.startsWith('config/')) return 'config';
|
|
86
|
+
return 'other';
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Total size and file count of the mirror folder. */
|
|
90
|
+
export async function measureMirror(root) {
|
|
91
|
+
const result = { bytes: 0, files: 0 };
|
|
92
|
+
async function walk(dir) {
|
|
93
|
+
let entries;
|
|
94
|
+
try {
|
|
95
|
+
entries = await fsp.readdir(dir, { withFileTypes: true });
|
|
96
|
+
} catch {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
for (const entry of entries) {
|
|
100
|
+
const full = path.join(dir, entry.name);
|
|
101
|
+
if (entry.isDirectory()) {
|
|
102
|
+
await walk(full);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const stat = await fsp.stat(full);
|
|
107
|
+
result.bytes += stat.size;
|
|
108
|
+
result.files += 1;
|
|
109
|
+
} catch {
|
|
110
|
+
// A file that vanished mid-walk is simply absent.
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
await walk(root);
|
|
115
|
+
return result;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Attachment objects are named after their own sha256. */
|
|
119
|
+
function isContentAddressed(rel) {
|
|
120
|
+
return /^attachments\/v1\/objects\/[0-9a-f]{2}\/[0-9a-f]{64}$/u.test(rel);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Content hash used to decide whether a file really changed. */
|
|
124
|
+
function sha256(buffer) {
|
|
125
|
+
return createHash('sha256').update(buffer).digest('hex');
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Download remote files that the mirror is missing or holds in an older copy.
|
|
130
|
+
* Read-only for the share: nothing is uploaded or deleted.
|
|
131
|
+
*/
|
|
132
|
+
/**
|
|
133
|
+
* Pull using the remote manifest as the index instead of walking the whole tree.
|
|
134
|
+
*
|
|
135
|
+
* A full PROPFIND tour costs one request per folder (about 100 on a normal corpus,
|
|
136
|
+
* several seconds). The manifest is written by every push from any machine and
|
|
137
|
+
* carries size, mtime and hash per file, so comparing against it needs a single GET.
|
|
138
|
+
* A periodic full scan still catches changes made outside the plugin.
|
|
139
|
+
*/
|
|
140
|
+
export async function pullMirrorFast(deps, signal) {
|
|
141
|
+
const { settings } = deps;
|
|
142
|
+
const mirror = requireMirror(settings);
|
|
143
|
+
const manifest = await readRemoteManifest(settings, signal);
|
|
144
|
+
const files = manifest !== null && manifest.json !== null && typeof manifest.json.files === 'object'
|
|
145
|
+
? manifest.json.files
|
|
146
|
+
: null;
|
|
147
|
+
if (files === null) return null;
|
|
148
|
+
|
|
149
|
+
let downloaded = 0;
|
|
150
|
+
let skipped = 0;
|
|
151
|
+
let bytes = 0;
|
|
152
|
+
const failed = [];
|
|
153
|
+
const downloadedRels = [];
|
|
154
|
+
|
|
155
|
+
for (const [rel, info] of Object.entries(files)) {
|
|
156
|
+
if (IGNORED.has(rel)) continue;
|
|
157
|
+
const target = localPathFor(mirror, rel);
|
|
158
|
+
let local;
|
|
159
|
+
try {
|
|
160
|
+
local = await fsp.stat(target);
|
|
161
|
+
} catch {
|
|
162
|
+
local = undefined;
|
|
163
|
+
}
|
|
164
|
+
const size = Number(info?.size) || 0;
|
|
165
|
+
const hash = typeof info?.hash === 'string' ? info.hash : '';
|
|
166
|
+
if (local !== undefined && local.size === size && hash !== '') {
|
|
167
|
+
try {
|
|
168
|
+
if (sha256(await fsp.readFile(target)) === hash) {
|
|
169
|
+
const authored = Number(info?.mtime) > 0 ? Number(info.mtime) : local.mtimeMs;
|
|
170
|
+
if (Math.abs(authored - local.mtimeMs) > MTIME_TOLERANCE_MS) {
|
|
171
|
+
await fsp.utimes(target, authored / 1000, authored / 1000).catch(() => {});
|
|
172
|
+
}
|
|
173
|
+
skipped += 1;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
} catch {
|
|
177
|
+
// Unreadable local copy: download it.
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (size > MAX_FILE_BYTES) {
|
|
181
|
+
skipped += 1;
|
|
182
|
+
failed.push(rel);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
let data;
|
|
186
|
+
try {
|
|
187
|
+
data = await fetchRemoteFile(settings, rel, signal);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
failed.push({ path: rel, error: String(error?.message ?? error) });
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
if (data === null) {
|
|
193
|
+
failed.push({ path: rel, error: '服务器返回 404' });
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
await fsp.mkdir(path.dirname(target), { recursive: true });
|
|
197
|
+
const temporary = `${target}.pull-${String(process.pid)}`;
|
|
198
|
+
await fsp.writeFile(temporary, data);
|
|
199
|
+
await fsp.rm(target, { force: true }).catch(() => {});
|
|
200
|
+
await fsp.rename(temporary, target);
|
|
201
|
+
const authored = Number(info?.mtime) > 0 ? Number(info.mtime) : Date.now();
|
|
202
|
+
await fsp.utimes(target, authored / 1000, authored / 1000).catch(() => {});
|
|
203
|
+
downloaded += 1;
|
|
204
|
+
if (!isInternal(rel)) {
|
|
205
|
+
downloadedRels.push(rel);
|
|
206
|
+
bytes += data.length;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Files the share no longer lists are gone from the mirror as well.
|
|
211
|
+
const local = await scanLocalTree(mirror);
|
|
212
|
+
let removed = 0;
|
|
213
|
+
for (const rel of Object.keys(local)) {
|
|
214
|
+
if (files[rel] !== undefined) continue;
|
|
215
|
+
if (IGNORED.has(rel)) continue;
|
|
216
|
+
try {
|
|
217
|
+
await fsp.rm(path.join(mirror, ...rel.split('/')), { force: true });
|
|
218
|
+
removed += 1;
|
|
219
|
+
} catch {
|
|
220
|
+
// A file that cannot be removed stays until the next full scan.
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
ok: true,
|
|
226
|
+
direction: 'pull',
|
|
227
|
+
fast: true,
|
|
228
|
+
downloaded,
|
|
229
|
+
skipped,
|
|
230
|
+
bytes,
|
|
231
|
+
failed,
|
|
232
|
+
removed,
|
|
233
|
+
requested: 1,
|
|
234
|
+
downloadedRels: downloadedRels.slice(0, 300),
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export async function pullMirror(deps, signal) {
|
|
239
|
+
const { settings } = deps;
|
|
240
|
+
const mirror = requireMirror(settings);
|
|
241
|
+
const listed = await listRemoteTree(settings, signal);
|
|
242
|
+
const manifest = await readRemoteManifest(settings, signal);
|
|
243
|
+
const known = manifest !== null && manifest.json !== null && typeof manifest.json.files === 'object' ? manifest.json.files : {};
|
|
244
|
+
let downloaded = 0;
|
|
245
|
+
const downloadedRels = [];
|
|
246
|
+
const categories = { sessions: 0, config: 0, titles: 0, trash: 0, attachments: 0, other: 0 };
|
|
247
|
+
let skipped = 0;
|
|
248
|
+
let bytes = 0;
|
|
249
|
+
const failed = [];
|
|
250
|
+
|
|
251
|
+
for (const [rel, info] of listed.files.entries()) {
|
|
252
|
+
if (IGNORED.has(rel)) continue;
|
|
253
|
+
const target = localPathFor(mirror, rel);
|
|
254
|
+
let mine;
|
|
255
|
+
try { mine = await fsp.stat(target); } catch { mine = undefined; }
|
|
256
|
+
if (mine !== undefined && !differs(info, { size: mine.size, mtime: mine.mtimeMs })) {
|
|
257
|
+
skipped += 1;
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
// A rewritten server timestamp is not a content change: trust the manifest
|
|
261
|
+
// hash before paying for a download.
|
|
262
|
+
if (mine !== undefined && info.size === mine.size && isContentAddressed(rel)) {
|
|
263
|
+
// attachments/v1/objects/<ab>/<sha256>: the file name is its own hash.
|
|
264
|
+
try {
|
|
265
|
+
if (sha256(await fsp.readFile(target)) === rel.split('/').pop()) {
|
|
266
|
+
const authored = Number(known[rel]?.mtime) > 0 ? Number(known[rel].mtime) : info.mtime;
|
|
267
|
+
if (authored > 0) await fsp.utimes(target, authored / 1000, authored / 1000).catch(() => {});
|
|
268
|
+
skipped += 1;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
} catch {
|
|
272
|
+
// Unreadable copy: fall through to the download.
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (mine !== undefined && info.size === mine.size && typeof known[rel]?.hash === 'string') {
|
|
276
|
+
try {
|
|
277
|
+
if (sha256(await fsp.readFile(target)) === known[rel].hash) {
|
|
278
|
+
// The recorded mtime is when the file was authored; the server one is
|
|
279
|
+
// when it was uploaded. Trusting the server time makes every machine
|
|
280
|
+
// look newer than the other one and causes endless re-downloads.
|
|
281
|
+
const authored = Number(known[rel]?.mtime) > 0 ? Number(known[rel].mtime) : info.mtime;
|
|
282
|
+
await fsp.utimes(target, authored / 1000, authored / 1000).catch(() => {});
|
|
283
|
+
skipped += 1;
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
} catch {
|
|
287
|
+
// Unreadable local copy: fall through to the download.
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
291
|
+
skipped += 1;
|
|
292
|
+
failed.push(rel);
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
let data;
|
|
296
|
+
try {
|
|
297
|
+
data = await fetchRemoteFile(settings, rel, signal);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
failed.push({ path: rel, error: String(error?.message ?? error) });
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
if (data === null) {
|
|
303
|
+
failed.push({ path: rel, error: '服务器返回 404' });
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
await fsp.mkdir(path.dirname(target), { recursive: true });
|
|
307
|
+
const temporary = `${target}.pull-${String(process.pid)}`;
|
|
308
|
+
await fsp.writeFile(temporary, data);
|
|
309
|
+
await fsp.rm(target, { force: true }).catch(() => {});
|
|
310
|
+
await fsp.rename(temporary, target);
|
|
311
|
+
const authored = Number(known[rel]?.mtime) > 0 ? Number(known[rel].mtime) : info.mtime;
|
|
312
|
+
if (authored > 0) {
|
|
313
|
+
await fsp.utimes(target, authored / 1000, authored / 1000).catch(() => {});
|
|
314
|
+
}
|
|
315
|
+
downloaded += isInternal(rel) ? 0 : 1;
|
|
316
|
+
if (!isInternal(rel)) categories[categoryOf(rel)] += 1;
|
|
317
|
+
bytes += isInternal(rel) ? 0 : data.length;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return { ok: true, direction: 'pull', downloaded, skipped, bytes, failed, requests: listed.requests, truncated: listed.truncated, downloadedRels: downloadedRels.slice(0, 300), categories };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Upload mirror files that the share is missing or holds in an older copy.
|
|
325
|
+
* Additive: it never deletes a remote file.
|
|
326
|
+
*/
|
|
327
|
+
export async function pushMirror(deps, signal) {
|
|
328
|
+
const { settings, useManifestIndex = false } = deps;
|
|
329
|
+
const mirror = requireMirror(settings);
|
|
330
|
+
const local = await scanLocalTree(mirror);
|
|
331
|
+
const previous = await readRemoteManifest(settings, signal);
|
|
332
|
+
// The manifest already names every file the share holds, so a PROPFIND tour is
|
|
333
|
+
// only needed when it is missing or a full reconciliation was requested.
|
|
334
|
+
const manifestFiles = previous !== null && previous.json !== null && typeof previous.json.files === 'object'
|
|
335
|
+
? previous.json.files
|
|
336
|
+
: null;
|
|
337
|
+
const listed = useManifestIndex && manifestFiles !== null
|
|
338
|
+
? { files: new Map(Object.entries(manifestFiles).map(([rel, info]) => [rel, { size: Number(info?.size) || 0, mtime: Number(info?.mtime) || 0 }])), requests: 0, truncated: false }
|
|
339
|
+
: await listRemoteTree(settings, signal);
|
|
340
|
+
const known = previous !== null && previous.json !== null && typeof previous.json.files === 'object' ? previous.json.files : {};
|
|
341
|
+
const ensured = new Set(['']);
|
|
342
|
+
const manifest = {};
|
|
343
|
+
const categories = { sessions: 0, config: 0, titles: 0, trash: 0, attachments: 0, other: 0 };
|
|
344
|
+
let uploaded = 0;
|
|
345
|
+
const uploadedRels = [];
|
|
346
|
+
const deletedRels = [];
|
|
347
|
+
let skipped = 0;
|
|
348
|
+
let bytes = 0;
|
|
349
|
+
const failed = [];
|
|
350
|
+
|
|
351
|
+
for (const [rel, info] of local.entries()) {
|
|
352
|
+
if (IGNORED.has(rel)) continue;
|
|
353
|
+
const entry = known[rel];
|
|
354
|
+
const remote = listed.files.get(rel);
|
|
355
|
+
const entryIsCurrent = entry !== undefined
|
|
356
|
+
&& Number(entry.size) === info.size
|
|
357
|
+
&& typeof entry.mtime === 'number'
|
|
358
|
+
&& info.mtime <= Number(entry.mtime) + MTIME_TOLERANCE_MS;
|
|
359
|
+
|
|
360
|
+
if (entryIsCurrent && (remote === undefined || !differs(remote, info))) {
|
|
361
|
+
// Untouched locally since the last push, and the share agrees.
|
|
362
|
+
let hash = entry.hash;
|
|
363
|
+
if (typeof hash !== 'string') {
|
|
364
|
+
// Older manifests recorded size and time only; without a hash every later
|
|
365
|
+
// pull sees a differing server stamp and downloads the file again.
|
|
366
|
+
try {
|
|
367
|
+
hash = sha256(await fsp.readFile(localPathFor(mirror, rel)));
|
|
368
|
+
} catch {
|
|
369
|
+
hash = undefined;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
manifest[rel] = { size: info.size, mtime: info.mtime, hash };
|
|
373
|
+
skipped += 1;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (entry === undefined && remote !== undefined && !differs(remote, info)) {
|
|
378
|
+
// No manifest yet (first run or a new file), but the share already holds this
|
|
379
|
+
// exact size/time pair: adopt it instead of re-uploading.
|
|
380
|
+
manifest[rel] = { size: info.size, mtime: info.mtime };
|
|
381
|
+
skipped += 1;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
let data;
|
|
386
|
+
try {
|
|
387
|
+
data = await fsp.readFile(localPathFor(mirror, rel));
|
|
388
|
+
} catch (error) {
|
|
389
|
+
failed.push({ path: rel, error: String(error?.message ?? error) });
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (data.length > MAX_FILE_BYTES) {
|
|
393
|
+
skipped += 1;
|
|
394
|
+
failed.push({ path: rel, error: '超过 200 MB 上限' });
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
const hash = sha256(data);
|
|
398
|
+
if (entry !== undefined && entry.hash === hash) {
|
|
399
|
+
// Content unchanged (only the timestamp moved): refresh the record, skip upload.
|
|
400
|
+
manifest[rel] = { size: data.length, mtime: info.mtime, hash };
|
|
401
|
+
skipped += 1;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
await uploadRemoteFile(settings, rel, data, ensured, signal);
|
|
406
|
+
} catch (error) {
|
|
407
|
+
failed.push({ path: rel, error: String(error?.message ?? error) });
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
manifest[rel] = { size: data.length, mtime: info.mtime, hash };
|
|
411
|
+
if (!isInternal(rel)) {
|
|
412
|
+
categories[categoryOf(rel)] += 1;
|
|
413
|
+
uploadedRels.push(rel);
|
|
414
|
+
}
|
|
415
|
+
uploaded += isInternal(rel) ? 0 : 1;
|
|
416
|
+
bytes += isInternal(rel) ? 0 : data.length;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// Files the previous manifest listed but the mirror no longer holds were
|
|
420
|
+
// deleted locally (purge, prune, trash cleanup) — remove them from the share
|
|
421
|
+
// too, otherwise the cloud only ever grows. Guarded so that a wiped mirror or
|
|
422
|
+
// a first run can never trigger a mass delete.
|
|
423
|
+
const knownVisible = Object.keys(known).filter((rel) => !isInternal(rel));
|
|
424
|
+
const localVisible = [...local.keys()].filter((rel) => !isInternal(rel));
|
|
425
|
+
const removed = knownVisible.filter((rel) => !local.has(rel) && !IGNORED.has(rel));
|
|
426
|
+
let deleted = 0;
|
|
427
|
+
const deleteFailed = [];
|
|
428
|
+
const deletedCategories = { sessions: 0, config: 0, titles: 0, trash: 0, attachments: 0, other: 0 };
|
|
429
|
+
let deleteSkipped = null;
|
|
430
|
+
if (removed.length > 0) {
|
|
431
|
+
const cap = Math.max(20, Math.floor(knownVisible.length * 0.3));
|
|
432
|
+
if (localVisible.length === 0) {
|
|
433
|
+
deleteSkipped = '镜像为空,疑似被清空,已跳过云端删除';
|
|
434
|
+
} else if (removed.length > cap) {
|
|
435
|
+
deleteSkipped = `本轮待删除 ${String(removed.length)} 个文件,超过安全上限 ${String(cap)},已跳过`;
|
|
436
|
+
} else {
|
|
437
|
+
for (const rel of removed) {
|
|
438
|
+
try {
|
|
439
|
+
await deleteRemoteFile(settings, rel, signal);
|
|
440
|
+
deleted += 1;
|
|
441
|
+
deletedRels.push(rel);
|
|
442
|
+
deletedCategories[categoryOf(rel)] += 1;
|
|
443
|
+
} catch (error) {
|
|
444
|
+
deleteFailed.push({ path: rel, error: String(error?.message ?? error) });
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
// DAV deletes files, not the folders that held them: prune the empty
|
|
448
|
+
// session folder (and its project folder) that would otherwise linger.
|
|
449
|
+
const parents = new Set();
|
|
450
|
+
for (const rel of removed) {
|
|
451
|
+
const parts = rel.split('/');
|
|
452
|
+
for (let depth = parts.length - 1; depth >= 2; depth -= 1) parents.add(parts.slice(0, depth).join('/'));
|
|
453
|
+
}
|
|
454
|
+
const deepestFirst = [...parents].sort((a, b) => b.split('/').length - a.split('/').length);
|
|
455
|
+
for (const dir of deepestFirst) {
|
|
456
|
+
try {
|
|
457
|
+
await deleteEmptyRemoteDir(settings, dir, signal);
|
|
458
|
+
} catch {
|
|
459
|
+
// A failed prune leaves an empty folder; the next run retries.
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Keep manifest entries for untouched remote files too, so the next preview
|
|
466
|
+
// can take the fast path instead of walking the whole tree.
|
|
467
|
+
const removedSet = new Set(removed);
|
|
468
|
+
for (const [rel, info] of listed.files.entries()) {
|
|
469
|
+
if (removedSet.has(rel)) continue;
|
|
470
|
+
if (manifest[rel] === undefined) manifest[rel] = known[rel] ?? info;
|
|
471
|
+
}
|
|
472
|
+
try {
|
|
473
|
+
await writeRemoteManifest(settings, manifest, ensured, signal);
|
|
474
|
+
} catch {
|
|
475
|
+
// A missing manifest only costs a full listing next time.
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
return {
|
|
479
|
+
ok: true,
|
|
480
|
+
direction: 'push',
|
|
481
|
+
uploaded,
|
|
482
|
+
skipped,
|
|
483
|
+
bytes,
|
|
484
|
+
deleted,
|
|
485
|
+
categories,
|
|
486
|
+
deletedCategories,
|
|
487
|
+
uploadedRels: uploadedRels.slice(0, 300),
|
|
488
|
+
deletedRels: deletedRels.slice(0, 300),
|
|
489
|
+
deleteFailed,
|
|
490
|
+
deleteSkipped,
|
|
491
|
+
failed,
|
|
492
|
+
requests: listed.requests,
|
|
493
|
+
truncated: listed.truncated,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function requireMirror(settings) {
|
|
498
|
+
const mirror = typeof settings.mirrorDir === 'string' ? settings.mirrorDir.trim() : '';
|
|
499
|
+
if (mirror === '') throw Object.assign(new Error('请先填写本地镜像目录。'), { code: 'mirror-missing' });
|
|
500
|
+
return mirror;
|
|
501
|
+
}
|
|
502
|
+
|
package/host/move.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Move one session into another workspace, in place.
|
|
3
|
+
*
|
|
4
|
+
* DSH derives a session's project directory from the `cwd` in its header and the
|
|
5
|
+
* Host keeps that header in memory for as long as it has the session loaded, so
|
|
6
|
+
* attaching a rewritten session would be rejected with a cwd mismatch. The move
|
|
7
|
+
* therefore edits storage directly — log header plus `workspace.json` — and takes
|
|
8
|
+
* effect the next time the app reads them, which is what a restart does.
|
|
9
|
+
*
|
|
10
|
+
* The rewrite is guarded: no live Agent, an existing target workspace different
|
|
11
|
+
* from the current one, a verified read-back before the old copy is removed, and
|
|
12
|
+
* an untouched original whenever anything fails.
|
|
13
|
+
*/
|
|
14
|
+
import { promises as fsp, readdirSync } from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import {
|
|
17
|
+
failure,
|
|
18
|
+
findOwningWorkspace,
|
|
19
|
+
locateSessionDir,
|
|
20
|
+
workspaceSnapshot,
|
|
21
|
+
} from './trash.js';
|
|
22
|
+
import { projectKey } from './engine/scan.js';
|
|
23
|
+
import { readSessionFile, rewriteCwd, writeSessionFile } from './engine/session.js';
|
|
24
|
+
|
|
25
|
+
const READ_PAGE = 500;
|
|
26
|
+
|
|
27
|
+
/** Read every durable event of one cold session, paging through the log. */
|
|
28
|
+
export async function readAllEvents(persistence, sessionId) {
|
|
29
|
+
const handle = await persistence.open(sessionId, 'read');
|
|
30
|
+
try {
|
|
31
|
+
const events = [];
|
|
32
|
+
let offset = 0;
|
|
33
|
+
while (true) {
|
|
34
|
+
const page = await handle.read(offset, READ_PAGE);
|
|
35
|
+
const batch = page?.events ?? [];
|
|
36
|
+
if (batch.length === 0) break;
|
|
37
|
+
events.push(...batch);
|
|
38
|
+
offset += batch.length;
|
|
39
|
+
if (batch.length < READ_PAGE) break;
|
|
40
|
+
}
|
|
41
|
+
return events;
|
|
42
|
+
} finally {
|
|
43
|
+
await handle.close();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The workspaces a session may move to, plus the one currently holding it. */
|
|
48
|
+
export async function moveCandidates(deps, sessionId) {
|
|
49
|
+
const { registry } = deps;
|
|
50
|
+
const current = findOwningWorkspace(registry, sessionId);
|
|
51
|
+
const currentInfo = workspaceSnapshot(current);
|
|
52
|
+
const workspaces = (registry?.list?.() ?? [])
|
|
53
|
+
.map((workspace) => workspaceSnapshot(workspace))
|
|
54
|
+
.filter((info) => info !== undefined && info.id !== currentInfo?.id)
|
|
55
|
+
.map((info) => ({
|
|
56
|
+
id: info.id,
|
|
57
|
+
title: info.title,
|
|
58
|
+
path: info.path,
|
|
59
|
+
sessionCount: info.sessionIds.length,
|
|
60
|
+
}));
|
|
61
|
+
return {
|
|
62
|
+
current: currentInfo === undefined ? null : { id: currentInfo.id, title: currentInfo.title },
|
|
63
|
+
workspaces,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The newest log file of a session directory. */
|
|
68
|
+
function newestLogFile(dir) {
|
|
69
|
+
const files = readdirSync(dir).filter((name) => name.startsWith('session.v'));
|
|
70
|
+
if (files.length === 0) return null;
|
|
71
|
+
files.sort((a, b) => {
|
|
72
|
+
const left = Number(/session\.v(\d+)/u.exec(a)?.[1] ?? 0);
|
|
73
|
+
const right = Number(/session\.v(\d+)/u.exec(b)?.[1] ?? 0);
|
|
74
|
+
return left - right;
|
|
75
|
+
});
|
|
76
|
+
return path.join(dir, files[files.length - 1]);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Same path on Windows, ignoring case and trailing separators. */
|
|
80
|
+
function samePath(left, right) {
|
|
81
|
+
const clean = (value) => String(value).replace(/[\\/]+$/u, '').replace(/\//gu, '\\').toLowerCase();
|
|
82
|
+
return clean(left) === clean(right);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Rewrite the workspace document so the session belongs to the target group.
|
|
87
|
+
* The file is the single durable record of membership; writing it directly avoids
|
|
88
|
+
* the Host's in-memory check that would reject a session whose header still holds
|
|
89
|
+
* the old cwd.
|
|
90
|
+
*/
|
|
91
|
+
async function rewriteMembership(paths, sessionId, targetWorkspaceId, targetPath) {
|
|
92
|
+
const file = path.join(paths.home, 'storages', 'workspace.json');
|
|
93
|
+
let doc;
|
|
94
|
+
try {
|
|
95
|
+
doc = JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
96
|
+
} catch (error) {
|
|
97
|
+
throw failure('move-workspace-read', `无法读取工作区登记:${error.message}`);
|
|
98
|
+
}
|
|
99
|
+
const table = doc?.tables?.workspaces;
|
|
100
|
+
if (table === null || typeof table !== 'object' || table[targetWorkspaceId] === undefined) {
|
|
101
|
+
throw failure('move-workspace-record', '工作区登记里找不到目标分组。');
|
|
102
|
+
}
|
|
103
|
+
for (const record of Object.values(table)) {
|
|
104
|
+
if (Array.isArray(record?.sessionIds)) {
|
|
105
|
+
record.sessionIds = record.sessionIds.filter((id) => id !== sessionId);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const target = table[targetWorkspaceId];
|
|
109
|
+
target.sessionIds = [...(target.sessionIds ?? []), sessionId];
|
|
110
|
+
target.updatedAt = new Date().toISOString();
|
|
111
|
+
if (typeof target.path !== 'string' || target.path === '') target.path = targetPath;
|
|
112
|
+
|
|
113
|
+
const temporary = `${file}.${String(process.pid)}.tmp`;
|
|
114
|
+
await fsp.writeFile(temporary, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
|
|
115
|
+
await fsp.rename(temporary, file);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Move one session into another workspace.
|
|
120
|
+
*
|
|
121
|
+
* @param deps - Host services and resolved paths.
|
|
122
|
+
* @param sessionId - source session.
|
|
123
|
+
* @param targetWorkspaceId - destination workspace.
|
|
124
|
+
* @returns the same session id with its new workspace and cwd.
|
|
125
|
+
*/
|
|
126
|
+
export async function moveSession(deps, sessionId, targetWorkspaceId) {
|
|
127
|
+
const { paths, registry, persistence, agents, settings } = deps;
|
|
128
|
+
if (settings.moveEnabled !== true) throw failure('move-disabled', '会话移动已在设置中关闭。');
|
|
129
|
+
if (agents !== undefined && typeof agents.get === 'function') {
|
|
130
|
+
const agent = agents.get(sessionId);
|
|
131
|
+
if (agent !== undefined && agent?.status === 'running') {
|
|
132
|
+
throw failure('session-live', '该会话正在运行任务,等它结束或停止后再移动。');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const snapshot = await persistence.stat(sessionId);
|
|
136
|
+
if (snapshot === undefined) throw failure('session-missing', '会话不存在或已被删除。');
|
|
137
|
+
const target = registry?.get?.(targetWorkspaceId);
|
|
138
|
+
if (target === undefined) throw failure('move-target-missing', '目标工作区不存在。');
|
|
139
|
+
const source = findOwningWorkspace(registry, sessionId);
|
|
140
|
+
if (source !== undefined && source.id === targetWorkspaceId) {
|
|
141
|
+
throw failure('move-same', '该会话已经在这个工作区中。');
|
|
142
|
+
}
|
|
143
|
+
const sourceDir = await locateSessionDir(paths, sessionId);
|
|
144
|
+
if (sourceDir === undefined) throw failure('session-dir-missing', '找不到该会话的本机目录。');
|
|
145
|
+
|
|
146
|
+
const sourceFile = newestLogFile(sourceDir);
|
|
147
|
+
if (sourceFile === null) throw failure('move-empty', '该会话没有可移动的日志。');
|
|
148
|
+
|
|
149
|
+
const parsed = await readSessionFile(sourceFile);
|
|
150
|
+
const toCwd = target.path;
|
|
151
|
+
const alreadyThere = samePath(parsed.header.cwd ?? '', toCwd);
|
|
152
|
+
|
|
153
|
+
let targetDir = sourceDir;
|
|
154
|
+
if (!alreadyThere) {
|
|
155
|
+
targetDir = path.join(paths.sessionsRoot, projectKey(toCwd), sessionId);
|
|
156
|
+
const targetFile = path.join(targetDir, path.basename(sourceFile));
|
|
157
|
+
await fsp.mkdir(targetDir, { recursive: true });
|
|
158
|
+
try {
|
|
159
|
+
const texts = rewriteCwd(parsed, toCwd).texts;
|
|
160
|
+
const expectedFrames = texts.length;
|
|
161
|
+
await writeSessionFile(targetFile, texts);
|
|
162
|
+
const stat = await fsp.stat(sourceFile);
|
|
163
|
+
await fsp.utimes(targetFile, stat.mtimeMs / 1000, stat.mtimeMs / 1000).catch(() => {});
|
|
164
|
+
const check = await readSessionFile(targetFile);
|
|
165
|
+
if (check.header.id !== sessionId || !samePath(check.header.cwd ?? '', toCwd)) {
|
|
166
|
+
throw failure('move-verify', '写入后校验失败:会话标识或路径不一致,已保留原文件。');
|
|
167
|
+
}
|
|
168
|
+
if (check.texts.length !== expectedFrames) {
|
|
169
|
+
throw failure('move-verify', `写入后校验失败:期望${String(expectedFrames)}条,实际${String(check.texts.length)}条,已保留原文件。`);
|
|
170
|
+
}
|
|
171
|
+
} catch (error) {
|
|
172
|
+
await fsp.rm(targetDir, { recursive: true, force: true }).catch(() => {});
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
await rewriteMembership(paths, sessionId, targetWorkspaceId, toCwd);
|
|
178
|
+
|
|
179
|
+
if (!alreadyThere) {
|
|
180
|
+
// The old copy disappears only after the new one verified and membership moved.
|
|
181
|
+
await fsp.rm(sourceDir, { recursive: true, force: true }).catch(() => {});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// The projection shard still describes the old cwd; the host rebuilds it from
|
|
185
|
+
// the log on the next read.
|
|
186
|
+
const shard = path.join(paths.projcacheRoot, 'sessions', `${sessionId}.json`);
|
|
187
|
+
await fsp.rm(shard, { force: true }).catch(() => {});
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
sessionId,
|
|
191
|
+
workspaceId: targetWorkspaceId,
|
|
192
|
+
cwd: toCwd,
|
|
193
|
+
inPlace: true,
|
|
194
|
+
needsRestart: true,
|
|
195
|
+
};
|
|
196
|
+
}
|