@rljson/fs-agent 0.0.85 → 0.2.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/README.api.md +383 -0
- package/README.architecture.md +483 -288
- package/README.contributors.md +101 -15
- package/README.md +41 -11
- package/README.public.md +409 -796
- package/README.tests.md +460 -0
- package/README.trouble.md +70 -8
- package/dist/README.api.md +383 -0
- package/dist/README.architecture.md +483 -288
- package/dist/README.contributors.md +101 -15
- package/dist/README.md +41 -11
- package/dist/README.public.md +409 -796
- package/dist/README.tests.md +460 -0
- package/dist/README.trouble.md +70 -8
- package/dist/fs-agent.d.ts +703 -426
- package/dist/fs-agent.js +2801 -1584
- package/dist/fs-atomic-write.d.ts +46 -0
- package/dist/fs-edit-chain.d.ts +368 -0
- package/dist/fs-ignore.d.ts +32 -0
- package/dist/fs-merge.d.ts +109 -0
- package/dist/fs-receive.d.ts +83 -0
- package/dist/fs-scanner.d.ts +169 -6
- package/dist/fs-send.d.ts +53 -0
- package/dist/fs-signals.d.ts +169 -0
- package/dist/fs-stamps.d.ts +94 -0
- package/dist/index.d.ts +5 -2
- package/package.json +11 -11
- package/dist/fs-anti-entropy.d.ts +0 -146
- package/dist/fs-conflict-resolver.d.ts +0 -181
package/dist/fs-agent.js
CHANGED
|
@@ -1,125 +1,189 @@
|
|
|
1
1
|
import { BsMem } from "@rljson/bs";
|
|
2
|
-
import { Route, createTreesTableCfg } from "@rljson/rljson";
|
|
3
|
-
import { watch, writeFileSync, existsSync, readFileSync, appendFileSync } from "fs";
|
|
4
|
-
import { stat, open, mkdir, utimes, readdir, readFile, writeFile, rename, unlink, rm } from "fs/promises";
|
|
5
|
-
import { dirname, join } from "path";
|
|
6
2
|
import { hip } from "@rljson/hash";
|
|
3
|
+
import { timeId, createEditTableCfg, createMultiEditTableCfg, createEditHistoryTableCfg, compareRefStamp, isRefStamp, Route, createTreesTableCfg } from "@rljson/rljson";
|
|
4
|
+
import { watch, existsSync, readFileSync, writeFileSync, appendFileSync } from "fs";
|
|
5
|
+
import { writeFile, rename, unlink, open, stat, mkdir, utimes, readdir, readFile, lstat, rm, rmdir } from "fs/promises";
|
|
6
|
+
import { join, dirname, relative, sep, resolve } from "path";
|
|
7
7
|
import { stateBeaconEvent, Db } from "@rljson/db";
|
|
8
8
|
import { IoMem, createSocketPair } from "@rljson/io";
|
|
9
9
|
import { Server, Client } from "@rljson/server";
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
this.
|
|
10
|
+
const SIGNAL_LOG_MAX = 200;
|
|
11
|
+
const SIGNAL_PATHS_MAX = 20;
|
|
12
|
+
const SIGNAL_ONCE_MAX = 500;
|
|
13
|
+
const SIGNAL_LOG_FILE = ".fsagent-signals.json";
|
|
14
|
+
class FsSignals {
|
|
15
|
+
_signals = [];
|
|
16
|
+
_totals = /* @__PURE__ */ new Map();
|
|
17
|
+
_listeners = /* @__PURE__ */ new Set();
|
|
18
|
+
_once = /* @__PURE__ */ new Set();
|
|
19
|
+
/**
|
|
20
|
+
* Records one signal.
|
|
21
|
+
* @param input - What happened.
|
|
22
|
+
* @returns The signal as recorded, stamped and bounded.
|
|
23
|
+
*/
|
|
24
|
+
add(input) {
|
|
25
|
+
const paths = [...input.paths].sort();
|
|
26
|
+
const signal = {
|
|
27
|
+
...input,
|
|
28
|
+
at: input.at ?? Date.now(),
|
|
29
|
+
paths: paths.slice(0, SIGNAL_PATHS_MAX),
|
|
30
|
+
pathCount: paths.length
|
|
31
|
+
};
|
|
32
|
+
this._signals.push(signal);
|
|
33
|
+
while (this._signals.length > SIGNAL_LOG_MAX) this._signals.shift();
|
|
34
|
+
this._totals.set(signal.kind, (this._totals.get(signal.kind) ?? 0) + 1);
|
|
35
|
+
for (const listener of this._listeners) {
|
|
36
|
+
try {
|
|
37
|
+
listener(signal);
|
|
38
|
+
} catch {
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return signal;
|
|
33
42
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
return
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
43
|
+
/**
|
|
44
|
+
* Records a signal at most once per agent, for a standing condition.
|
|
45
|
+
*
|
|
46
|
+
* A misconfiguration is true for the life of the process, so reporting it per
|
|
47
|
+
* event would bury everything else.
|
|
48
|
+
* @param key - What is being reported once.
|
|
49
|
+
* @param input - What happened.
|
|
50
|
+
* @returns The signal, or `undefined` if this key was already reported.
|
|
51
|
+
*/
|
|
52
|
+
addOnce(key, input) {
|
|
53
|
+
if (this._once.has(key)) return void 0;
|
|
54
|
+
this._once.add(key);
|
|
55
|
+
while (this._once.size > SIGNAL_ONCE_MAX) {
|
|
56
|
+
this._once.delete(this._once.values().next().value);
|
|
57
|
+
}
|
|
58
|
+
return this.add(input);
|
|
59
|
+
}
|
|
60
|
+
/** Every signal kept, oldest first. */
|
|
61
|
+
get all() {
|
|
62
|
+
return this._signals;
|
|
63
|
+
}
|
|
64
|
+
/** Only the signals a person still has to act on. */
|
|
65
|
+
get needingAction() {
|
|
66
|
+
return this._signals.filter((s) => s.action === "required");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* How many of each kind have ever been recorded, dropped ones included.
|
|
70
|
+
* @returns The counts, keyed by kind.
|
|
71
|
+
*/
|
|
72
|
+
totals() {
|
|
73
|
+
return Object.fromEntries(this._totals);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Subscribes to signals as they happen.
|
|
77
|
+
* @param listener - Called once per signal.
|
|
78
|
+
* @returns Unsubscribes.
|
|
79
|
+
*/
|
|
80
|
+
subscribe(listener) {
|
|
81
|
+
this._listeners.add(listener);
|
|
82
|
+
return () => {
|
|
83
|
+
this._listeners.delete(listener);
|
|
71
84
|
};
|
|
72
85
|
}
|
|
73
86
|
/**
|
|
74
|
-
*
|
|
75
|
-
* @
|
|
76
|
-
*/
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
87
|
+
* What to persist.
|
|
88
|
+
* @returns The log, ready to serialise.
|
|
89
|
+
*/
|
|
90
|
+
persisted() {
|
|
91
|
+
return { signals: [...this._signals], totals: this.totals() };
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Restores a persisted log, so a host that starts later still sees what
|
|
95
|
+
* happened while it was not running.
|
|
96
|
+
*
|
|
97
|
+
* Tolerant by construction: a log that cannot be understood is skipped
|
|
98
|
+
* rather than thrown, because a corrupt notification file must never stop a
|
|
99
|
+
* folder from syncing.
|
|
100
|
+
* @param raw - What was read from disk.
|
|
101
|
+
*/
|
|
102
|
+
restore(raw) {
|
|
103
|
+
if (typeof raw !== "object" || raw === null) return;
|
|
104
|
+
const log = raw;
|
|
105
|
+
if (Array.isArray(log.signals)) {
|
|
106
|
+
for (const entry of log.signals) {
|
|
107
|
+
if (!FsSignals._isSignal(entry)) continue;
|
|
108
|
+
this._signals.push(entry);
|
|
109
|
+
}
|
|
110
|
+
while (this._signals.length > SIGNAL_LOG_MAX) this._signals.shift();
|
|
90
111
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
this._nextRepairAt = now + this._options.graceMs;
|
|
98
|
-
return;
|
|
112
|
+
if (typeof log.totals === "object" && log.totals !== null) {
|
|
113
|
+
for (const [kind, count] of Object.entries(log.totals)) {
|
|
114
|
+
if (typeof count === "number" && Number.isFinite(count)) {
|
|
115
|
+
this._totals.set(kind, count);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
99
118
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
hubRef,
|
|
117
|
-
localRef: view.currentRef,
|
|
118
|
-
attempt: this._attempts
|
|
119
|
-
};
|
|
120
|
-
this._deps.repair(decision, hubRef, [...hubPredecessors], this._attempts);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Whether a restored entry is shaped like a signal.
|
|
122
|
+
*
|
|
123
|
+
* Only the fields something downstream reads without checking. A log written
|
|
124
|
+
* by a newer build may carry a `kind` this one has never heard of, and that
|
|
125
|
+
* is kept rather than dropped: an unknown kind is still a true record of
|
|
126
|
+
* something that happened, and dropping it would make a downgrade lose
|
|
127
|
+
* history.
|
|
128
|
+
* @param value - The entry.
|
|
129
|
+
* @returns Whether it can be kept.
|
|
130
|
+
*/
|
|
131
|
+
static _isSignal(value) {
|
|
132
|
+
if (typeof value !== "object" || value === null) return false;
|
|
133
|
+
const entry = value;
|
|
134
|
+
return typeof entry.kind === "string" && typeof entry.at === "number" && Array.isArray(entry.paths) && typeof entry.pathCount === "number" && typeof entry.action === "string";
|
|
121
135
|
}
|
|
122
136
|
}
|
|
137
|
+
const ATOMIC_TMP_PREFIX = ".fsagent-tmp-";
|
|
138
|
+
const atomicTmpPath = (filePath) => {
|
|
139
|
+
const rnd = `${Date.now().toString(36)}-${Math.floor(
|
|
140
|
+
Math.random() * 1e9
|
|
141
|
+
).toString(36)}`;
|
|
142
|
+
return join(dirname(filePath), `${ATOMIC_TMP_PREFIX}${rnd}`);
|
|
143
|
+
};
|
|
144
|
+
const atomicWriteFile = async (filePath, content) => {
|
|
145
|
+
const tmp = atomicTmpPath(filePath);
|
|
146
|
+
try {
|
|
147
|
+
await writeFile(tmp, content);
|
|
148
|
+
await rename(tmp, filePath);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
try {
|
|
151
|
+
await unlink(tmp);
|
|
152
|
+
} catch {
|
|
153
|
+
}
|
|
154
|
+
throw err;
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const atomicWriteStream = async (filePath, stream, wrapReadError) => {
|
|
158
|
+
const tmp = atomicTmpPath(filePath);
|
|
159
|
+
const handle = await open(tmp, "w");
|
|
160
|
+
try {
|
|
161
|
+
const reader = stream.getReader();
|
|
162
|
+
for (; ; ) {
|
|
163
|
+
let chunk;
|
|
164
|
+
try {
|
|
165
|
+
chunk = await reader.read();
|
|
166
|
+
} catch (error) {
|
|
167
|
+
throw wrapReadError ? wrapReadError(error) : error;
|
|
168
|
+
}
|
|
169
|
+
if (chunk.done) break;
|
|
170
|
+
await handle.write(chunk.value);
|
|
171
|
+
}
|
|
172
|
+
} catch (error) {
|
|
173
|
+
await handle.close();
|
|
174
|
+
await unlink(tmp).catch(() => {
|
|
175
|
+
});
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
await handle.close();
|
|
179
|
+
try {
|
|
180
|
+
await rename(tmp, filePath);
|
|
181
|
+
} catch (err) {
|
|
182
|
+
await unlink(tmp).catch(() => {
|
|
183
|
+
});
|
|
184
|
+
throw err;
|
|
185
|
+
}
|
|
186
|
+
};
|
|
123
187
|
const STREAM_ABOVE_BYTES = 4 * 1024 * 1024;
|
|
124
188
|
const storeFileAsBlob = async (bs, handle, size) => {
|
|
125
189
|
if (size <= STREAM_ABOVE_BYTES) {
|
|
@@ -194,17 +258,7 @@ class FsBlobAdapter {
|
|
|
194
258
|
await mkdir(dir, { recursive: true });
|
|
195
259
|
}
|
|
196
260
|
const stream = await bs.getBlobStream(metadata.blobId);
|
|
197
|
-
|
|
198
|
-
try {
|
|
199
|
-
const reader = stream.getReader();
|
|
200
|
-
for (; ; ) {
|
|
201
|
-
const { done, value } = await reader.read();
|
|
202
|
-
if (done) break;
|
|
203
|
-
await handle.write(value);
|
|
204
|
-
}
|
|
205
|
-
} finally {
|
|
206
|
-
await handle.close();
|
|
207
|
-
}
|
|
261
|
+
await atomicWriteStream(targetPath, stream);
|
|
208
262
|
if (preserveMtime && metadata.mtime) {
|
|
209
263
|
const mtime = new Date(metadata.mtime);
|
|
210
264
|
await utimes(targetPath, mtime, mtime);
|
|
@@ -250,248 +304,6 @@ class FsBlobAdapter {
|
|
|
250
304
|
return new FsBlobAdapter();
|
|
251
305
|
}
|
|
252
306
|
}
|
|
253
|
-
const DIR_MARKER = "<dir>";
|
|
254
|
-
function fsTreeToContentMap(tree) {
|
|
255
|
-
const map = /* @__PURE__ */ new Map();
|
|
256
|
-
for (const [, node] of tree.trees) {
|
|
257
|
-
const meta = node.meta;
|
|
258
|
-
if (meta?.type === "file") {
|
|
259
|
-
map.set(
|
|
260
|
-
meta.relativePath,
|
|
261
|
-
meta.blobId ?? ""
|
|
262
|
-
);
|
|
263
|
-
} else if (meta?.type === "directory" && meta.relativePath !== ".") {
|
|
264
|
-
map.set(meta.relativePath, DIR_MARKER);
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
return map;
|
|
268
|
-
}
|
|
269
|
-
function compareTips(a, b) {
|
|
270
|
-
if (a.timestamp !== b.timestamp) {
|
|
271
|
-
return a.timestamp - b.timestamp;
|
|
272
|
-
}
|
|
273
|
-
if (a.clientId !== b.clientId) {
|
|
274
|
-
return a.clientId > b.clientId ? 1 : -1;
|
|
275
|
-
}
|
|
276
|
-
if (a.ref !== b.ref) {
|
|
277
|
-
return a.ref > b.ref ? 1 : -1;
|
|
278
|
-
}
|
|
279
|
-
return 0;
|
|
280
|
-
}
|
|
281
|
-
function decideWinner(a, b) {
|
|
282
|
-
return compareTips(a, b) >= 0 ? { winner: a, loser: b } : { winner: b, loser: a };
|
|
283
|
-
}
|
|
284
|
-
function findCommonAncestor(rows, tipA, tipB) {
|
|
285
|
-
const prevOf = /* @__PURE__ */ new Map();
|
|
286
|
-
for (const row of rows) {
|
|
287
|
-
prevOf.set(row.timeId, row.previous ?? []);
|
|
288
|
-
}
|
|
289
|
-
const ancestorsOfA = /* @__PURE__ */ new Set();
|
|
290
|
-
const stack = [tipA];
|
|
291
|
-
while (stack.length > 0) {
|
|
292
|
-
const id = stack.pop();
|
|
293
|
-
if (ancestorsOfA.has(id)) {
|
|
294
|
-
continue;
|
|
295
|
-
}
|
|
296
|
-
ancestorsOfA.add(id);
|
|
297
|
-
for (const p of prevOf.get(id) ?? []) {
|
|
298
|
-
stack.push(p);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
const visited = /* @__PURE__ */ new Set();
|
|
302
|
-
let frontier = [tipB];
|
|
303
|
-
while (frontier.length > 0) {
|
|
304
|
-
const next = [];
|
|
305
|
-
for (const id of frontier) {
|
|
306
|
-
if (ancestorsOfA.has(id)) {
|
|
307
|
-
return id;
|
|
308
|
-
}
|
|
309
|
-
if (visited.has(id)) {
|
|
310
|
-
continue;
|
|
311
|
-
}
|
|
312
|
-
visited.add(id);
|
|
313
|
-
for (const p of prevOf.get(id) ?? []) {
|
|
314
|
-
next.push(p);
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
frontier = next;
|
|
318
|
-
}
|
|
319
|
-
return null;
|
|
320
|
-
}
|
|
321
|
-
function formatConflictTimestamp(ms) {
|
|
322
|
-
const d = new Date(ms);
|
|
323
|
-
const p = (n, w = 2) => String(n).padStart(w, "0");
|
|
324
|
-
const date = `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}`;
|
|
325
|
-
const time = `${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`;
|
|
326
|
-
return `${date} ${time}`;
|
|
327
|
-
}
|
|
328
|
-
function conflictCopyName(relativePath, clientId, timestamp, taken) {
|
|
329
|
-
const slash = relativePath.lastIndexOf("/");
|
|
330
|
-
const dir = slash >= 0 ? relativePath.slice(0, slash + 1) : "";
|
|
331
|
-
const base = slash >= 0 ? relativePath.slice(slash + 1) : relativePath;
|
|
332
|
-
const dot = base.lastIndexOf(".");
|
|
333
|
-
const stem = dot > 0 ? base.slice(0, dot) : base;
|
|
334
|
-
const ext = dot > 0 ? base.slice(dot) : "";
|
|
335
|
-
const ts = formatConflictTimestamp(timestamp);
|
|
336
|
-
const marker = `(conflicted copy ${clientId} ${ts})`;
|
|
337
|
-
let candidate = `${dir}${stem} ${marker}${ext}`;
|
|
338
|
-
let n = 1;
|
|
339
|
-
while (taken.has(candidate)) {
|
|
340
|
-
candidate = `${dir}${stem} ${marker} (${n})${ext}`;
|
|
341
|
-
n++;
|
|
342
|
-
}
|
|
343
|
-
taken.add(candidate);
|
|
344
|
-
return candidate;
|
|
345
|
-
}
|
|
346
|
-
function threeWayMerge(o, ours, theirs, winnerSide, loserClientId, loserTimestamp) {
|
|
347
|
-
const merged = /* @__PURE__ */ new Map();
|
|
348
|
-
const copies = [];
|
|
349
|
-
const conflictPaths = [];
|
|
350
|
-
const taken = /* @__PURE__ */ new Set([...o.keys(), ...ours.keys(), ...theirs.keys()]);
|
|
351
|
-
const allPaths = new Set(taken);
|
|
352
|
-
for (const path of [...allPaths].sort()) {
|
|
353
|
-
const a = o.get(path);
|
|
354
|
-
const b = ours.get(path);
|
|
355
|
-
const c = theirs.get(path);
|
|
356
|
-
if (b === c) {
|
|
357
|
-
if (b !== void 0) {
|
|
358
|
-
merged.set(path, b);
|
|
359
|
-
}
|
|
360
|
-
continue;
|
|
361
|
-
}
|
|
362
|
-
if (b === a) {
|
|
363
|
-
if (c !== void 0) {
|
|
364
|
-
merged.set(path, c);
|
|
365
|
-
}
|
|
366
|
-
continue;
|
|
367
|
-
}
|
|
368
|
-
if (c === a) {
|
|
369
|
-
if (b !== void 0) {
|
|
370
|
-
merged.set(path, b);
|
|
371
|
-
}
|
|
372
|
-
continue;
|
|
373
|
-
}
|
|
374
|
-
conflictPaths.push(path);
|
|
375
|
-
const winnerVal = winnerSide === "ours" ? b : c;
|
|
376
|
-
const loserVal = winnerSide === "ours" ? c : b;
|
|
377
|
-
if (winnerVal !== void 0) {
|
|
378
|
-
merged.set(path, winnerVal);
|
|
379
|
-
}
|
|
380
|
-
if (loserVal !== void 0 && loserVal !== DIR_MARKER) {
|
|
381
|
-
const copyPath = conflictCopyName(
|
|
382
|
-
path,
|
|
383
|
-
loserClientId,
|
|
384
|
-
loserTimestamp,
|
|
385
|
-
taken
|
|
386
|
-
);
|
|
387
|
-
copies.push({ path: copyPath, blobId: loserVal });
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
return { merged, copies, conflictPaths };
|
|
391
|
-
}
|
|
392
|
-
class FsConflictResolver {
|
|
393
|
-
constructor(deps) {
|
|
394
|
-
this.deps = deps;
|
|
395
|
-
}
|
|
396
|
-
_log(level, msg) {
|
|
397
|
-
this.deps.log?.(level, `[FsConflictResolver] ${msg}`);
|
|
398
|
-
}
|
|
399
|
-
/**
|
|
400
|
-
* Resolves the conflict, returning the stored merge ref, or null when the
|
|
401
|
-
* conflict is not ours / not actionable.
|
|
402
|
-
* @param conflict - The detected DAG-branch conflict
|
|
403
|
-
* @returns The stored merge revision's root ref, or null
|
|
404
|
-
*/
|
|
405
|
-
async resolve(conflict) {
|
|
406
|
-
const { treeKey } = this.deps;
|
|
407
|
-
if (conflict.table !== treeKey) {
|
|
408
|
-
return null;
|
|
409
|
-
}
|
|
410
|
-
const tips = conflict.branches ?? [];
|
|
411
|
-
if (tips.length < 2) {
|
|
412
|
-
return null;
|
|
413
|
-
}
|
|
414
|
-
const rows = await this.deps.getInsertHistory(treeKey);
|
|
415
|
-
const rowByTimeId = new Map(
|
|
416
|
-
rows.map((r) => [r.timeId, r])
|
|
417
|
-
);
|
|
418
|
-
const branchTips = [];
|
|
419
|
-
for (const timeId of tips) {
|
|
420
|
-
const row = rowByTimeId.get(timeId);
|
|
421
|
-
const ref2 = await this.deps.getRefOfTimeId(treeKey, timeId);
|
|
422
|
-
branchTips.push({
|
|
423
|
-
timeId,
|
|
424
|
-
ref: ref2 ?? "",
|
|
425
|
-
clientId: row?.origin ?? "",
|
|
426
|
-
timestamp: row?.clientTimestamp ?? 0
|
|
427
|
-
});
|
|
428
|
-
}
|
|
429
|
-
const ordered = [...branchTips].sort((x, y) => compareTips(x, y));
|
|
430
|
-
const loserTip = ordered[0];
|
|
431
|
-
const winnerTip = ordered[1];
|
|
432
|
-
if (!loserTip.ref || !winnerTip.ref) {
|
|
433
|
-
this._log(
|
|
434
|
-
"warn",
|
|
435
|
-
`missing tree ref for a tip (loser=${loserTip.ref}, winner=${winnerTip.ref})`
|
|
436
|
-
);
|
|
437
|
-
return null;
|
|
438
|
-
}
|
|
439
|
-
const loserTipId = loserTip.timeId;
|
|
440
|
-
const winnerTipId = winnerTip.timeId;
|
|
441
|
-
const loserTree = await this.deps.fetchTree(loserTip.ref);
|
|
442
|
-
const winnerTree = await this.deps.fetchTree(winnerTip.ref);
|
|
443
|
-
const loserMap = fsTreeToContentMap(loserTree);
|
|
444
|
-
const winnerMap = fsTreeToContentMap(winnerTree);
|
|
445
|
-
const ancestorTimeId = findCommonAncestor(rows, loserTipId, winnerTipId);
|
|
446
|
-
let ancestorMap = /* @__PURE__ */ new Map();
|
|
447
|
-
if (ancestorTimeId) {
|
|
448
|
-
const ancRef = await this.deps.getRefOfTimeId(treeKey, ancestorTimeId);
|
|
449
|
-
if (ancRef) {
|
|
450
|
-
ancestorMap = fsTreeToContentMap(await this.deps.fetchTree(ancRef));
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
const plan = threeWayMerge(
|
|
454
|
-
ancestorMap,
|
|
455
|
-
loserMap,
|
|
456
|
-
winnerMap,
|
|
457
|
-
"theirs",
|
|
458
|
-
loserTip.clientId,
|
|
459
|
-
loserTip.timestamp
|
|
460
|
-
);
|
|
461
|
-
await this.deps.restoreTree(winnerTree);
|
|
462
|
-
for (const [path, blobId] of plan.merged) {
|
|
463
|
-
if (blobId === DIR_MARKER) {
|
|
464
|
-
continue;
|
|
465
|
-
}
|
|
466
|
-
if (winnerMap.get(path) === blobId) {
|
|
467
|
-
continue;
|
|
468
|
-
}
|
|
469
|
-
await this.deps.writeFileAt(path, await this.deps.getBlobContent(blobId));
|
|
470
|
-
}
|
|
471
|
-
for (const [path, blobId] of winnerMap) {
|
|
472
|
-
if (blobId === DIR_MARKER) {
|
|
473
|
-
continue;
|
|
474
|
-
}
|
|
475
|
-
if (!plan.merged.has(path)) {
|
|
476
|
-
await this.deps.deleteFileAt(path);
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
for (const copy of plan.copies) {
|
|
480
|
-
await this.deps.writeFileAt(
|
|
481
|
-
copy.path,
|
|
482
|
-
await this.deps.getBlobContent(copy.blobId)
|
|
483
|
-
);
|
|
484
|
-
}
|
|
485
|
-
const mergedTree = await this.deps.scan();
|
|
486
|
-
const ref = await this.deps.storeMerge(mergedTree, [loserTipId, winnerTipId]);
|
|
487
|
-
this.deps.onMergeStored?.(ref);
|
|
488
|
-
this._log(
|
|
489
|
-
"info",
|
|
490
|
-
`resolved fork ${loserTipId.slice(0, 6)}…/${winnerTipId.slice(0, 6)}… → ${ref.slice(0, 8)}… (${plan.conflictPaths.length} conflict(s), ${plan.copies.length} copy/ies)`
|
|
491
|
-
);
|
|
492
|
-
return ref;
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
307
|
class FsDbAdapter {
|
|
496
308
|
constructor(db, treeKey) {
|
|
497
309
|
this.db = db;
|
|
@@ -551,89 +363,1056 @@ class FsDbAdapter {
|
|
|
551
363
|
return this.db;
|
|
552
364
|
}
|
|
553
365
|
}
|
|
554
|
-
const
|
|
555
|
-
const
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
_missedChangesDuringPause = false;
|
|
566
|
-
/** Periodic full-rescan timer that catches events the native watcher drops. */
|
|
567
|
-
_safetyTimer = null;
|
|
568
|
-
/** When the current pause began, or null when not paused. */
|
|
569
|
-
_pausedAt = null;
|
|
570
|
-
/** Releases a pause whose resume never arrived (see {@link pauseWatch}). */
|
|
571
|
-
_autoResumeTimer = null;
|
|
572
|
-
/** Set by stopWatch() so a pending watcher reinstall / rescan bails out. */
|
|
573
|
-
_stopRequested = false;
|
|
574
|
-
/** Path→content cache backing {@link FsScanOptions.scanCachePath} (unused when unset). */
|
|
575
|
-
_scanCachePath;
|
|
576
|
-
/** Last-scan cache (loaded from disk); consulted to skip re-read/re-hash. */
|
|
577
|
-
_blobCache = /* @__PURE__ */ new Map();
|
|
578
|
-
/** Cache rebuilt during the CURRENT scan; becomes `_blobCache` at the end (self-pruning). */
|
|
579
|
-
_nextBlobCache = /* @__PURE__ */ new Map();
|
|
580
|
-
/** Ensures the persisted cache is read from disk only once. */
|
|
581
|
-
_cacheLoaded = false;
|
|
582
|
-
/** Entries that vanished mid-scan, counted per {@link scan} for one summary. */
|
|
583
|
-
_vanishedDuringScan = 0;
|
|
584
|
-
/** The scan pass running right now, if any. See {@link _scanAfterNow}. */
|
|
585
|
-
_activeScan = null;
|
|
586
|
-
/** The single follow-up pass everyone who arrived mid-scan is waiting on. */
|
|
587
|
-
_pendingScan = null;
|
|
588
|
-
constructor(rootPath, options = {}) {
|
|
589
|
-
this._rootPath = rootPath;
|
|
590
|
-
this._options = {
|
|
591
|
-
ignore: options.ignore || ["node_modules", ".git", "dist", "coverage"],
|
|
592
|
-
maxDepth: options.maxDepth,
|
|
593
|
-
followSymlinks: options.followSymlinks ?? false,
|
|
594
|
-
bs: options.bs,
|
|
595
|
-
scanCachePath: options.scanCachePath
|
|
596
|
-
};
|
|
597
|
-
this._bs = options.bs || new BsMem();
|
|
598
|
-
this._scanCachePath = options.scanCachePath;
|
|
599
|
-
}
|
|
600
|
-
get tree() {
|
|
601
|
-
return this._tree;
|
|
366
|
+
const FS_EDIT_ACTION = "putFsTree";
|
|
367
|
+
const DEFAULT_MAX_WALK = 500;
|
|
368
|
+
const createFsChainTables = async (db, treeKey) => {
|
|
369
|
+
await db.core.createTable(createEditTableCfg(treeKey));
|
|
370
|
+
await db.core.createTable(createMultiEditTableCfg(treeKey));
|
|
371
|
+
await db.core.createTable(createEditHistoryTableCfg(treeKey));
|
|
372
|
+
};
|
|
373
|
+
class FsEditChain {
|
|
374
|
+
constructor(_db, _treeKey) {
|
|
375
|
+
this._db = _db;
|
|
376
|
+
this._treeKey = _treeKey;
|
|
602
377
|
}
|
|
603
|
-
/**
|
|
604
|
-
|
|
605
|
-
|
|
378
|
+
/** The last own-lineage walk, keyed by the head it was computed for. */
|
|
379
|
+
_lineageCache;
|
|
380
|
+
/**
|
|
381
|
+
* Creates the chain's tables if absent. Where this node stands is not the
|
|
382
|
+
* chain's business: a table several nodes write has no tip of its own, and
|
|
383
|
+
* the agent keeps its head in its state file.
|
|
384
|
+
*/
|
|
385
|
+
async init() {
|
|
386
|
+
await createFsChainTables(this._db, this._treeKey);
|
|
606
387
|
}
|
|
607
|
-
|
|
608
|
-
|
|
388
|
+
/**
|
|
389
|
+
* Appends one entry.
|
|
390
|
+
* @param opts - What the change was; see {@link FsAppendOptions}.
|
|
391
|
+
* @returns The entry that was written.
|
|
392
|
+
*/
|
|
393
|
+
async append(opts) {
|
|
394
|
+
const changed = [...opts.changed ?? []].sort();
|
|
395
|
+
const removed = [...opts.removed ?? []].sort();
|
|
396
|
+
const previous = [...opts.previous];
|
|
397
|
+
const data = { treeRef: opts.treeRef, changed, removed };
|
|
398
|
+
const edit = {
|
|
399
|
+
name: `${FS_EDIT_ACTION} ${opts.treeRef}`,
|
|
400
|
+
action: {
|
|
401
|
+
name: FS_EDIT_ACTION,
|
|
402
|
+
type: FS_EDIT_ACTION,
|
|
403
|
+
data,
|
|
404
|
+
_hash: ""
|
|
405
|
+
},
|
|
406
|
+
_hash: ""
|
|
407
|
+
};
|
|
408
|
+
const editRef = this._refOf(
|
|
409
|
+
await this._db.addEdit(this._treeKey, edit),
|
|
410
|
+
"Edits"
|
|
411
|
+
);
|
|
412
|
+
const multiEditRef = this._refOf(
|
|
413
|
+
await this._db.addMultiEdit(this._treeKey, {
|
|
414
|
+
// A single-entry multiEdit per chain link. fs has no notion of several
|
|
415
|
+
// edits landing as one unit, and inventing one here would be a shape
|
|
416
|
+
// nothing produces.
|
|
417
|
+
previous: null,
|
|
418
|
+
edit: editRef,
|
|
419
|
+
_hash: ""
|
|
420
|
+
}),
|
|
421
|
+
"MultiEdits"
|
|
422
|
+
);
|
|
423
|
+
const isRoot = previous.length === 0 && changed.length === 0 && removed.length === 0;
|
|
424
|
+
const stamp = opts.timeId ?? (isRoot ? `0:${opts.treeRef}` : timeId());
|
|
425
|
+
const head = this._refOf(
|
|
426
|
+
await this._db.addEditHistory(this._treeKey, {
|
|
427
|
+
timeId: stamp,
|
|
428
|
+
multiEditRef,
|
|
429
|
+
dataRef: opts.treeRef,
|
|
430
|
+
previous,
|
|
431
|
+
_hash: ""
|
|
432
|
+
}),
|
|
433
|
+
"EditHistory"
|
|
434
|
+
);
|
|
435
|
+
if (this._lineageCache !== void 0 && previous.length === 1 && previous[0] === this._lineageCache.head) {
|
|
436
|
+
const refs = new Set(this._lineageCache.refs);
|
|
437
|
+
refs.add(head);
|
|
438
|
+
this._lineageCache = { head, refs };
|
|
439
|
+
}
|
|
440
|
+
return { head, timeId: stamp, treeRef: opts.treeRef, previous, changed, removed };
|
|
609
441
|
}
|
|
610
|
-
|
|
611
|
-
|
|
442
|
+
/**
|
|
443
|
+
* Reads one entry back.
|
|
444
|
+
* @param head - The `EditHistory` ref to read.
|
|
445
|
+
* @returns The entry, or `undefined` when this node cannot resolve it — a
|
|
446
|
+
* ref a peer holds and we do not is the ordinary case, not an error.
|
|
447
|
+
*/
|
|
448
|
+
async entry(head) {
|
|
449
|
+
const histories = await this._db.getEditHistories(this._treeKey, head);
|
|
450
|
+
if (histories.length === 0) return void 0;
|
|
451
|
+
const history = histories[0];
|
|
452
|
+
const multiEdits = await this._db.getMultiEdits(
|
|
453
|
+
this._treeKey,
|
|
454
|
+
history.multiEditRef
|
|
455
|
+
);
|
|
456
|
+
if (multiEdits.length === 0) return void 0;
|
|
457
|
+
const edits = await this._db.getEdits(this._treeKey, multiEdits[0].edit);
|
|
458
|
+
if (edits.length === 0) return void 0;
|
|
459
|
+
const data = edits[0].action?.data;
|
|
460
|
+
return {
|
|
461
|
+
head,
|
|
462
|
+
timeId: history.timeId,
|
|
463
|
+
treeRef: history.dataRef,
|
|
464
|
+
previous: [...history.previous ?? []],
|
|
465
|
+
changed: [...data?.changed ?? []],
|
|
466
|
+
removed: [...data?.removed ?? []]
|
|
467
|
+
};
|
|
612
468
|
}
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
469
|
+
/**
|
|
470
|
+
* How two heads stand, and for a fork the ancestor to merge against.
|
|
471
|
+
*
|
|
472
|
+
* `same` — the one head. `behind` — theirs descends from ours. `ahead` —
|
|
473
|
+
* ours descends from theirs. A descent found is proof, whatever else in
|
|
474
|
+
* either history cannot be read. `fork` — neither descends from the other:
|
|
475
|
+
* `base` is a common ancestor no other common ancestor descends from, the
|
|
476
|
+
* smallest ref of them when there are several, so every node merging the
|
|
477
|
+
* same two heads merges against the same base. `undefined` when the two
|
|
478
|
+
* share no history within the walk. `incomplete` — no descent was found and
|
|
479
|
+
* an entry could not be read, so a fork cannot be told from a lag.
|
|
480
|
+
*
|
|
481
|
+
* A walk that exhausts `maxWalk` with everything readable answers `fork`:
|
|
482
|
+
* less precise than the truth, never destructive.
|
|
483
|
+
* @param ours - This node's head.
|
|
484
|
+
* @param theirs - The head that arrived.
|
|
485
|
+
* @param maxWalk - Give up past this many entries per side.
|
|
486
|
+
* @returns The relation, and the merge base of a fork.
|
|
487
|
+
*/
|
|
488
|
+
async relate(ours, theirs, maxWalk = DEFAULT_MAX_WALK) {
|
|
489
|
+
if (ours === theirs) return { verdict: "same" };
|
|
490
|
+
const fromTheirs = await this._parentsOf(theirs, maxWalk);
|
|
491
|
+
if (fromTheirs.parents.has(ours)) return { verdict: "behind" };
|
|
492
|
+
const fromOurs = await this._parentsOf(ours, maxWalk);
|
|
493
|
+
if (fromOurs.parents.has(theirs)) return { verdict: "ahead" };
|
|
494
|
+
if (fromTheirs.holed || fromOurs.holed) return { verdict: "incomplete" };
|
|
495
|
+
const common = [...fromOurs.parents.keys()].filter(
|
|
496
|
+
(ref) => fromTheirs.parents.has(ref)
|
|
497
|
+
);
|
|
498
|
+
const dominated = /* @__PURE__ */ new Set();
|
|
499
|
+
for (const ref of common) {
|
|
500
|
+
const stack = [...fromOurs.parents.get(ref)];
|
|
501
|
+
while (stack.length > 0) {
|
|
502
|
+
const below = stack.pop();
|
|
503
|
+
if (dominated.has(below)) continue;
|
|
504
|
+
dominated.add(below);
|
|
505
|
+
stack.push(...fromOurs.parents.get(below) ?? []);
|
|
620
506
|
}
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
507
|
+
}
|
|
508
|
+
const best = common.filter((ref) => !dominated.has(ref)).sort();
|
|
509
|
+
return { verdict: "fork", base: best[0] };
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* The `previous` of every entry reachable from `head`, by generation.
|
|
513
|
+
* @param head - Where to start.
|
|
514
|
+
* @param maxWalk - Give up past this many entries.
|
|
515
|
+
* @returns Each entry read, mapped to its parents, and whether an entry
|
|
516
|
+
* could not be read.
|
|
517
|
+
*/
|
|
518
|
+
async _parentsOf(head, maxWalk) {
|
|
519
|
+
const parents = /* @__PURE__ */ new Map();
|
|
520
|
+
let holed = false;
|
|
521
|
+
let frontier = [head];
|
|
522
|
+
while (frontier.length > 0 && parents.size < maxWalk) {
|
|
523
|
+
const next = [];
|
|
524
|
+
for (const ref of new Set(frontier)) {
|
|
525
|
+
if (parents.has(ref)) continue;
|
|
526
|
+
const entry = await this.entry(ref);
|
|
527
|
+
if (!entry) {
|
|
528
|
+
holed = true;
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
parents.set(ref, entry.previous);
|
|
532
|
+
next.push(...entry.previous);
|
|
626
533
|
}
|
|
627
|
-
|
|
628
|
-
`Cannot access root path "${this._rootPath}": ${error instanceof Error ? error.message : String(error)}`
|
|
629
|
-
);
|
|
534
|
+
frontier = next;
|
|
630
535
|
}
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
536
|
+
return { parents, holed };
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Every entry reachable from `head`, itself included.
|
|
540
|
+
*
|
|
541
|
+
* `holed` — an entry could not be RESOLVED. The caller must conclude
|
|
542
|
+
* nothing: the unreachable part may contain the very ref it was looking for,
|
|
543
|
+
* and a walk that answers "not an ancestor" on that basis is how a node
|
|
544
|
+
* decides it is ahead of a peer it is actually behind.
|
|
545
|
+
*
|
|
546
|
+
* `bounded` — the walk ran out of budget with everything it asked for
|
|
547
|
+
* readable. A different statement, and a usable one: no relation within this
|
|
548
|
+
* many entries of history. See {@link relate}.
|
|
549
|
+
* @param head - Where to start.
|
|
550
|
+
* @param maxWalk - Give up past this many entries.
|
|
551
|
+
* @returns The refs reached, whether anything was unreadable, and whether
|
|
552
|
+
* the budget ran out.
|
|
553
|
+
*/
|
|
554
|
+
async _ancestorsOf(head, maxWalk = DEFAULT_MAX_WALK) {
|
|
555
|
+
const refs = /* @__PURE__ */ new Set();
|
|
556
|
+
let holed = false;
|
|
557
|
+
let bounded = false;
|
|
558
|
+
let frontier = [head];
|
|
559
|
+
while (frontier.length > 0) {
|
|
560
|
+
const wanted = frontier.filter((ref) => !refs.has(ref) && !!refs.add(ref));
|
|
561
|
+
if (wanted.length === 0) break;
|
|
562
|
+
if (refs.size > maxWalk) {
|
|
563
|
+
bounded = true;
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
const next = [];
|
|
567
|
+
for (const ref of wanted) {
|
|
568
|
+
const entry = await this.entry(ref);
|
|
569
|
+
if (!entry) {
|
|
570
|
+
holed = true;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
for (const previous of entry.previous) next.push(previous);
|
|
574
|
+
}
|
|
575
|
+
frontier = next;
|
|
634
576
|
}
|
|
635
|
-
|
|
577
|
+
return { refs, holed, bounded };
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Every entry this node's own head descends from, itself included.
|
|
581
|
+
*
|
|
582
|
+
* Cached on the head it was computed for. Announcements arrive in bursts and
|
|
583
|
+
* this node's head changes only when it records an entry, so the walk is
|
|
584
|
+
* done once per state rather than once per announcement.
|
|
585
|
+
* @param ourHead - This node's head, or `undefined` when it has none.
|
|
586
|
+
* @param maxWalk - Give up past this many entries.
|
|
587
|
+
* @returns The refs reached, or `undefined` when the walk could not be
|
|
588
|
+
* trusted — an unreadable entry means the stop set is unknown, not empty.
|
|
589
|
+
*/
|
|
590
|
+
async _ourLineage(ourHead, maxWalk) {
|
|
591
|
+
if (ourHead === void 0) return /* @__PURE__ */ new Set();
|
|
592
|
+
if (this._lineageCache?.head === ourHead) return this._lineageCache.refs;
|
|
593
|
+
const walk = await this._ancestorsOf(ourHead, maxWalk);
|
|
594
|
+
if (walk.holed) return void 0;
|
|
595
|
+
this._lineageCache = { head: ourHead, refs: walk.refs };
|
|
596
|
+
return walk.refs;
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* The newest edit on this lineage that CHANGED or REMOVED a given path.
|
|
600
|
+
*
|
|
601
|
+
* **The per-path question, and the one the conflict resolver could not ask.**
|
|
602
|
+
* `compareTips` orders a BRANCH by its tip, and the caller then uses that one
|
|
603
|
+
* verdict for every path the two branches disagree about — so a tip wins
|
|
604
|
+
* paths it never touched. Measured: a node that had been offline came back,
|
|
605
|
+
* wrote one file of its own, and that newer tip took `doc.txt` as well,
|
|
606
|
+
* rolling the writer's own folder from v8 back to v5.
|
|
607
|
+
*
|
|
608
|
+
* Asking per path answers it exactly: the last edit naming `doc.txt` is the
|
|
609
|
+
* writer's, and the returning node's entry does not name it at all, so it
|
|
610
|
+
* does not count for it. No clock is involved — the answer is read out of the
|
|
611
|
+
* shared history, so every node computes the same winner on its own.
|
|
612
|
+
*
|
|
613
|
+
* **A removal counts as touching the path.** An edit/delete conflict is still
|
|
614
|
+
* two people acting on one file, and the one who acted later decides it.
|
|
615
|
+
*
|
|
616
|
+
* `undefined` means "cannot say": either nothing on this lineage ever named
|
|
617
|
+
* the path, or the walk could not be read to the end. The caller must not
|
|
618
|
+
* read that as "nobody edited it" — it falls back to the branch-level order.
|
|
619
|
+
* @param head - The lineage's tip.
|
|
620
|
+
* @param path - The relative path being decided.
|
|
621
|
+
* @param maxWalk - Give up past this many entries.
|
|
622
|
+
* @returns The newest entry naming `path`, or `undefined`.
|
|
623
|
+
*/
|
|
624
|
+
async lastEditOf(head, path, maxWalk = DEFAULT_MAX_WALK) {
|
|
625
|
+
const seen = /* @__PURE__ */ new Set();
|
|
626
|
+
let frontier = [head];
|
|
627
|
+
while (frontier.length > 0) {
|
|
628
|
+
const wanted = frontier.filter((ref) => !seen.has(ref) && !!seen.add(ref));
|
|
629
|
+
if (wanted.length === 0) break;
|
|
630
|
+
if (seen.size > maxWalk) break;
|
|
631
|
+
const next = [];
|
|
632
|
+
const here = [];
|
|
633
|
+
for (const ref of wanted) {
|
|
634
|
+
const entry = await this.entry(ref);
|
|
635
|
+
if (!entry) return void 0;
|
|
636
|
+
if (entry.changed.includes(path) || entry.removed.includes(path)) {
|
|
637
|
+
here.push(entry);
|
|
638
|
+
}
|
|
639
|
+
for (const previous of entry.previous) next.push(previous);
|
|
640
|
+
}
|
|
641
|
+
if (here.length > 0) {
|
|
642
|
+
const newest = here.map((entry) => entry.timeId).sort().pop();
|
|
643
|
+
return here.find((entry) => entry.timeId === newest);
|
|
644
|
+
}
|
|
645
|
+
frontier = next;
|
|
646
|
+
}
|
|
647
|
+
return void 0;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* The NET removals between a peer's head and a state this node knows.
|
|
651
|
+
*
|
|
652
|
+
* **Why a walk is needed at all, and it cost a red run to see.** A removal is
|
|
653
|
+
* stated ONCE, in the entry that made it. A node that was partitioned when it
|
|
654
|
+
* deleted a file states the removal in an entry nobody received; its next
|
|
655
|
+
* entry, after it rejoins, computes its `changed`/`removed` against its own
|
|
656
|
+
* last announcement and therefore says nothing about that deletion. So a peer
|
|
657
|
+
* reading only the head learns nothing, and the file survives on every node
|
|
658
|
+
* except the one that deleted it — which is the measured failure.
|
|
659
|
+
*
|
|
660
|
+
* Walking `previous` back to a state the receiver recognises closes exactly
|
|
661
|
+
* that gap, and the ancestry is reachable by hash alone (proven in
|
|
662
|
+
* `test/fs-chain-crosses-the-wire.spec.ts`).
|
|
663
|
+
*
|
|
664
|
+
* **Replayed oldest-first, so a re-add cancels a removal.** A path deleted
|
|
665
|
+
* and then created again inside the walked range is not a removal at all,
|
|
666
|
+
* and taking the union of `removed` would delete it. Order is the whole
|
|
667
|
+
* correctness of this function.
|
|
668
|
+
*
|
|
669
|
+
* **`complete` is mongo's contract, and it matters more than the result.**
|
|
670
|
+
* When an entry cannot be resolved the walk is truncated, and the caller MUST
|
|
671
|
+
* NOT treat the answer as authoritative — ancestors beyond the missing row
|
|
672
|
+
* are unknown, and one of them may be the re-add that cancels a removal we
|
|
673
|
+
* did collect. `@rljson/mongo-agent` states it as: *"a caller must not latch
|
|
674
|
+
* the head; ancestors beyond the missing row would otherwise be lost
|
|
675
|
+
* forever"*.
|
|
676
|
+
* **Where the walk stops is THIS NODE'S OWN LINEAGE, asked of the chain.**
|
|
677
|
+
* It used to be a set of content refs: the current one, the last applied one,
|
|
678
|
+
* and a thousand remembered past states. That set approximated "everywhere I
|
|
679
|
+
* have been" — capped, so a long-lived node forgot its oldest states, and
|
|
680
|
+
* matched BY CONTENT, so an entry on a lineage this node never travelled
|
|
681
|
+
* stopped the walk whenever it happened to produce bytes this node also
|
|
682
|
+
* holds. Identical content across nodes was rare while mtime was in the
|
|
683
|
+
* identity; now it is the norm.
|
|
684
|
+
*
|
|
685
|
+
* Neither is a measured data loss — stopping early collects FEWER removals,
|
|
686
|
+
* which is the safe direction, and content equality does mean the folder was
|
|
687
|
+
* in that state. It is a heuristic standing in for a question the chain can
|
|
688
|
+
* answer exactly, which is the whole reason the chain exists.
|
|
689
|
+
* @param head - The peer's head.
|
|
690
|
+
* @param ourHead - This node's own head, or `undefined` when it has none —
|
|
691
|
+
* a node with no history of its own recognises no state, so nothing stops
|
|
692
|
+
* the walk short of `maxWalk`.
|
|
693
|
+
* @param maxWalk - Give up past this many entries. A walk this deep is a
|
|
694
|
+
* cold replay rather than a catch-up, and left unbounded it pins a core on
|
|
695
|
+
* a long chain.
|
|
696
|
+
* **Both halves of the net delta are returned**: a path deleted and created
|
|
697
|
+
* again inside the walked range is a change, not a removal, and only the
|
|
698
|
+
* second half can say so.
|
|
699
|
+
* @returns The net removals, the net changes, and whether the walk resolved
|
|
700
|
+
* completely.
|
|
701
|
+
*/
|
|
702
|
+
async collectRemovals(head, ourHead, maxWalk = DEFAULT_MAX_WALK) {
|
|
703
|
+
const stopAt = await this._ourLineage(ourHead, maxWalk);
|
|
704
|
+
if (stopAt === void 0) {
|
|
705
|
+
return { removed: [], changed: [], complete: false };
|
|
706
|
+
}
|
|
707
|
+
const walked = [];
|
|
708
|
+
const seen = /* @__PURE__ */ new Set();
|
|
709
|
+
let complete = true;
|
|
710
|
+
let frontier = [head];
|
|
711
|
+
while (frontier.length > 0) {
|
|
712
|
+
const wanted = frontier.filter((ref) => !seen.has(ref) && !!seen.add(ref));
|
|
713
|
+
if (wanted.length === 0) break;
|
|
714
|
+
if (walked.length + wanted.length > maxWalk) {
|
|
715
|
+
complete = false;
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
const next = [];
|
|
719
|
+
for (const ref of wanted) {
|
|
720
|
+
const entry = await this.entry(ref);
|
|
721
|
+
if (!entry) {
|
|
722
|
+
complete = false;
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
if (stopAt.has(ref)) continue;
|
|
726
|
+
walked.push(entry);
|
|
727
|
+
for (const previous of entry.previous) next.push(previous);
|
|
728
|
+
}
|
|
729
|
+
frontier = next;
|
|
730
|
+
}
|
|
731
|
+
const order = [...walked].reverse();
|
|
732
|
+
const removed = /* @__PURE__ */ new Set();
|
|
733
|
+
const changed = /* @__PURE__ */ new Set();
|
|
734
|
+
for (const entry of order) {
|
|
735
|
+
for (const path of entry.removed) {
|
|
736
|
+
removed.add(path);
|
|
737
|
+
changed.delete(path);
|
|
738
|
+
}
|
|
739
|
+
for (const path of entry.changed) {
|
|
740
|
+
changed.add(path);
|
|
741
|
+
removed.delete(path);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return {
|
|
745
|
+
removed: [...removed].sort(),
|
|
746
|
+
changed: [...changed].sort(),
|
|
747
|
+
complete
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Pulls the generated ref out of an insert result.
|
|
752
|
+
* @param result - What `db.add*` returned.
|
|
753
|
+
* @param suffix - The table suffix, e.g. `Edits`.
|
|
754
|
+
* @returns The ref.
|
|
755
|
+
*/
|
|
756
|
+
_refOf(result, suffix) {
|
|
757
|
+
const rows = result;
|
|
758
|
+
const ref = rows?.[0]?.[`${this._treeKey}${suffix}Ref`];
|
|
759
|
+
if (!ref) throw new Error(`FsEditChain: no ref for ${suffix}`);
|
|
760
|
+
return ref;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
const ALL_GONE_MIN_FILES = 10;
|
|
764
|
+
const planJoin = (q) => {
|
|
765
|
+
const write = [];
|
|
766
|
+
const announce = [];
|
|
767
|
+
const recover = [];
|
|
768
|
+
const conflict = [];
|
|
769
|
+
for (const [path, hash] of q.head) {
|
|
770
|
+
const here = q.folder.get(path);
|
|
771
|
+
if (here === void 0) {
|
|
772
|
+
write.push(path);
|
|
773
|
+
} else if (here !== hash) {
|
|
774
|
+
conflict.push(path);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
for (const path of q.folder.keys()) {
|
|
778
|
+
if (q.head.has(path)) continue;
|
|
779
|
+
if (q.removedEver.has(path)) {
|
|
780
|
+
recover.push(path);
|
|
781
|
+
} else {
|
|
782
|
+
announce.push(path);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
return {
|
|
786
|
+
write: write.sort(),
|
|
787
|
+
announce: announce.sort(),
|
|
788
|
+
recover: recover.sort(),
|
|
789
|
+
conflict: conflict.sort()
|
|
790
|
+
};
|
|
791
|
+
};
|
|
792
|
+
const DIR_MARKER = "<dir>";
|
|
793
|
+
const merge3 = (base, ours, theirs) => {
|
|
794
|
+
const merged = /* @__PURE__ */ new Map();
|
|
795
|
+
const conflicts = [];
|
|
796
|
+
const unknownStamps = [];
|
|
797
|
+
const taken = /* @__PURE__ */ new Set([
|
|
798
|
+
...base.keys(),
|
|
799
|
+
...ours.content.keys(),
|
|
800
|
+
...theirs.content.keys()
|
|
801
|
+
]);
|
|
802
|
+
const owned = /* @__PURE__ */ new Map();
|
|
803
|
+
for (const path of [...taken].sort()) {
|
|
804
|
+
const a = base.get(path);
|
|
805
|
+
const b = ours.content.get(path);
|
|
806
|
+
const c = theirs.content.get(path);
|
|
807
|
+
if (b === void 0 || c === void 0) continue;
|
|
808
|
+
if (b === DIR_MARKER === (c === DIR_MARKER)) continue;
|
|
809
|
+
const dirSide = b === DIR_MARKER ? ours : theirs;
|
|
810
|
+
const fileSide = b === DIR_MARKER ? theirs : ours;
|
|
811
|
+
const dirUntouched = dirSide.content.get(path) === a && !subtreeChanged(base, dirSide, path);
|
|
812
|
+
const fileUntouched = fileSide.content.get(path) === a;
|
|
813
|
+
if (dirUntouched || fileUntouched) continue;
|
|
814
|
+
owned.set(path, dirSide);
|
|
815
|
+
const copyPath = copyName(
|
|
816
|
+
path,
|
|
817
|
+
fileSide.introducer(path).nodeId,
|
|
818
|
+
void 0,
|
|
819
|
+
taken
|
|
820
|
+
);
|
|
821
|
+
merged.set(copyPath, fileSide.content.get(path));
|
|
822
|
+
conflicts.push({ kind: "collision/type", path, copyPath });
|
|
823
|
+
}
|
|
824
|
+
for (const path of [...taken].sort()) {
|
|
825
|
+
const dir = [...owned.keys()].find(
|
|
826
|
+
(d) => path === d || path.startsWith(`${d}/`)
|
|
827
|
+
);
|
|
828
|
+
if (dir !== void 0) {
|
|
829
|
+
const value = owned.get(dir).content.get(path);
|
|
830
|
+
if (value !== void 0) merged.set(path, value);
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
const a = base.get(path);
|
|
834
|
+
const b = ours.content.get(path);
|
|
835
|
+
const c = theirs.content.get(path);
|
|
836
|
+
if (b === c || c === a) {
|
|
837
|
+
if (b !== void 0) merged.set(path, b);
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
if (b === a) {
|
|
841
|
+
if (c !== void 0) merged.set(path, c);
|
|
842
|
+
continue;
|
|
843
|
+
}
|
|
844
|
+
if (b === void 0 || c === void 0) {
|
|
845
|
+
merged.set(path, b ?? c);
|
|
846
|
+
conflicts.push({ kind: "conflict/arbitrary", path });
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
const mine = ours.introducer(path);
|
|
850
|
+
const yours = theirs.introducer(path);
|
|
851
|
+
if (!mine.stamp || !yours.stamp) {
|
|
852
|
+
unknownStamps.push(path);
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
const order = compareRefStamp(mine.stamp, yours.stamp) || (mine.entry < yours.entry ? -1 : 1);
|
|
856
|
+
const [winner, loser, loserIntroducer] = order >= 0 ? [b, c, yours] : [c, b, mine];
|
|
857
|
+
merged.set(path, winner);
|
|
858
|
+
const copyPath = copyName(
|
|
859
|
+
path,
|
|
860
|
+
loserIntroducer.nodeId,
|
|
861
|
+
loserIntroducer.stamp,
|
|
862
|
+
taken
|
|
863
|
+
);
|
|
864
|
+
merged.set(copyPath, loser);
|
|
865
|
+
conflicts.push({ kind: "conflict/arbitrary", path, copyPath });
|
|
866
|
+
}
|
|
867
|
+
return { merged, conflicts, unknownStamps };
|
|
868
|
+
};
|
|
869
|
+
const subtreeChanged = (base, side, dir) => {
|
|
870
|
+
const prefix = `${dir}/`;
|
|
871
|
+
for (const path of /* @__PURE__ */ new Set([...base.keys(), ...side.content.keys()])) {
|
|
872
|
+
if (path.startsWith(prefix) && base.get(path) !== side.content.get(path)) {
|
|
873
|
+
return true;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
return false;
|
|
877
|
+
};
|
|
878
|
+
const copyName = (path, nodeId, stamp, taken) => {
|
|
879
|
+
const who = [stamp ? `${stamp.hub}-${stamp.n}` : "", nodeId].filter((part) => part !== "").join(" ");
|
|
880
|
+
return unusedName(
|
|
881
|
+
path,
|
|
882
|
+
`(conflicted copy${who === "" ? "" : ` ${who}`})`,
|
|
883
|
+
taken
|
|
884
|
+
);
|
|
885
|
+
};
|
|
886
|
+
const joinCopyName = (path, at, taken) => {
|
|
887
|
+
const d = new Date(at);
|
|
888
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
889
|
+
const date = `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}`;
|
|
890
|
+
const time = `${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`;
|
|
891
|
+
return unusedName(path, `(conflicted copy ${date} ${time} local)`, taken);
|
|
892
|
+
};
|
|
893
|
+
const recoveredName = (path, taken) => unusedName(path, "(recovered)", taken);
|
|
894
|
+
const unusedName = (path, marker, taken) => {
|
|
895
|
+
const slash = path.lastIndexOf("/");
|
|
896
|
+
const dir = path.slice(0, slash + 1);
|
|
897
|
+
const base = path.slice(slash + 1);
|
|
898
|
+
const dot = base.lastIndexOf(".");
|
|
899
|
+
const stem = dot > 0 ? base.slice(0, dot) : base;
|
|
900
|
+
const ext = dot > 0 ? base.slice(dot) : "";
|
|
901
|
+
let candidate = `${dir}${stem} ${marker}${ext}`;
|
|
902
|
+
for (let n = 1; taken.has(candidate); n++) {
|
|
903
|
+
candidate = `${dir}${stem} ${marker} (${n})${ext}`;
|
|
904
|
+
}
|
|
905
|
+
taken.add(candidate);
|
|
906
|
+
return candidate;
|
|
907
|
+
};
|
|
908
|
+
const receive = async (head, deps) => {
|
|
909
|
+
if (deps.ownHead() === void 0) return "no-head";
|
|
910
|
+
await deps.flushLocal();
|
|
911
|
+
const own = deps.ownHead();
|
|
912
|
+
if (head === own) return "in-sync";
|
|
913
|
+
const relation = await deps.relate(own, head);
|
|
914
|
+
switch (relation.verdict) {
|
|
915
|
+
case "same":
|
|
916
|
+
return "in-sync";
|
|
917
|
+
case "behind":
|
|
918
|
+
return deps.applyBehind(head);
|
|
919
|
+
case "ahead":
|
|
920
|
+
deps.announceOwn();
|
|
921
|
+
return "announced";
|
|
922
|
+
case "incomplete":
|
|
923
|
+
deps.blocked(head, "the history between the two heads cannot be read");
|
|
924
|
+
return "blocked";
|
|
925
|
+
}
|
|
926
|
+
const [ours, theirs] = await Promise.all([
|
|
927
|
+
deps.treeRefOf(own),
|
|
928
|
+
deps.treeRefOf(head)
|
|
929
|
+
]);
|
|
930
|
+
if (ours === void 0 || theirs === void 0) {
|
|
931
|
+
deps.blocked(head, "a forked head names a tree that cannot be read");
|
|
932
|
+
return "blocked";
|
|
933
|
+
}
|
|
934
|
+
if (ours === theirs) {
|
|
935
|
+
if (head < own) {
|
|
936
|
+
await deps.adopt(head);
|
|
937
|
+
return "adopted";
|
|
938
|
+
}
|
|
939
|
+
deps.announceOwn();
|
|
940
|
+
return "announced";
|
|
941
|
+
}
|
|
942
|
+
return deps.merge(head, relation.base);
|
|
943
|
+
};
|
|
944
|
+
const planAuthoring = (q) => {
|
|
945
|
+
const changed = [];
|
|
946
|
+
const removed = [];
|
|
947
|
+
for (const [path, value] of q.folder) {
|
|
948
|
+
if (q.head.get(path) !== value) changed.push(path);
|
|
949
|
+
}
|
|
950
|
+
for (const path of q.head.keys()) {
|
|
951
|
+
if (!q.folder.has(path)) removed.push(path);
|
|
952
|
+
}
|
|
953
|
+
if (changed.length === 0 && removed.length === 0) return { kind: "unchanged" };
|
|
954
|
+
const isFile = (value) => value !== void 0 && value !== DIR_MARKER;
|
|
955
|
+
const held = [...q.head.values()].filter(isFile).length;
|
|
956
|
+
const remaining = [...q.folder.values()].filter(isFile).length;
|
|
957
|
+
const stillHere = new Set([...q.folder.values()].filter(isFile));
|
|
958
|
+
const watched = (path) => {
|
|
959
|
+
for (let at = path; ; ) {
|
|
960
|
+
if (q.watched.has(at)) return true;
|
|
961
|
+
const slash = at.lastIndexOf("/");
|
|
962
|
+
if (slash < 0) return false;
|
|
963
|
+
at = at.slice(0, slash);
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
const disappeared = removed.filter(
|
|
967
|
+
(path) => isFile(q.head.get(path)) && !stillHere.has(q.head.get(path)) && !watched(path)
|
|
968
|
+
);
|
|
969
|
+
const mass = disappeared.length > q.minFiles && disappeared.length / held > q.maxRatio;
|
|
970
|
+
const allGone = disappeared.length > 0 && held > q.allGoneMinFiles && remaining <= q.allGoneMinFiles;
|
|
971
|
+
if (mass || allGone) return { kind: "refused", disappeared, held };
|
|
972
|
+
return { kind: "author", changed: changed.sort(), removed: removed.sort() };
|
|
973
|
+
};
|
|
974
|
+
const stampTableCfg = (key) => ({
|
|
975
|
+
key,
|
|
976
|
+
type: "components",
|
|
977
|
+
isHead: false,
|
|
978
|
+
isRoot: false,
|
|
979
|
+
isShared: true,
|
|
980
|
+
columns: [
|
|
981
|
+
{ key: "_hash", type: "string", titleShort: "Hash", titleLong: "Hash" },
|
|
982
|
+
{ key: "entry", type: "string", titleShort: "Entry", titleLong: "Chain entry" },
|
|
983
|
+
{ key: "domain", type: "string", titleShort: "Domain", titleLong: "Domain" },
|
|
984
|
+
{ key: "epoch", type: "number", titleShort: "Epoch", titleLong: "Hub epoch" },
|
|
985
|
+
{ key: "hub", type: "string", titleShort: "Hub", titleLong: "Stamping hub" },
|
|
986
|
+
{ key: "n", type: "number", titleShort: "N", titleLong: "Sequence" },
|
|
987
|
+
{ key: "walked", type: "boolean", titleShort: "Walked", titleLong: "Entries below stamped" }
|
|
988
|
+
]
|
|
989
|
+
});
|
|
990
|
+
class FsStamps {
|
|
991
|
+
constructor(_db, _treeKey, _previousOf) {
|
|
992
|
+
this._db = _db;
|
|
993
|
+
this._treeKey = _treeKey;
|
|
994
|
+
this._previousOf = _previousOf;
|
|
995
|
+
}
|
|
996
|
+
_byEntry = /* @__PURE__ */ new Map();
|
|
997
|
+
/** Stamped entries whose ancestors have not been walked yet. */
|
|
998
|
+
_open = /* @__PURE__ */ new Set();
|
|
999
|
+
/** The highest epoch heard, per domain. */
|
|
1000
|
+
_maxEpoch = /* @__PURE__ */ new Map();
|
|
1001
|
+
/** The table the stamps are kept in. */
|
|
1002
|
+
get table() {
|
|
1003
|
+
return `${this._treeKey}EditStamps`;
|
|
1004
|
+
}
|
|
1005
|
+
/** How many walks stopped short and wait for {@link settle}. */
|
|
1006
|
+
get open() {
|
|
1007
|
+
return this._open.size;
|
|
1008
|
+
}
|
|
1009
|
+
// ...........................................................................
|
|
1010
|
+
/** Creates the table if absent, and loads what it holds. */
|
|
1011
|
+
async init() {
|
|
1012
|
+
await this._db.core.createTable(stampTableCfg(this.table));
|
|
1013
|
+
const dump = await this._db.core.dumpTable(this.table);
|
|
1014
|
+
const walked = /* @__PURE__ */ new Set();
|
|
1015
|
+
for (const row of dump[this.table]._data) {
|
|
1016
|
+
const { entry, domain, epoch, hub, n } = row;
|
|
1017
|
+
this._set(entry, { domain, epoch, hub, n });
|
|
1018
|
+
if (row.walked) walked.add(entry);
|
|
1019
|
+
}
|
|
1020
|
+
for (const entry of this._byEntry.keys()) {
|
|
1021
|
+
if (!walked.has(entry)) this._open.add(entry);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* The stamp an entry reached the fleet with.
|
|
1026
|
+
* @param entry - The chain entry.
|
|
1027
|
+
* @returns Its stamp, or `undefined` while nobody has told this node.
|
|
1028
|
+
*/
|
|
1029
|
+
get(entry) {
|
|
1030
|
+
return this._byEntry.get(entry);
|
|
1031
|
+
}
|
|
1032
|
+
// ...........................................................................
|
|
1033
|
+
/**
|
|
1034
|
+
* Records the stamp a head arrived with, for it and for every entry below it
|
|
1035
|
+
* no earlier announcement carried.
|
|
1036
|
+
* @param head - The announced head.
|
|
1037
|
+
* @param stamp - The stamp it arrived with. A malformed one is ignored.
|
|
1038
|
+
* @param maxWalk - How many rows to read; past it the walk stays open.
|
|
1039
|
+
*/
|
|
1040
|
+
async heard(head, stamp, maxWalk = DEFAULT_MAX_WALK) {
|
|
1041
|
+
if (!isRefStamp(stamp) || this._byEntry.has(head)) return;
|
|
1042
|
+
const { domain, epoch, hub, n } = stamp;
|
|
1043
|
+
this._set(head, { domain, epoch, hub, n });
|
|
1044
|
+
this._open.add(head);
|
|
1045
|
+
await this._walk([head], /* @__PURE__ */ new Set([head]), maxWalk);
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Resumes every walk that stopped short.
|
|
1049
|
+
*
|
|
1050
|
+
* Not part of {@link heard}: a row that cannot be read can cost a blocked
|
|
1051
|
+
* read each time it is asked for, and an announcement arrives every few
|
|
1052
|
+
* seconds. Only a merge that is missing a stamp calls this.
|
|
1053
|
+
* @param maxWalk - How many rows to read; past it the walks stay open.
|
|
1054
|
+
*/
|
|
1055
|
+
async settle(maxWalk = DEFAULT_MAX_WALK) {
|
|
1056
|
+
await this._walk([...this._open], /* @__PURE__ */ new Set(), maxWalk);
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* The highest epoch this node has heard in a domain — what a hub taking
|
|
1060
|
+
* office here has to continue above.
|
|
1061
|
+
* @param domain - The domain.
|
|
1062
|
+
* @returns The epoch, or `0` when none was heard.
|
|
1063
|
+
*/
|
|
1064
|
+
maxEpoch(domain) {
|
|
1065
|
+
return this._maxEpoch.get(domain) ?? 0;
|
|
1066
|
+
}
|
|
1067
|
+
/** The highest epoch heard in every domain this node has heard of. */
|
|
1068
|
+
get epochs() {
|
|
1069
|
+
return Object.fromEntries(this._maxEpoch);
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Records an entry's stamp, and the epoch it carries.
|
|
1073
|
+
* @param entry - The chain entry.
|
|
1074
|
+
* @param stamp - Its stamp.
|
|
1075
|
+
*/
|
|
1076
|
+
_set(entry, stamp) {
|
|
1077
|
+
this._byEntry.set(entry, stamp);
|
|
1078
|
+
if (stamp.epoch > this.maxEpoch(stamp.domain)) {
|
|
1079
|
+
this._maxEpoch.set(stamp.domain, stamp.epoch);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
// ...........................................................................
|
|
1083
|
+
/**
|
|
1084
|
+
* Walks down from open entries, giving every unstamped entry it reaches the
|
|
1085
|
+
* stamp it was reached with, and stores what changed.
|
|
1086
|
+
*
|
|
1087
|
+
* Earliest stamp first: an entry two announcements carried belongs to the
|
|
1088
|
+
* earlier one, and a walk resumed late must not lose it to a later walk that
|
|
1089
|
+
* happens to be fewer steps away.
|
|
1090
|
+
* @param seeds - The open entries to walk from.
|
|
1091
|
+
* @param changed - Entries stamped by the caller, to be stored too.
|
|
1092
|
+
* @param maxWalk - How many rows to read.
|
|
1093
|
+
*/
|
|
1094
|
+
async _walk(seeds, changed, maxWalk) {
|
|
1095
|
+
const pending = new Set(seeds);
|
|
1096
|
+
for (let reads = 0; pending.size > 0 && reads < maxWalk; reads++) {
|
|
1097
|
+
const entry = [...pending].reduce((a, b) => this._before(b, a) ? b : a);
|
|
1098
|
+
pending.delete(entry);
|
|
1099
|
+
const previous = await this._previousOf(entry);
|
|
1100
|
+
if (previous === void 0) continue;
|
|
1101
|
+
const stamp = this._byEntry.get(entry);
|
|
1102
|
+
for (const parent of previous) {
|
|
1103
|
+
if (this._byEntry.has(parent)) continue;
|
|
1104
|
+
this._set(parent, stamp);
|
|
1105
|
+
this._open.add(parent);
|
|
1106
|
+
pending.add(parent);
|
|
1107
|
+
changed.add(parent);
|
|
1108
|
+
}
|
|
1109
|
+
this._open.delete(entry);
|
|
1110
|
+
changed.add(entry);
|
|
1111
|
+
}
|
|
1112
|
+
if (changed.size === 0) return;
|
|
1113
|
+
await this._db.core.import(
|
|
1114
|
+
{
|
|
1115
|
+
[this.table]: {
|
|
1116
|
+
_type: "components",
|
|
1117
|
+
_data: [...changed].map(
|
|
1118
|
+
(entry) => ({
|
|
1119
|
+
entry,
|
|
1120
|
+
...this._byEntry.get(entry),
|
|
1121
|
+
walked: !this._open.has(entry)
|
|
1122
|
+
})
|
|
1123
|
+
)
|
|
1124
|
+
}
|
|
1125
|
+
},
|
|
1126
|
+
{ validate: false }
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Whether `a` was stamped before `b`.
|
|
1131
|
+
* @param a - A stamped entry.
|
|
1132
|
+
* @param b - Another.
|
|
1133
|
+
* @returns `true` when `a`'s stamp is the earlier, ties broken on the entry.
|
|
1134
|
+
*/
|
|
1135
|
+
_before(a, b) {
|
|
1136
|
+
const order = compareRefStamp(
|
|
1137
|
+
this._byEntry.get(a),
|
|
1138
|
+
this._byEntry.get(b)
|
|
1139
|
+
);
|
|
1140
|
+
return order < 0 || order === 0 && a < b;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
const GLOB_CHARS = /[*?/\\]/;
|
|
1144
|
+
const escapeLiteral = (text) => text.replace(/[.+^${}()|[\]\\\-]/g, "\\$&");
|
|
1145
|
+
const globToRegExp = (glob) => {
|
|
1146
|
+
let out = "";
|
|
1147
|
+
for (let i = 0; i < glob.length; i++) {
|
|
1148
|
+
const char = glob[i];
|
|
1149
|
+
if (char === "*") {
|
|
1150
|
+
if (glob[i + 1] === "*") {
|
|
1151
|
+
i++;
|
|
1152
|
+
if (glob[i + 1] === "/") {
|
|
1153
|
+
out += "(?:[^/]+/)*";
|
|
1154
|
+
i++;
|
|
1155
|
+
} else {
|
|
1156
|
+
out += ".*";
|
|
1157
|
+
}
|
|
1158
|
+
} else {
|
|
1159
|
+
out += "[^/]*";
|
|
1160
|
+
}
|
|
1161
|
+
} else if (char === "?") {
|
|
1162
|
+
out += "[^/]";
|
|
1163
|
+
} else {
|
|
1164
|
+
out += escapeLiteral(char);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
return new RegExp(`^${out}$`, "i");
|
|
1168
|
+
};
|
|
1169
|
+
const normalise = (path) => {
|
|
1170
|
+
const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
|
|
1171
|
+
return slashed === "." ? "" : slashed;
|
|
1172
|
+
};
|
|
1173
|
+
const compileRule = (pattern) => {
|
|
1174
|
+
const trimmed = pattern.trim();
|
|
1175
|
+
if (trimmed === "" || trimmed.startsWith("#")) return void 0;
|
|
1176
|
+
const negated = trimmed.startsWith("!");
|
|
1177
|
+
const body = negated ? trimmed.slice(1) : trimmed;
|
|
1178
|
+
if (!negated && !GLOB_CHARS.test(body)) {
|
|
1179
|
+
return {
|
|
1180
|
+
negated: false,
|
|
1181
|
+
dirOnly: false,
|
|
1182
|
+
kind: "literal",
|
|
1183
|
+
literal: body,
|
|
1184
|
+
re: void 0
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
const dirOnly = /[/\\]$/.test(body);
|
|
1188
|
+
const glob = normalise(body);
|
|
1189
|
+
if (glob === "") return void 0;
|
|
1190
|
+
return {
|
|
1191
|
+
negated,
|
|
1192
|
+
dirOnly,
|
|
1193
|
+
kind: glob.includes("/") ? "path" : "segment",
|
|
1194
|
+
literal: glob,
|
|
1195
|
+
re: globToRegExp(glob)
|
|
1196
|
+
};
|
|
1197
|
+
};
|
|
1198
|
+
const ruleMatches = (rule, path, segments, isDirectory) => {
|
|
1199
|
+
if (rule.kind === "literal") {
|
|
1200
|
+
return segments.some(
|
|
1201
|
+
(segment) => segment === rule.literal || segment.startsWith(rule.literal)
|
|
1202
|
+
);
|
|
1203
|
+
}
|
|
1204
|
+
const re = rule.re;
|
|
1205
|
+
if (rule.kind === "segment") {
|
|
1206
|
+
const last = segments.length - 1;
|
|
1207
|
+
return segments.some((segment, index) => {
|
|
1208
|
+
if (!re.test(segment)) return false;
|
|
1209
|
+
if (!rule.dirOnly) return true;
|
|
1210
|
+
return index < last || isDirectory !== false;
|
|
1211
|
+
});
|
|
1212
|
+
}
|
|
1213
|
+
if (re.test(path) && !(rule.dirOnly && isDirectory === false)) {
|
|
1214
|
+
return true;
|
|
1215
|
+
}
|
|
1216
|
+
let ancestor = "";
|
|
1217
|
+
for (const segment of segments.slice(0, -1)) {
|
|
1218
|
+
ancestor = ancestor === "" ? segment : `${ancestor}/${segment}`;
|
|
1219
|
+
if (re.test(ancestor)) return true;
|
|
1220
|
+
}
|
|
1221
|
+
return false;
|
|
1222
|
+
};
|
|
1223
|
+
const compileIgnore = (patterns) => {
|
|
1224
|
+
const rules = [];
|
|
1225
|
+
for (const pattern of patterns ?? []) {
|
|
1226
|
+
const rule = compileRule(pattern);
|
|
1227
|
+
if (rule !== void 0) rules.push(rule);
|
|
1228
|
+
}
|
|
1229
|
+
return {
|
|
1230
|
+
ignores: (relativePath, isDirectory) => {
|
|
1231
|
+
const path = normalise(relativePath);
|
|
1232
|
+
if (path === "") return false;
|
|
1233
|
+
const segments = path.split("/").filter((s) => s !== "");
|
|
1234
|
+
let ignored = false;
|
|
1235
|
+
for (const rule of rules) {
|
|
1236
|
+
if (ruleMatches(rule, path, segments, isDirectory)) {
|
|
1237
|
+
ignored = !rule.negated;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
return ignored;
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
};
|
|
1244
|
+
const _envRescan = Number(process.env["RLJSON_FS_RESCAN_MS"]);
|
|
1245
|
+
const SAFETY_RESCAN_INTERVAL_MS = Number.isFinite(_envRescan) && _envRescan > 0 ? _envRescan : 5e3;
|
|
1246
|
+
const STUCK_PAUSE_MS = 15e3;
|
|
1247
|
+
const DEFAULT_SETTLE_MS = 100;
|
|
1248
|
+
const OWN_WRITES_MAX = 1e4;
|
|
1249
|
+
class FsScanner {
|
|
1250
|
+
_rootPath;
|
|
1251
|
+
_tree = null;
|
|
1252
|
+
_watcher = null;
|
|
1253
|
+
_changeCallbacks = [];
|
|
1254
|
+
_options;
|
|
1255
|
+
/**
|
|
1256
|
+
* The ignore list, compiled once.
|
|
1257
|
+
*
|
|
1258
|
+
* Compiled rather than re-read per entry because a scan of a production
|
|
1259
|
+
* catalogue asks this question once per file, and a glob is a regular
|
|
1260
|
+
* expression that should be built once. `fs-ignore.ts` carries the
|
|
1261
|
+
* compatibility rule that keeps every prefix pattern working.
|
|
1262
|
+
*/
|
|
1263
|
+
_ignoreMatcher;
|
|
1264
|
+
_bs;
|
|
1265
|
+
_paused = false;
|
|
1266
|
+
_missedChangesDuringPause = false;
|
|
1267
|
+
/** Periodic full-rescan timer that catches events the native watcher drops. */
|
|
1268
|
+
_safetyTimer = null;
|
|
1269
|
+
/** When the current pause began, or null when not paused. */
|
|
1270
|
+
_pausedAt = null;
|
|
1271
|
+
/** Releases a pause whose resume never arrived (see {@link pauseWatch}). */
|
|
1272
|
+
_autoResumeTimer = null;
|
|
1273
|
+
/** Set by stopWatch() so a pending watcher reinstall / rescan bails out. */
|
|
1274
|
+
_stopRequested = false;
|
|
1275
|
+
/** Path→content cache backing {@link FsScanOptions.scanCachePath} (unused when unset). */
|
|
1276
|
+
_scanCachePath;
|
|
1277
|
+
/**
|
|
1278
|
+
* Paths this scan refused to read because they were still being written.
|
|
1279
|
+
*
|
|
1280
|
+
* Counted so {@link scan} knows to come back, and reported so a folder that
|
|
1281
|
+
* never settles is diagnosable rather than mysteriously stale.
|
|
1282
|
+
*/
|
|
1283
|
+
_unsettledDuringScan = [];
|
|
1284
|
+
/**
|
|
1285
|
+
* When the scan now running began.
|
|
1286
|
+
*
|
|
1287
|
+
* A file whose timestamp is newer than this is still being written: the
|
|
1288
|
+
* bytes moved while this scan was in progress. See the gate in
|
|
1289
|
+
* {@link _scanDirectory}.
|
|
1290
|
+
*/
|
|
1291
|
+
_scanStartedAt = 0;
|
|
1292
|
+
/** When the pass that produced {@link tree} began; 0 before the first. */
|
|
1293
|
+
_treeStartedAt = 0;
|
|
1294
|
+
/**
|
|
1295
|
+
* Large files whose size this scanner has seen but not yet seen settle.
|
|
1296
|
+
*
|
|
1297
|
+
* path → the size observed last time. A file leaves the map the scan after
|
|
1298
|
+
* its size stops changing, which is when it is finally read. Bounded by the
|
|
1299
|
+
* number of large files being written at once, which is a handful.
|
|
1300
|
+
*/
|
|
1301
|
+
_growing = /* @__PURE__ */ new Map();
|
|
1302
|
+
/** Pending follow-up scan for {@link _unsettledDuringScan}. */
|
|
1303
|
+
_settleTimer = null;
|
|
1304
|
+
/** Last-scan cache (loaded from disk); consulted to skip re-read/re-hash. */
|
|
1305
|
+
_blobCache = /* @__PURE__ */ new Map();
|
|
1306
|
+
/** Cache rebuilt during the CURRENT scan; becomes `_blobCache` at the end (self-pruning). */
|
|
1307
|
+
_nextBlobCache = /* @__PURE__ */ new Map();
|
|
1308
|
+
/** Ensures the persisted cache is read from disk only once. */
|
|
1309
|
+
_cacheLoaded = false;
|
|
1310
|
+
/** Entries that vanished mid-scan, counted per {@link scan} for one summary. */
|
|
1311
|
+
_vanishedDuringScan = 0;
|
|
1312
|
+
/** The scan pass running right now, if any. See {@link _scanAfterNow}. */
|
|
1313
|
+
_activeScan = null;
|
|
1314
|
+
/**
|
|
1315
|
+
* Files this process wrote whole a moment ago — by an atomic rename — keyed
|
|
1316
|
+
* by relative path. See {@link noteWrite}.
|
|
1317
|
+
*/
|
|
1318
|
+
_ownWrites = /* @__PURE__ */ new Map();
|
|
1319
|
+
/** The single follow-up pass everyone who arrived mid-scan is waiting on. */
|
|
1320
|
+
_pendingScan = null;
|
|
1321
|
+
constructor(rootPath, options = {}) {
|
|
1322
|
+
this._rootPath = rootPath;
|
|
1323
|
+
this._options = {
|
|
1324
|
+
ignore: options.ignore || ["node_modules", ".git", "dist", "coverage"],
|
|
1325
|
+
maxDepth: options.maxDepth,
|
|
1326
|
+
followSymlinks: options.followSymlinks ?? false,
|
|
1327
|
+
bs: options.bs,
|
|
1328
|
+
scanCachePath: options.scanCachePath,
|
|
1329
|
+
settleMs: options.settleMs ?? DEFAULT_SETTLE_MS
|
|
1330
|
+
};
|
|
1331
|
+
this._ignoreMatcher = compileIgnore(this._options.ignore);
|
|
1332
|
+
this._bs = options.bs || new BsMem();
|
|
1333
|
+
this._scanCachePath = options.scanCachePath;
|
|
1334
|
+
}
|
|
1335
|
+
get tree() {
|
|
1336
|
+
return this._tree;
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* When the pass that produced {@link tree} began — 0 before the first. A
|
|
1340
|
+
* caller that wrote to the folder tells from it whether that pass could have
|
|
1341
|
+
* read its write half-done.
|
|
1342
|
+
* @returns Epoch ms.
|
|
1343
|
+
*/
|
|
1344
|
+
get treeStartedAt() {
|
|
1345
|
+
return this._treeStartedAt;
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* The folder as it is now: a scan guaranteed to have STARTED after this
|
|
1349
|
+
* call, sharing one pass with anyone else asking meanwhile. What a caller
|
|
1350
|
+
* that acts on the folder must use — {@link tree} is the last pass, which
|
|
1351
|
+
* may have run while something was still writing.
|
|
1352
|
+
* @returns The tree.
|
|
1353
|
+
*/
|
|
1354
|
+
scanFresh() {
|
|
1355
|
+
return this._scanAfterNow();
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Tells the scanner a file was just written whole by this process, with the
|
|
1359
|
+
* given content. The next scan takes it as written — never as a copy still
|
|
1360
|
+
* in progress, whatever its timestamp says. A file that changed since is
|
|
1361
|
+
* read as usual.
|
|
1362
|
+
*
|
|
1363
|
+
* Without it, a write in the second half of the millisecond a scan starts
|
|
1364
|
+
* in reads as "changed during this scan" — Node rounds an mtime to the
|
|
1365
|
+
* nearest millisecond, the scan's start is truncated — and the scan reused
|
|
1366
|
+
* the version BEFORE the write: measured as a receiver announcing the
|
|
1367
|
+
* previous save of a file it had just applied, which reverted the writer's
|
|
1368
|
+
* own copy.
|
|
1369
|
+
* @param relativePath - The file, `/`-separated.
|
|
1370
|
+
* @param blobId - Its content.
|
|
1371
|
+
* @param size - Its size as written.
|
|
1372
|
+
* @param mtime - Its mtime as written, ms.
|
|
1373
|
+
*/
|
|
1374
|
+
noteWrite(relativePath, blobId, size, mtime) {
|
|
1375
|
+
if (this._ownWrites.size >= OWN_WRITES_MAX) {
|
|
1376
|
+
this._ownWrites.delete(this._ownWrites.keys().next().value);
|
|
1377
|
+
}
|
|
1378
|
+
this._ownWrites.set(relativePath, { blobId, size, mtime });
|
|
1379
|
+
}
|
|
1380
|
+
/** Whether a watcher is currently installed. */
|
|
1381
|
+
get isWatching() {
|
|
1382
|
+
return this._watcher !== null;
|
|
1383
|
+
}
|
|
1384
|
+
get rootPath() {
|
|
1385
|
+
return this._rootPath;
|
|
1386
|
+
}
|
|
1387
|
+
get bs() {
|
|
1388
|
+
return this._bs;
|
|
1389
|
+
}
|
|
1390
|
+
async scan() {
|
|
1391
|
+
try {
|
|
1392
|
+
const stats = await stat(this._rootPath);
|
|
1393
|
+
if (!stats.isDirectory()) {
|
|
1394
|
+
throw new Error(
|
|
1395
|
+
`Root path "${this._rootPath}" exists but is not a directory`
|
|
1396
|
+
);
|
|
1397
|
+
}
|
|
1398
|
+
} catch (error) {
|
|
1399
|
+
if (error.code === "ENOENT") {
|
|
1400
|
+
throw new Error(
|
|
1401
|
+
`Root path "${this._rootPath}" does not exist. Cannot scan non-existent directory.`
|
|
1402
|
+
);
|
|
1403
|
+
}
|
|
1404
|
+
throw new Error(
|
|
1405
|
+
`Cannot access root path "${this._rootPath}": ${error instanceof Error ? error.message : String(error)}`
|
|
1406
|
+
);
|
|
1407
|
+
}
|
|
1408
|
+
if (this._scanCachePath) {
|
|
1409
|
+
await this._loadPersistedCache();
|
|
1410
|
+
this._nextBlobCache = /* @__PURE__ */ new Map();
|
|
1411
|
+
}
|
|
1412
|
+
const trees = /* @__PURE__ */ new Map();
|
|
636
1413
|
this._vanishedDuringScan = 0;
|
|
1414
|
+
this._unsettledDuringScan = [];
|
|
1415
|
+
this._scanStartedAt = Date.now();
|
|
637
1416
|
let rootTree;
|
|
638
1417
|
try {
|
|
639
1418
|
rootTree = await this._scanDirectory(this._rootPath, ".", 0, trees);
|
|
@@ -665,8 +1444,20 @@ class FsScanner {
|
|
|
665
1444
|
rootHash: rootHashStr,
|
|
666
1445
|
trees
|
|
667
1446
|
};
|
|
1447
|
+
this._treeStartedAt = this._scanStartedAt;
|
|
1448
|
+
if (this._unsettledDuringScan.length > 0) {
|
|
1449
|
+
const waiting = [...this._unsettledDuringScan];
|
|
1450
|
+
if (this._settleTimer === null) {
|
|
1451
|
+
this._settleTimer = setTimeout(() => {
|
|
1452
|
+
this._settleTimer = null;
|
|
1453
|
+
if (this._stopRequested) return;
|
|
1454
|
+
void this._rescanAfterSettle(waiting[0]);
|
|
1455
|
+
}, this._options.settleMs + 50);
|
|
1456
|
+
this._settleTimer.unref?.();
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
this._blobCache = this._nextBlobCache;
|
|
668
1460
|
if (this._scanCachePath) {
|
|
669
|
-
this._blobCache = this._nextBlobCache;
|
|
670
1461
|
await this._persistCache();
|
|
671
1462
|
}
|
|
672
1463
|
return this._tree;
|
|
@@ -676,11 +1467,11 @@ class FsScanner {
|
|
|
676
1467
|
const childTrees = [];
|
|
677
1468
|
const childRefs = [];
|
|
678
1469
|
for (const entry of entries) {
|
|
679
|
-
if (this._shouldIgnore(entry.name)) {
|
|
680
|
-
continue;
|
|
681
|
-
}
|
|
682
1470
|
const childPath = join(absolutePath, entry.name);
|
|
683
1471
|
const childRelPath = relativePath === "." ? entry.name : `${relativePath}/${entry.name}`;
|
|
1472
|
+
if (this._shouldIgnorePath(childRelPath, entry.isDirectory())) {
|
|
1473
|
+
continue;
|
|
1474
|
+
}
|
|
684
1475
|
if (entry.isSymbolicLink() && !this._options.followSymlinks) {
|
|
685
1476
|
continue;
|
|
686
1477
|
}
|
|
@@ -703,9 +1494,33 @@ class FsScanner {
|
|
|
703
1494
|
childRefs.push(childHashStr);
|
|
704
1495
|
} else if (entry.isFile()) {
|
|
705
1496
|
const mtimeMs = childStats.mtime.getTime();
|
|
1497
|
+
const written = this._ownWrites.get(childRelPath);
|
|
1498
|
+
const ownWrite = written !== void 0 && written.size === childStats.size && Math.abs(written.mtime - mtimeMs) < 1;
|
|
1499
|
+
if (written !== void 0 && !ownWrite) {
|
|
1500
|
+
this._ownWrites.delete(childRelPath);
|
|
1501
|
+
}
|
|
1502
|
+
const now = Date.now();
|
|
1503
|
+
const inTheFuture = mtimeMs > now;
|
|
1504
|
+
const seen = this._growing.get(childRelPath);
|
|
1505
|
+
const growing = seen !== void 0 && seen !== childStats.size;
|
|
1506
|
+
const neverRead = !this._blobCache.has(childRelPath);
|
|
1507
|
+
const touchedJustNow = !inTheFuture && now - mtimeMs < this._options.settleMs;
|
|
1508
|
+
const firstSight = neverRead && (touchedJustNow || seen === void 0);
|
|
1509
|
+
if (!ownWrite && (growing || firstSight)) {
|
|
1510
|
+
this._growing.set(childRelPath, childStats.size);
|
|
1511
|
+
} else {
|
|
1512
|
+
this._growing.delete(childRelPath);
|
|
1513
|
+
}
|
|
1514
|
+
if (!ownWrite && this._watcher !== null && !this._paused && (mtimeMs > this._scanStartedAt && !inTheFuture || growing || firstSight)) {
|
|
1515
|
+
this._unsettledDuringScan.push(childRelPath);
|
|
1516
|
+
this._reuse(childRelPath, trees, childTrees, childRefs);
|
|
1517
|
+
continue;
|
|
1518
|
+
}
|
|
706
1519
|
const cached = this._scanCachePath ? this._blobCache.get(childRelPath) : void 0;
|
|
707
1520
|
let blobId;
|
|
708
|
-
if (
|
|
1521
|
+
if (ownWrite) {
|
|
1522
|
+
blobId = written.blobId;
|
|
1523
|
+
} else if (cached && cached.mtime === mtimeMs && cached.size === childStats.size) {
|
|
709
1524
|
blobId = cached.blobId;
|
|
710
1525
|
} else {
|
|
711
1526
|
let handle;
|
|
@@ -738,23 +1553,57 @@ class FsScanner {
|
|
|
738
1553
|
}
|
|
739
1554
|
blobId = blobProps.blobId;
|
|
740
1555
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
1556
|
+
const after = await stat(childPath).catch(
|
|
1557
|
+
/* v8 ignore next -- @preserve a vanished file already threw above */
|
|
1558
|
+
() => void 0
|
|
1559
|
+
);
|
|
1560
|
+
if (!this._paused && (after === void 0 || after.size !== childStats.size || after.mtime.getTime() !== mtimeMs)) {
|
|
1561
|
+
this._reuse(childRelPath, trees, childTrees, childRefs);
|
|
1562
|
+
continue;
|
|
747
1563
|
}
|
|
1564
|
+
this._nextBlobCache.set(childRelPath, {
|
|
1565
|
+
mtime: mtimeMs,
|
|
1566
|
+
size: childStats.size,
|
|
1567
|
+
blobId
|
|
1568
|
+
});
|
|
748
1569
|
const fileMeta = {
|
|
749
1570
|
name: entry.name,
|
|
750
1571
|
type: "file",
|
|
751
1572
|
relativePath: childRelPath,
|
|
752
1573
|
size: childStats.size,
|
|
753
|
-
// mtime
|
|
754
|
-
//
|
|
755
|
-
// mtime
|
|
756
|
-
//
|
|
757
|
-
|
|
1574
|
+
// NO mtime, and no absolute `path` — see {@link FsNodeMeta}, which
|
|
1575
|
+
// has documented both as excluded from the content identity all
|
|
1576
|
+
// along. `path` was; mtime was not, and the gap is what made a
|
|
1577
|
+
// node's deletions refusable by everybody.
|
|
1578
|
+
//
|
|
1579
|
+
// A tree ref is meant to be a SHARED IDENTITY: the same bytes give
|
|
1580
|
+
// the same ref on every machine, which is what lets a receiver
|
|
1581
|
+
// check a sender's claimed ancestry. mtime breaks that for any
|
|
1582
|
+
// file created independently rather than restored — the same
|
|
1583
|
+
// document saved on two machines, a seeded fixture, a folder
|
|
1584
|
+
// copied to two laptops — and it breaks it at MILLISECOND
|
|
1585
|
+
// granularity, which is far finer than anything a user does.
|
|
1586
|
+
// Measured on four nodes: one `keeper.txt`, written by a loop, held
|
|
1587
|
+
// `…104.2852`, `…104.4375` and `…104.5483` on disk, and
|
|
1588
|
+
// `stats.mtime.getTime()` truncates — so which side of a
|
|
1589
|
+
// millisecond boundary a write landed on decided the folder's ref.
|
|
1590
|
+
//
|
|
1591
|
+
// A node whose ref disagrees with its peers' for identical content
|
|
1592
|
+
// is out of the ancestry conversation: it announces parents nobody
|
|
1593
|
+
// can be in, so every deletion it sends is refused by everybody.
|
|
1594
|
+
// That is the register's most-reproduced entry, and a directory
|
|
1595
|
+
// removal is what makes it
|
|
1596
|
+
// visible because it returns a folder to a state whose ref must
|
|
1597
|
+
// still agree. Measured: 10 of 10 on the four-node directory
|
|
1598
|
+
// deletion with mtime out, 8 of 10 with it in.
|
|
1599
|
+
//
|
|
1600
|
+
// The cost is real and accepted: a restored file carries the time
|
|
1601
|
+
// it arrived, not the time the author saved it. Timestamps still
|
|
1602
|
+
// round-trip for a tree that carries them (the restore honours
|
|
1603
|
+
// `meta.mtime` when a peer sends one), and this agent keeps every
|
|
1604
|
+
// mtime it observes in the scan cache, where the skip-a-write
|
|
1605
|
+
// optimisation needs it. What is given up is propagating the
|
|
1606
|
+
// author's clock, and no part of sync correctness depends on it.
|
|
758
1607
|
blobId
|
|
759
1608
|
// Link to content in Bs
|
|
760
1609
|
};
|
|
@@ -789,7 +1638,7 @@ class FsScanner {
|
|
|
789
1638
|
id: dirName,
|
|
790
1639
|
isParent: childRefs.length > 0,
|
|
791
1640
|
meta: dirMeta,
|
|
792
|
-
children: childRefs.length > 0 ? childRefs : null
|
|
1641
|
+
children: childRefs.length > 0 ? [...childRefs].sort() : null
|
|
793
1642
|
};
|
|
794
1643
|
return dirTree;
|
|
795
1644
|
}
|
|
@@ -833,12 +1682,12 @@ class FsScanner {
|
|
|
833
1682
|
*
|
|
834
1683
|
* `fs.watch` in recursive mode reports a path RELATIVE TO THE ROOT
|
|
835
1684
|
* (`sub/dir/.fsagent-tmp-abc`), while the ignore patterns are basenames.
|
|
836
|
-
*
|
|
1685
|
+
* The matcher tested a basename only, so a nested match never fired:
|
|
837
1686
|
* every atomic write the agent itself makes during a restore came back as a
|
|
838
1687
|
* change event, each event triggered a scan, and the debounce that batches a
|
|
839
1688
|
* push was reset before it could fire.
|
|
840
1689
|
*
|
|
841
|
-
* Measured on
|
|
1690
|
+
* Measured on a large production folder: after a 3 642-file restore the watcher
|
|
842
1691
|
* reported the SAME newly added file nine times and the agent never emitted a
|
|
843
1692
|
* ref for it — `[fs] added: …/probe-….txt` nine times, no `sync:out`. The
|
|
844
1693
|
* file did not fail to arrive; it was never sent.
|
|
@@ -846,24 +1695,13 @@ class FsScanner {
|
|
|
846
1695
|
* Every segment is tested, because the pattern may match a directory as
|
|
847
1696
|
* easily as a file.
|
|
848
1697
|
* @param relativePath - Path as the watcher reports it.
|
|
849
|
-
* @
|
|
1698
|
+
* @param isDirectory - Whether the path is a directory, when the caller
|
|
1699
|
+
* knows. A directory-only pattern (`build/`) needs it; the watcher cannot
|
|
1700
|
+
* say, and not knowing never widens what is ignored.
|
|
1701
|
+
* @returns True when the ignore list covers this path.
|
|
850
1702
|
*/
|
|
851
|
-
_shouldIgnorePath(relativePath) {
|
|
852
|
-
|
|
853
|
-
if (segment && this._shouldIgnore(segment)) return true;
|
|
854
|
-
}
|
|
855
|
-
return false;
|
|
856
|
-
}
|
|
857
|
-
_shouldIgnore(name) {
|
|
858
|
-
if (!this._options.ignore) {
|
|
859
|
-
return false;
|
|
860
|
-
}
|
|
861
|
-
for (const pattern of this._options.ignore) {
|
|
862
|
-
if (name === pattern || name.startsWith(pattern)) {
|
|
863
|
-
return true;
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
return false;
|
|
1703
|
+
_shouldIgnorePath(relativePath, isDirectory) {
|
|
1704
|
+
return this._ignoreMatcher.ignores(relativePath, isDirectory);
|
|
867
1705
|
}
|
|
868
1706
|
async watch() {
|
|
869
1707
|
if (this._watcher) {
|
|
@@ -902,7 +1740,10 @@ class FsScanner {
|
|
|
902
1740
|
};
|
|
903
1741
|
this._stopRequested = false;
|
|
904
1742
|
this._watcher = watch(this._rootPath, { recursive: true }, onEvent);
|
|
905
|
-
|
|
1743
|
+
this._watcher.on(
|
|
1744
|
+
"error",
|
|
1745
|
+
FsScanner._isWindows ? onError : FsScanner._onWatchError
|
|
1746
|
+
);
|
|
906
1747
|
if (!this._safetyTimer) {
|
|
907
1748
|
this._safetyTimer = setInterval(() => {
|
|
908
1749
|
void this._runSafetyRescan();
|
|
@@ -916,6 +1757,59 @@ class FsScanner {
|
|
|
916
1757
|
* notification so syncToDb reconciles the drift. Paused/stopped scanners and
|
|
917
1758
|
* scan failures are no-ops.
|
|
918
1759
|
*/
|
|
1760
|
+
/**
|
|
1761
|
+
* Re-reads the folder once a file this scan would not read has settled.
|
|
1762
|
+
*
|
|
1763
|
+
* Through the coalescer, like the safety rescan, so a settle landing inside
|
|
1764
|
+
* a burst does not add a whole extra pass. Notifies unconditionally: the
|
|
1765
|
+
* caller already knows something was deferred, and the point is to get the
|
|
1766
|
+
* file out now rather than on the five-second rescan.
|
|
1767
|
+
* @param path - The path that was deferred, for the change event.
|
|
1768
|
+
*/
|
|
1769
|
+
/**
|
|
1770
|
+
* Carries a file's PREVIOUS node into the scan being built, because the file
|
|
1771
|
+
* on disk right now is still being written.
|
|
1772
|
+
*
|
|
1773
|
+
* A path simply left out of a tree reads as a DELETION to every peer that
|
|
1774
|
+
* holds it, so a user saving over a document would have it deleted
|
|
1775
|
+
* everywhere. Reusing the last node says the truthful thing instead: as far
|
|
1776
|
+
* as the network is concerned this change has not happened yet.
|
|
1777
|
+
*
|
|
1778
|
+
* A file nobody has ever seen has no previous node and IS left out, which is
|
|
1779
|
+
* correct — it cannot be a deletion of something no peer holds.
|
|
1780
|
+
*
|
|
1781
|
+
* The node must go into `trees` as well as into the parent's children. It is
|
|
1782
|
+
* the kind of thing that looks redundant and is not: leaving it out gave the
|
|
1783
|
+
* root a child hash with no node behind it, and the whole folder came out
|
|
1784
|
+
* empty.
|
|
1785
|
+
* @param relativePath - The deferred path.
|
|
1786
|
+
* @param trees - The node map this scan is building.
|
|
1787
|
+
* @param childTrees - The parent's child nodes.
|
|
1788
|
+
* @param childRefs - The parent's child hashes.
|
|
1789
|
+
*/
|
|
1790
|
+
_reuse(relativePath, trees, childTrees, childRefs) {
|
|
1791
|
+
this._unsettledDuringScan.push(relativePath);
|
|
1792
|
+
const previous = this.getTreeByPath(relativePath);
|
|
1793
|
+
if (!previous) return;
|
|
1794
|
+
const hash = previous._hash;
|
|
1795
|
+
trees.set(hash, previous);
|
|
1796
|
+
childTrees.push(previous);
|
|
1797
|
+
childRefs.push(hash);
|
|
1798
|
+
const known = this._blobCache.get(relativePath);
|
|
1799
|
+
if (known) this._nextBlobCache.set(relativePath, known);
|
|
1800
|
+
}
|
|
1801
|
+
async _rescanAfterSettle(path) {
|
|
1802
|
+
if (this._stopRequested) return;
|
|
1803
|
+
try {
|
|
1804
|
+
await this._scanAfterNow();
|
|
1805
|
+
if (this._stopRequested) return;
|
|
1806
|
+
await this._notifyChange({ type: "modified", path });
|
|
1807
|
+
} catch (err) {
|
|
1808
|
+
console.warn(
|
|
1809
|
+
`[fs-scanner] settle rescan failed: ${FsScanner._errMessage(err)}`
|
|
1810
|
+
);
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
919
1813
|
async _runSafetyRescan() {
|
|
920
1814
|
if (this._stopRequested) return;
|
|
921
1815
|
if (this._paused && !this._pauseLooksStuck({ type: "safety-rescan", path: "." })) {
|
|
@@ -965,6 +1859,20 @@ class FsScanner {
|
|
|
965
1859
|
* @param err - The caught value
|
|
966
1860
|
* @returns A message string
|
|
967
1861
|
*/
|
|
1862
|
+
/**
|
|
1863
|
+
* What a watcher error does off Windows: nothing that could crash.
|
|
1864
|
+
*
|
|
1865
|
+
* An FSWatcher with no `'error'` listener throws what it emits, and Node's
|
|
1866
|
+
* recursive watcher on Linux emits ENOENT when a directory is deleted while
|
|
1867
|
+
* it walks it — the agent died of a user deleting a nested folder. There is
|
|
1868
|
+
* nothing to reinstall: the watcher stays, and the safety rescan picks up
|
|
1869
|
+
* whatever it missed. Anything other than a vanished directory is said.
|
|
1870
|
+
* @param err - The error the watcher emitted.
|
|
1871
|
+
*/
|
|
1872
|
+
static _onWatchError(err) {
|
|
1873
|
+
if (err?.code === "ENOENT") return;
|
|
1874
|
+
console.warn(`[fs-scanner] watcher error: ${FsScanner._errMessage(err)}`);
|
|
1875
|
+
}
|
|
968
1876
|
static _errMessage(err) {
|
|
969
1877
|
return err instanceof Error ? err.message : String(err);
|
|
970
1878
|
}
|
|
@@ -1045,12 +1953,12 @@ class FsScanner {
|
|
|
1045
1953
|
* callback, so those scans all run AT ONCE. Copying 1 200 tiny files into a
|
|
1046
1954
|
* watched folder took 1 200 concurrent full scans: the CPU sat 82% idle
|
|
1047
1955
|
* waiting on the filesystem, RSS climbed from 263 MB to 785 MB, and after two
|
|
1048
|
-
* minutes the peer had received nothing. On
|
|
1956
|
+
* minutes the peer had received nothing. On a 3 702-file folder
|
|
1049
1957
|
* the same burst wedged the client outright.
|
|
1050
1958
|
*
|
|
1051
1959
|
* Started-after is the part that cannot be traded away. Joining a scan that
|
|
1052
1960
|
* began BEFORE the event would let a push carry a tree that predates the file
|
|
1053
|
-
* that triggered it — which is precisely the partial trees
|
|
1961
|
+
* that triggered it — which is precisely the partial trees a real fleet saw
|
|
1054
1962
|
* advertised: 64 nodes, then 103, then 204, each a stale snapshot of a folder
|
|
1055
1963
|
* that already held twelve hundred files. So a caller either starts a scan
|
|
1056
1964
|
* now, or waits for the one that begins when the current pass ends. A burst
|
|
@@ -1115,6 +2023,20 @@ class FsScanner {
|
|
|
1115
2023
|
await callback(change);
|
|
1116
2024
|
}
|
|
1117
2025
|
}
|
|
2026
|
+
/**
|
|
2027
|
+
* What the last completed scan saw on disk for one path.
|
|
2028
|
+
*
|
|
2029
|
+
* The agent asks this to decide whether a restore may skip writing a file:
|
|
2030
|
+
* a matching blobId means the bytes are already right, and the recorded
|
|
2031
|
+
* size and mtime are what a `stat` is checked against. Reading it from here
|
|
2032
|
+
* rather than from the tree is deliberate — mtime is no longer part of a
|
|
2033
|
+
* tree node, precisely so refs do not depend on it.
|
|
2034
|
+
* @param relativePath - Path relative to the scan root.
|
|
2035
|
+
* @returns What the scan recorded, or `undefined` if it saw no such file.
|
|
2036
|
+
*/
|
|
2037
|
+
knownFile(relativePath) {
|
|
2038
|
+
return this._blobCache.get(relativePath);
|
|
2039
|
+
}
|
|
1118
2040
|
onChange(callback) {
|
|
1119
2041
|
this._changeCallbacks.push(callback);
|
|
1120
2042
|
}
|
|
@@ -1125,6 +2047,10 @@ class FsScanner {
|
|
|
1125
2047
|
}
|
|
1126
2048
|
stopWatch() {
|
|
1127
2049
|
this._stopRequested = true;
|
|
2050
|
+
if (this._settleTimer) {
|
|
2051
|
+
clearTimeout(this._settleTimer);
|
|
2052
|
+
this._settleTimer = null;
|
|
2053
|
+
}
|
|
1128
2054
|
if (this._autoResumeTimer) {
|
|
1129
2055
|
clearTimeout(this._autoResumeTimer);
|
|
1130
2056
|
this._autoResumeTimer = null;
|
|
@@ -1239,26 +2165,30 @@ const DEFAULT_TIMEOUTS = {
|
|
|
1239
2165
|
fetchTree: 2e4,
|
|
1240
2166
|
extract: 15e3,
|
|
1241
2167
|
restore: 15e3,
|
|
1242
|
-
|
|
1243
|
-
debounceMs: 300,
|
|
1244
|
-
processRefRetries: 3,
|
|
1245
|
-
processRefRetryDelayMs: 5e3,
|
|
1246
|
-
recoveryRetries: 10
|
|
2168
|
+
debounceMs: 300
|
|
1247
2169
|
};
|
|
1248
2170
|
const DISCONNECT_PAUSE_MAX_MS = 3e4;
|
|
1249
2171
|
const SYNC_ERROR_FILE = ".sync-errors.log";
|
|
1250
|
-
const
|
|
2172
|
+
const RECOVERED_DIR = ".fsagent-recovered";
|
|
2173
|
+
const DEFAULT_JOIN_WAIT_MS = 1500;
|
|
1251
2174
|
const AGENT_STATE_FILE = ".fsagent-state.json";
|
|
1252
|
-
const REFUSAL_ANSWER_COOLDOWN_MS = 5e3;
|
|
1253
2175
|
const TREE_FETCH_CONCURRENCY = 64;
|
|
1254
2176
|
const RESTORED_BLOB_MEMORY_MAX = 5e4;
|
|
1255
2177
|
const RESTORE_FETCH_CONCURRENCY = 16;
|
|
1256
|
-
const STATE_HISTORY_MAX = 1e3;
|
|
1257
|
-
const VERDICT_REASON = {
|
|
1258
|
-
"own-echo": "is this agent's own last advertisement echoed back",
|
|
1259
|
-
stale: "is not the newest its sender has advertised"
|
|
1260
|
-
};
|
|
1261
2178
|
const MASS_DELETE_MIN_FILES = 100;
|
|
2179
|
+
const REPAIR_ACTION = {
|
|
2180
|
+
"no-head": "blocked",
|
|
2181
|
+
applied: "pull",
|
|
2182
|
+
adopted: "pull",
|
|
2183
|
+
refused: "blocked",
|
|
2184
|
+
announced: "push",
|
|
2185
|
+
merged: "merge",
|
|
2186
|
+
deferred: "blocked",
|
|
2187
|
+
blocked: "blocked"
|
|
2188
|
+
};
|
|
2189
|
+
const RECEIVE_AGAIN_MAX = 3;
|
|
2190
|
+
const STAMP_ASK_MIN_MS = 500;
|
|
2191
|
+
const STAMP_ASK_MAX_MS = 3e4;
|
|
1262
2192
|
const MASS_DELETE_MAX_RATIO = 0.3;
|
|
1263
2193
|
class RestoreIncompleteError extends Error {
|
|
1264
2194
|
}
|
|
@@ -1280,6 +2210,22 @@ class BlobUnavailableError extends RestoreIncompleteError {
|
|
|
1280
2210
|
this.name = "BlobUnavailableError";
|
|
1281
2211
|
}
|
|
1282
2212
|
}
|
|
2213
|
+
class UnwritablePathError extends RestoreIncompleteError {
|
|
2214
|
+
constructor(impossiblePaths) {
|
|
2215
|
+
super(
|
|
2216
|
+
`restore could not write ${impossiblePaths.length} path${impossiblePaths.length === 1 ? "" : "s"} that cannot be written here: ${impossiblePaths.join(", ")}`
|
|
2217
|
+
);
|
|
2218
|
+
this.impossiblePaths = impossiblePaths;
|
|
2219
|
+
this.name = "UnwritablePathError";
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
class DiskFullError extends RestoreIncompleteError {
|
|
2223
|
+
constructor(path) {
|
|
2224
|
+
super(`no space left to write "${path}"`);
|
|
2225
|
+
this.path = path;
|
|
2226
|
+
this.name = "DiskFullError";
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
1283
2229
|
class MassDeleteRefusedError extends RestoreIncompleteError {
|
|
1284
2230
|
constructor(wouldPrune, totalFiles, incomingFiles) {
|
|
1285
2231
|
super(
|
|
@@ -1294,88 +2240,30 @@ class MassDeleteRefusedError extends RestoreIncompleteError {
|
|
|
1294
2240
|
}
|
|
1295
2241
|
}
|
|
1296
2242
|
class FsAgent {
|
|
2243
|
+
/**
|
|
2244
|
+
* The prefix on every line this agent logs — see {@link FsAgentOptions.logName}.
|
|
2245
|
+
*
|
|
2246
|
+
* `[FsAgent]` when unnamed, so an unnamed agent's output is byte-identical
|
|
2247
|
+
* to what it was before this existed.
|
|
2248
|
+
*/
|
|
2249
|
+
_tag;
|
|
1297
2250
|
_scanner;
|
|
1298
2251
|
_adapter;
|
|
1299
2252
|
_rootPath;
|
|
1300
2253
|
_bs;
|
|
1301
|
-
_db;
|
|
1302
|
-
_treeKey;
|
|
1303
|
-
_stopSync;
|
|
1304
|
-
_stopSyncFromDb;
|
|
1305
|
-
_lastSentRef;
|
|
1306
|
-
/**
|
|
1307
|
-
* The ref this agent last pushed as its OWN work.
|
|
1308
|
-
*
|
|
1309
|
-
* Not the same as {@link _lastSentRef}, which an apply also sets when it
|
|
1310
|
-
* leaves the folder equal to — or short of — what it applied. Only a state
|
|
1311
|
-
* this agent authored may be re-announced by the anti-entropy: re-announcing
|
|
1312
|
-
* one it is still catching up to would roll its peers back.
|
|
1313
|
-
*/
|
|
1314
|
-
_lastPushedRef;
|
|
1315
|
-
/** Tuning for the anti-entropy, as passed in. */
|
|
1316
|
-
_antiEntropyOptions;
|
|
1317
|
-
/** The running anti-entropy, while {@link syncFromDb} is active. */
|
|
1318
|
-
_antiEntropy;
|
|
1319
|
-
/**
|
|
1320
|
-
* The incoming ref most recently applied. Retired from the connector's dedup
|
|
1321
|
-
* sets when the next one supersedes it, so a peer returning the tree to that
|
|
1322
|
-
* state can still reach this agent.
|
|
1323
|
-
*/
|
|
1324
|
-
_lastAppliedRef;
|
|
1325
|
-
/** When this agent last answered a refusal, for the cooldown. */
|
|
1326
|
-
_lastRefusalAnswerMs = 0;
|
|
1327
|
-
/** Content fingerprint of the last tree we broadcasted (paths+blobIds) */
|
|
1328
|
-
_lastSentContentKey;
|
|
1329
|
-
/**
|
|
1330
|
-
* True while a ref received from a peer is being applied to disk.
|
|
1331
|
-
*
|
|
1332
|
-
* The safety rescan cannot tell a local change the watcher missed (which it
|
|
1333
|
-
* must broadcast) from a remote change not yet applied here (which it must
|
|
1334
|
-
* not). The agent can: while this is set, the disk is mid-way through
|
|
1335
|
-
* someone else's revision, so a rescan-driven push would re-assert our stale
|
|
1336
|
-
* view — and undo a deletion the peer just made.
|
|
1337
|
-
*/
|
|
1338
|
-
_remoteApplyInFlight = false;
|
|
1339
|
-
/**
|
|
1340
|
-
* Whether a safety rescan was suppressed while a remote apply was running.
|
|
1341
|
-
*
|
|
1342
|
-
* The rescan is what covers a watcher that drops or coalesces events, so a
|
|
1343
|
-
* suppressed one has to be re-run rather than forgotten — see the deferral in
|
|
1344
|
-
* `syncToDb`'s change handler.
|
|
1345
|
-
*/
|
|
1346
|
-
_rescanDeferred = false;
|
|
1347
|
-
/** Re-runs a deferred rescan once the apply that blocked it has finished. */
|
|
1348
|
-
_flushDeferredRescan;
|
|
1349
2254
|
/** Files written vs left alone by the current {@link restore}. */
|
|
1350
2255
|
_restoreWritten = 0;
|
|
1351
2256
|
_restoreSkipped = 0;
|
|
1352
2257
|
/**
|
|
1353
|
-
*
|
|
2258
|
+
* This folder's history: one entry per state this node pushed.
|
|
1354
2259
|
*
|
|
1355
|
-
*
|
|
1356
|
-
*
|
|
1357
|
-
*
|
|
1358
|
-
* an apply re-creates it. The local scan then sees the file present, and the
|
|
1359
|
-
* deletion is never announced at all: silently undone, everywhere.
|
|
2260
|
+
* Created on the first `syncToDb`, and BEST-EFFORT throughout — a chain that
|
|
2261
|
+
* cannot be written must never stop a folder syncing. Nothing consumes it
|
|
2262
|
+
* yet; see `src/fs-edit-chain.ts`.
|
|
1360
2263
|
*/
|
|
1361
|
-
|
|
1362
|
-
/**
|
|
1363
|
-
|
|
1364
|
-
*
|
|
1365
|
-
* A push declaring one of these — but not the current one — comes from a
|
|
1366
|
-
* sender that is behind this node. Applying such a tree is what puts a
|
|
1367
|
-
* deleted file back, so it is ignored outright rather than applied
|
|
1368
|
-
* additively.
|
|
1369
|
-
*/
|
|
1370
|
-
_stateHistory = [];
|
|
1371
|
-
/**
|
|
1372
|
-
* Absolute paths of the files this agent has actually TOLD anyone about.
|
|
1373
|
-
*
|
|
1374
|
-
* A prune may only remove a file that peers could know exists. Anything
|
|
1375
|
-
* written since the last announcement is invisible to every sender, so a
|
|
1376
|
-
* tree that lacks it is not deleting it — it simply predates it.
|
|
1377
|
-
*/
|
|
1378
|
-
_announcedFiles = /* @__PURE__ */ new Set();
|
|
2264
|
+
_chain;
|
|
2265
|
+
/** See {@link FsAgentOptions.joinWaitMs}. */
|
|
2266
|
+
_joinWaitMs;
|
|
1379
2267
|
/**
|
|
1380
2268
|
* Files this restore DELETED.
|
|
1381
2269
|
*
|
|
@@ -1394,46 +2282,100 @@ class FsAgent {
|
|
|
1394
2282
|
* cannot abandon the rest of the tree and, above all, cannot stop the prune.
|
|
1395
2283
|
*/
|
|
1396
2284
|
_restoreUnavailable = [];
|
|
2285
|
+
/** Paths this filesystem rejected outright. See {@link UnwritablePathError}. */
|
|
2286
|
+
_restoreImpossible = [];
|
|
2287
|
+
/**
|
|
2288
|
+
* Paths whose KIND changed — a file where a directory was, or the reverse.
|
|
2289
|
+
*
|
|
2290
|
+
* Counted and reported because such a change removes whatever was there,
|
|
2291
|
+
* and a restore that silently deletes a subtree is one nobody can audit
|
|
2292
|
+
* afterwards.
|
|
2293
|
+
*/
|
|
2294
|
+
_restoreRetyped = 0;
|
|
2295
|
+
/**
|
|
2296
|
+
* How long each stage of the last push and the last apply took, in ms.
|
|
2297
|
+
*
|
|
2298
|
+
* measured on a real fleet: *"im Schnitt 3 Sekunden, im schlechtesten Fall
|
|
2299
|
+
* 84. Alle Zeitbudgets der Testsuite hängen an dieser Zahl."* And the reason
|
|
2300
|
+
* nobody could say more than that: *"bisher wird nur die Gesamtzeit
|
|
2301
|
+
* gemessen. Die einzelnen Schritte mitmessen — Scan, Prüfsumme, Ablage,
|
|
2302
|
+
* Meldung, Abholen, Schreiben —, sonst rät man."* (`the weakness register`
|
|
2303
|
+
* F5/C7.)
|
|
2304
|
+
*
|
|
2305
|
+
* A total tells you a sync was slow. It does not tell you whether the folder
|
|
2306
|
+
* was being hashed, a blob was crossing the network, or a disk was writing —
|
|
2307
|
+
* and those have different people to talk to. Kept as a plain record so a
|
|
2308
|
+
* host can log or display it without this agent deciding how.
|
|
2309
|
+
*/
|
|
2310
|
+
_stageMs = {};
|
|
2311
|
+
/**
|
|
2312
|
+
* Times one stage into {@link _stageMs}.
|
|
2313
|
+
*
|
|
2314
|
+
* Overwrites rather than accumulates: the question is "what did the last
|
|
2315
|
+
* cycle cost", and a running total answers a different one and never resets.
|
|
2316
|
+
* @param stage - The stage name.
|
|
2317
|
+
* @param work - What to time.
|
|
2318
|
+
* @returns Whatever `work` returned.
|
|
2319
|
+
*/
|
|
2320
|
+
async _timed(stage, work) {
|
|
2321
|
+
const started = Date.now();
|
|
2322
|
+
try {
|
|
2323
|
+
return await work();
|
|
2324
|
+
} finally {
|
|
2325
|
+
this._stageMs[stage] = Date.now() - started;
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
/**
|
|
2329
|
+
* What each stage of the last push and apply cost, in milliseconds.
|
|
2330
|
+
*
|
|
2331
|
+
* A snapshot, safe to keep: `push.*` is the send side, `apply.*` the receive
|
|
2332
|
+
* side, and a stage absent simply has not run yet in this process.
|
|
2333
|
+
*/
|
|
2334
|
+
get stageTimings() {
|
|
2335
|
+
return { ...this._stageMs };
|
|
2336
|
+
}
|
|
1397
2337
|
/**
|
|
1398
2338
|
* What this agent last wrote to each absolute path, so a repeat restore can
|
|
1399
2339
|
* recognise its own work without re-reading the file.
|
|
1400
2340
|
*/
|
|
1401
2341
|
_restoredBlobs = /* @__PURE__ */ new Map();
|
|
1402
2342
|
_timeouts;
|
|
1403
|
-
/** Client-only: resolve DAG-branch conflicts into merge revisions. */
|
|
1404
|
-
_resolveConflicts;
|
|
1405
2343
|
/**
|
|
1406
|
-
*
|
|
1407
|
-
*
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
2344
|
+
* Everything this folder has signalled, bounded and countable.
|
|
2345
|
+
*
|
|
2346
|
+
* Seeded from {@link SIGNAL_LOG_FILE} on the first write rather than in the
|
|
2347
|
+
* constructor, because the constructor does no I/O and a host may construct
|
|
2348
|
+
* an agent for a folder that does not exist yet.
|
|
1410
2349
|
*/
|
|
1411
|
-
|
|
2350
|
+
_signals = new FsSignals();
|
|
2351
|
+
/** Whether {@link SIGNAL_LOG_FILE} has been read back yet this process. */
|
|
2352
|
+
_signalsRestored = false;
|
|
1412
2353
|
constructor(rootPath, bs, options = {}) {
|
|
1413
2354
|
this._rootPath = rootPath;
|
|
1414
2355
|
this._bs = bs || new BsMem();
|
|
1415
|
-
this._db = options.db;
|
|
1416
|
-
this._treeKey = options.treeKey;
|
|
1417
2356
|
this._timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts };
|
|
1418
|
-
this.
|
|
1419
|
-
this.
|
|
2357
|
+
if (options.onSignal) this._signals.subscribe(options.onSignal);
|
|
2358
|
+
this._joinWaitMs = options.joinWaitMs ?? DEFAULT_JOIN_WAIT_MS;
|
|
2359
|
+
this._tag = options.logName === void 0 ? "[FsAgent]" : `[FsAgent ${options.logName}]`;
|
|
1420
2360
|
this._scanner = new FsScanner(rootPath, {
|
|
1421
2361
|
...options,
|
|
1422
2362
|
ignore: [
|
|
1423
2363
|
...options.ignore || [],
|
|
1424
2364
|
SYNC_ERROR_FILE,
|
|
1425
2365
|
ATOMIC_TMP_PREFIX,
|
|
1426
|
-
AGENT_STATE_FILE
|
|
2366
|
+
AGENT_STATE_FILE,
|
|
2367
|
+
// The signal log is bookkeeping, not content: a folder that writes a
|
|
2368
|
+
// file to itself on every event never stops changing. A file the agent
|
|
2369
|
+
// writes inside the folder has to be listed here.
|
|
2370
|
+
SIGNAL_LOG_FILE,
|
|
2371
|
+
// And the set-aside copies, for the same reason one level up: they are
|
|
2372
|
+
// deliberately NOT announced, which a tree ref cannot express about a
|
|
2373
|
+
// file inside the folder it describes. See `RECOVERED_DIR`.
|
|
2374
|
+
RECOVERED_DIR
|
|
1427
2375
|
],
|
|
1428
2376
|
bs: this._bs
|
|
1429
2377
|
});
|
|
1430
2378
|
this._adapter = new FsBlobAdapter(this._bs);
|
|
1431
|
-
if (this._db && this._treeKey) {
|
|
1432
|
-
this._startAutoSync().catch(() => {
|
|
1433
|
-
});
|
|
1434
|
-
this._startAutoSyncFromDb(options.bidirectional || false).catch(() => {
|
|
1435
|
-
});
|
|
1436
|
-
}
|
|
1437
2379
|
}
|
|
1438
2380
|
/**
|
|
1439
2381
|
* Gets the root path
|
|
@@ -1472,8 +2414,54 @@ class FsAgent {
|
|
|
1472
2414
|
* A divergence that lasts is the one thing a lost message leaves behind, and
|
|
1473
2415
|
* until now nothing reported it: this is what a diagnostics view should show.
|
|
1474
2416
|
*/
|
|
2417
|
+
/**
|
|
2418
|
+
* Everything that happened to this folder that a person might care about,
|
|
2419
|
+
* oldest first — see {@link FsSignal}.
|
|
2420
|
+
*
|
|
2421
|
+
* Seeded from {@link SIGNAL_LOG_FILE} the first time it is read, so a host
|
|
2422
|
+
* that starts after the event still sees it. Bounded; {@link signalTotals}
|
|
2423
|
+
* keeps the count of what was dropped.
|
|
2424
|
+
* @returns The signals kept.
|
|
2425
|
+
*/
|
|
2426
|
+
get signals() {
|
|
2427
|
+
this._restoreSignals();
|
|
2428
|
+
return this._signals.all;
|
|
2429
|
+
}
|
|
2430
|
+
/**
|
|
2431
|
+
* The signals a person still has to act on — `action: 'required'`.
|
|
2432
|
+
*
|
|
2433
|
+
* The list a UI should surface. Everything else is a record of something the
|
|
2434
|
+
* agent already dealt with.
|
|
2435
|
+
* @returns The unresolved signals.
|
|
2436
|
+
*/
|
|
2437
|
+
get signalsNeedingAction() {
|
|
2438
|
+
this._restoreSignals();
|
|
2439
|
+
return this._signals.needingAction;
|
|
2440
|
+
}
|
|
2441
|
+
/**
|
|
2442
|
+
* How many signals of each kind this folder has EVER produced.
|
|
2443
|
+
*
|
|
2444
|
+
* Not bounded by the log, so a folder that produced two thousand refusals
|
|
2445
|
+
* still says two thousand after the oldest are dropped.
|
|
2446
|
+
* @returns Counts keyed by {@link FsSignalKind}.
|
|
2447
|
+
*/
|
|
2448
|
+
get signalTotals() {
|
|
2449
|
+
this._restoreSignals();
|
|
2450
|
+
return this._signals.totals();
|
|
2451
|
+
}
|
|
2452
|
+
/**
|
|
2453
|
+
* Subscribes to signals as they happen.
|
|
2454
|
+
*
|
|
2455
|
+
* The same channel as the `onSignal` option, for a host that wants to attach
|
|
2456
|
+
* later or more than once.
|
|
2457
|
+
* @param listener - Called once per signal.
|
|
2458
|
+
* @returns Unsubscribes.
|
|
2459
|
+
*/
|
|
2460
|
+
onSignal(listener) {
|
|
2461
|
+
return this._signals.subscribe(listener);
|
|
2462
|
+
}
|
|
1475
2463
|
get antiEntropyStatus() {
|
|
1476
|
-
return this.
|
|
2464
|
+
return this._hubStatus;
|
|
1477
2465
|
}
|
|
1478
2466
|
/**
|
|
1479
2467
|
* Records the ref this folder is now at, so a restart can still say what it
|
|
@@ -1499,35 +2487,95 @@ class FsAgent {
|
|
|
1499
2487
|
await this._scanner.watch();
|
|
1500
2488
|
}
|
|
1501
2489
|
}
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
2490
|
+
/**
|
|
2491
|
+
* Records one signal, tells subscribers, and persists the log.
|
|
2492
|
+
*
|
|
2493
|
+
* **Never throws.** A notification that cannot be filed must not take the
|
|
2494
|
+
* operation it describes with it. Nothing about a sync depends on anybody
|
|
2495
|
+
* being told.
|
|
2496
|
+
* @param input - What happened; see {@link FsSignal}.
|
|
2497
|
+
*/
|
|
2498
|
+
_signal(input) {
|
|
2499
|
+
this._restoreSignals();
|
|
2500
|
+
this._signals.add(input);
|
|
2501
|
+
this._persistSignals();
|
|
2502
|
+
}
|
|
2503
|
+
/**
|
|
2504
|
+
* Reports what joining a network did to this folder.
|
|
2505
|
+
*
|
|
2506
|
+
* **The case a person is most likely to ask about**, and it had no channel at
|
|
2507
|
+
* all: a machine rejoining with files the network has since deleted, or with
|
|
2508
|
+
* its own edits of paths that moved on — a restored backup, a laptop back
|
|
2509
|
+
* from a fortnight away. Nothing is lost either way, because the files are
|
|
2510
|
+
* moved aside rather than removed. But a folder that quietly grows a
|
|
2511
|
+
* `.fsagent-recovered/` directory is unexplainable from outside the machine,
|
|
2512
|
+
* and a line in that machine's console is not an answer.
|
|
2513
|
+
*
|
|
2514
|
+
* Extracted from the join body so it can be tested without standing up a
|
|
2515
|
+
* chain, a db and a peer — the emission is a separate concern from deciding
|
|
2516
|
+
* what to emit about.
|
|
2517
|
+
* @param recovered - Paths moved aside because the history removed them.
|
|
2518
|
+
* @param conflicted - Paths edited here while away and changed elsewhere.
|
|
2519
|
+
*/
|
|
2520
|
+
_signalJoinOutcome(recovered, conflicted) {
|
|
2521
|
+
if (recovered.length > 0) {
|
|
2522
|
+
this._signal({
|
|
2523
|
+
kind: "join/recovered",
|
|
2524
|
+
paths: recovered,
|
|
2525
|
+
action: "review",
|
|
2526
|
+
decidedBy: "chain",
|
|
2527
|
+
detail: `${recovered.length} file(s) this machine still held had been deleted by the network, so they were moved into ${RECOVERED_DIR}/ rather than deleted`
|
|
2528
|
+
});
|
|
2529
|
+
}
|
|
2530
|
+
if (conflicted.length > 0) {
|
|
2531
|
+
this._signal({
|
|
2532
|
+
kind: "join/conflicted",
|
|
2533
|
+
paths: conflicted,
|
|
2534
|
+
action: "review",
|
|
2535
|
+
decidedBy: "chain",
|
|
2536
|
+
detail: `${conflicted.length} file(s) were edited on this machine while it was away and also changed on the network; both versions were kept`
|
|
2537
|
+
});
|
|
2538
|
+
}
|
|
2539
|
+
}
|
|
2540
|
+
/**
|
|
2541
|
+
* Records a standing condition at most once per agent.
|
|
2542
|
+
* @param key - What is being reported once.
|
|
2543
|
+
* @param input - What happened.
|
|
2544
|
+
*/
|
|
2545
|
+
_signalOnce(key, input) {
|
|
2546
|
+
this._restoreSignals();
|
|
2547
|
+
if (this._signals.addOnce(key, input) !== void 0) {
|
|
2548
|
+
this._persistSignals();
|
|
1511
2549
|
}
|
|
1512
2550
|
}
|
|
1513
2551
|
/**
|
|
1514
|
-
*
|
|
2552
|
+
* Reads {@link SIGNAL_LOG_FILE} back, once.
|
|
1515
2553
|
*
|
|
1516
|
-
*
|
|
1517
|
-
*
|
|
1518
|
-
*
|
|
1519
|
-
* @returns The persisted ref, or `undefined`.
|
|
2554
|
+
* Lazily rather than in the constructor, which does no I/O: a host may
|
|
2555
|
+
* construct an agent for a folder that is created later, and a signal log is
|
|
2556
|
+
* never worth failing a construction over.
|
|
1520
2557
|
*/
|
|
1521
|
-
|
|
2558
|
+
_restoreSignals() {
|
|
2559
|
+
if (this._signalsRestored) return;
|
|
2560
|
+
this._signalsRestored = true;
|
|
1522
2561
|
try {
|
|
1523
|
-
const file = join(this._rootPath,
|
|
1524
|
-
if (!existsSync(file)) return
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
2562
|
+
const file = join(this._rootPath, SIGNAL_LOG_FILE);
|
|
2563
|
+
if (!existsSync(file)) return;
|
|
2564
|
+
this._signals.restore(JSON.parse(readFileSync(file, "utf-8")));
|
|
2565
|
+
} catch (err) {
|
|
2566
|
+
this._writeSyncError("signals/restore", err);
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
/** Writes the signal log, best effort. */
|
|
2570
|
+
_persistSignals() {
|
|
2571
|
+
try {
|
|
2572
|
+
writeFileSync(
|
|
2573
|
+
join(this._rootPath, SIGNAL_LOG_FILE),
|
|
2574
|
+
JSON.stringify(this._signals.persisted(), null, 1),
|
|
2575
|
+
"utf-8"
|
|
2576
|
+
);
|
|
2577
|
+
} catch (err) {
|
|
2578
|
+
this._writeSyncError("signals/persist", err);
|
|
1531
2579
|
}
|
|
1532
2580
|
}
|
|
1533
2581
|
/**
|
|
@@ -1548,85 +2596,28 @@ ${err.stack}` : String(err);
|
|
|
1548
2596
|
}
|
|
1549
2597
|
}
|
|
1550
2598
|
/**
|
|
1551
|
-
*
|
|
1552
|
-
*
|
|
1553
|
-
*
|
|
1554
|
-
* @
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
return err instanceof Error ? err.message : String(err);
|
|
1558
|
-
}
|
|
1559
|
-
/**
|
|
1560
|
-
* Retries an async operation up to `attempts` times with exponential backoff
|
|
1561
|
-
* (each delay doubles from `baseDelayMs`). For transient failures — a file
|
|
1562
|
-
* briefly locked by antivirus or a save-and-rename editor, a peer briefly
|
|
1563
|
-
* unreachable. Non-final failures are logged once at warn level so retry
|
|
1564
|
-
* pressure is visible without log-spam.
|
|
1565
|
-
* @param fn - The operation to run
|
|
1566
|
-
* @param attempts - Maximum number of attempts
|
|
1567
|
-
* @param baseDelayMs - Initial backoff delay (doubles each retry)
|
|
1568
|
-
* @param label - Human-readable label for log messages
|
|
1569
|
-
* @returns The operation's resolved value
|
|
1570
|
-
*/
|
|
1571
|
-
static async _withRetry(fn, attempts, baseDelayMs, label) {
|
|
1572
|
-
let lastErr;
|
|
1573
|
-
for (let i = 0; i < attempts; i++) {
|
|
1574
|
-
try {
|
|
1575
|
-
return await fn();
|
|
1576
|
-
} catch (err) {
|
|
1577
|
-
lastErr = err;
|
|
1578
|
-
if (i === attempts - 1) {
|
|
1579
|
-
break;
|
|
1580
|
-
}
|
|
1581
|
-
const delay = baseDelayMs * Math.pow(2, i);
|
|
1582
|
-
console.warn(
|
|
1583
|
-
`[FsAgent] ${label} attempt ${i + 1}/${attempts} failed: ${FsAgent._errMessage(err)} — retry in ${delay}ms`
|
|
1584
|
-
);
|
|
1585
|
-
await new Promise((r) => setTimeout(r, delay));
|
|
1586
|
-
}
|
|
1587
|
-
}
|
|
1588
|
-
throw lastErr;
|
|
1589
|
-
}
|
|
1590
|
-
/**
|
|
1591
|
-
* Atomically writes a file: stages the content in a sibling `.<rand>.tmp`,
|
|
1592
|
-
* then renames over the target. The rename is atomic, so a crash mid-write
|
|
1593
|
-
* leaves only the temp behind — never a half-written target file. (We do not
|
|
1594
|
-
* `fsync` the temp: it adds significant per-file latency under bursty
|
|
1595
|
-
* restores, and durability-on-power-loss is secondary here since the content
|
|
1596
|
-
* is replicated and re-synced.) The random suffix keeps concurrent restores
|
|
1597
|
-
* of the same path from trampling each other.
|
|
2599
|
+
* Writes a file through a staging file and a rename.
|
|
2600
|
+
*
|
|
2601
|
+
* Kept as a thin named wrapper because the restore path reads as a pair with
|
|
2602
|
+
* {@link FsAgent._atomicWriteStream}. The rule, and the byte-level
|
|
2603
|
+
* corruption that made it a rule on every platform rather than on Windows
|
|
2604
|
+
* only, are in `fs-atomic-write.ts`.
|
|
1598
2605
|
* @param filePath - Destination path
|
|
1599
2606
|
* @param content - Bytes to write
|
|
1600
2607
|
*/
|
|
1601
2608
|
static async _atomicWriteFile(filePath, content) {
|
|
1602
|
-
|
|
1603
|
-
await writeFile(filePath, content);
|
|
1604
|
-
return;
|
|
1605
|
-
}
|
|
1606
|
-
const rnd = `${Date.now().toString(36)}-${Math.floor(
|
|
1607
|
-
Math.random() * 1e9
|
|
1608
|
-
).toString(36)}`;
|
|
1609
|
-
const tmp = join(dirname(filePath), `${ATOMIC_TMP_PREFIX}${rnd}`);
|
|
1610
|
-
try {
|
|
1611
|
-
await writeFile(tmp, content);
|
|
1612
|
-
await rename(tmp, filePath);
|
|
1613
|
-
} catch (err) {
|
|
1614
|
-
try {
|
|
1615
|
-
await unlink(tmp);
|
|
1616
|
-
} catch {
|
|
1617
|
-
}
|
|
1618
|
-
throw err;
|
|
1619
|
-
}
|
|
2609
|
+
return atomicWriteFile(filePath, content);
|
|
1620
2610
|
}
|
|
1621
2611
|
/**
|
|
1622
2612
|
* Whether this error came from reading the blob rather than writing the file.
|
|
1623
2613
|
*
|
|
1624
2614
|
* The two have different answers. A blob that cannot be fetched costs one
|
|
1625
2615
|
* file and the tree applies without it; a file that cannot be written is
|
|
1626
|
-
* usually a
|
|
1627
|
-
*
|
|
1628
|
-
*
|
|
1629
|
-
*
|
|
2616
|
+
* usually a document the host application still has open for a user, and that
|
|
2617
|
+
* one must not abort
|
|
2618
|
+
* the rest of the restore either. Conflating them would report an offline
|
|
2619
|
+
* peer as a locked file, and the field reports are read by people who act on
|
|
2620
|
+
* that distinction.
|
|
1630
2621
|
* @param error - The error thrown while writing the file.
|
|
1631
2622
|
* @returns Whether it came from the blob source.
|
|
1632
2623
|
*/
|
|
@@ -1636,12 +2627,12 @@ ${err.stack}` : String(err);
|
|
|
1636
2627
|
/**
|
|
1637
2628
|
* Writes a file from a stream, holding one chunk at a time.
|
|
1638
2629
|
*
|
|
1639
|
-
* The twin of {@link FsAgent._atomicWriteFile}
|
|
1640
|
-
*
|
|
1641
|
-
* file used to cost 500 MB of Buffer on the receiving agent, another
|
|
1642
|
-
* the socket parser, and — on the serving hub — the same again. That
|
|
1643
|
-
* shape that
|
|
1644
|
-
* than garbage, so no collection can reclaim any of it.
|
|
2630
|
+
* The twin of {@link FsAgent._atomicWriteFile} — temp and rename on every
|
|
2631
|
+
* platform, for the same reasons — but never materialising the whole file. A
|
|
2632
|
+
* 500 MB file used to cost 500 MB of Buffer on the receiving agent, another
|
|
2633
|
+
* copy in the socket parser, and — on the serving hub — the same again. That
|
|
2634
|
+
* is the shape that exhausted a cloud relay: memory that is work in flight
|
|
2635
|
+
* rather than garbage, so no collection can reclaim any of it.
|
|
1645
2636
|
*
|
|
1646
2637
|
* Read failures are tagged, because from here on the bytes arrive during the
|
|
1647
2638
|
* write rather than before it, and {@link FsAgent._isBlobReadError} is what
|
|
@@ -1650,46 +2641,14 @@ ${err.stack}` : String(err);
|
|
|
1650
2641
|
* @param stream - The bytes.
|
|
1651
2642
|
*/
|
|
1652
2643
|
static async _atomicWriteStream(filePath, stream) {
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
2644
|
+
return atomicWriteStream(
|
|
2645
|
+
filePath,
|
|
2646
|
+
stream,
|
|
2647
|
+
(error) => Object.assign(
|
|
2648
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
2649
|
+
{ __blobRead: true }
|
|
2650
|
+
)
|
|
1658
2651
|
);
|
|
1659
|
-
const handle = await open(target, "w");
|
|
1660
|
-
try {
|
|
1661
|
-
const reader = stream.getReader();
|
|
1662
|
-
for (; ; ) {
|
|
1663
|
-
let chunk;
|
|
1664
|
-
try {
|
|
1665
|
-
chunk = await reader.read();
|
|
1666
|
-
} catch (error) {
|
|
1667
|
-
throw Object.assign(
|
|
1668
|
-
error instanceof Error ? error : new Error(String(error)),
|
|
1669
|
-
{ __blobRead: true }
|
|
1670
|
-
);
|
|
1671
|
-
}
|
|
1672
|
-
if (chunk.done) break;
|
|
1673
|
-
await handle.write(chunk.value);
|
|
1674
|
-
}
|
|
1675
|
-
} catch (error) {
|
|
1676
|
-
await handle.close();
|
|
1677
|
-
if (target !== filePath) {
|
|
1678
|
-
await unlink(target).catch(() => {
|
|
1679
|
-
});
|
|
1680
|
-
}
|
|
1681
|
-
throw error;
|
|
1682
|
-
}
|
|
1683
|
-
await handle.close();
|
|
1684
|
-
if (target !== filePath) {
|
|
1685
|
-
try {
|
|
1686
|
-
await rename(target, filePath);
|
|
1687
|
-
} catch (err) {
|
|
1688
|
-
await unlink(target).catch(() => {
|
|
1689
|
-
});
|
|
1690
|
-
throw err;
|
|
1691
|
-
}
|
|
1692
|
-
}
|
|
1693
2652
|
}
|
|
1694
2653
|
/**
|
|
1695
2654
|
* Wraps a promise with a timeout.
|
|
@@ -1700,14 +2659,14 @@ ${err.stack}` : String(err);
|
|
|
1700
2659
|
* @param label - Human-readable label included in the error message
|
|
1701
2660
|
*/
|
|
1702
2661
|
static _withTimeout(promise, ms, label) {
|
|
1703
|
-
return new Promise((
|
|
2662
|
+
return new Promise((resolve2, reject) => {
|
|
1704
2663
|
const timer = setTimeout(() => {
|
|
1705
2664
|
reject(new Error(`Timeout after ${ms}ms: ${label}`));
|
|
1706
2665
|
}, ms);
|
|
1707
2666
|
promise.then(
|
|
1708
2667
|
(value) => {
|
|
1709
2668
|
clearTimeout(timer);
|
|
1710
|
-
|
|
2669
|
+
resolve2(value);
|
|
1711
2670
|
},
|
|
1712
2671
|
(err) => {
|
|
1713
2672
|
clearTimeout(timer);
|
|
@@ -1717,70 +2676,27 @@ ${err.stack}` : String(err);
|
|
|
1717
2676
|
});
|
|
1718
2677
|
}
|
|
1719
2678
|
/**
|
|
1720
|
-
*
|
|
1721
|
-
*
|
|
1722
|
-
*
|
|
1723
|
-
*
|
|
1724
|
-
*
|
|
1725
|
-
*
|
|
1726
|
-
*
|
|
1727
|
-
*
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
}
|
|
1739
|
-
},
|
|
1740
|
-
3,
|
|
1741
|
-
100,
|
|
1742
|
-
`sendRef(${ref.slice(0, 12)}…)`
|
|
1743
|
-
);
|
|
1744
|
-
}
|
|
1745
|
-
/**
|
|
1746
|
-
* Starts automatic syncing to database
|
|
1747
|
-
* Note: Auto-sync requires Connector which is not available in constructor.
|
|
1748
|
-
* Consider using syncToDb() directly instead of constructor options.
|
|
1749
|
-
*/
|
|
1750
|
-
async _startAutoSync() {
|
|
1751
|
-
if (!this._db || !this._treeKey) {
|
|
1752
|
-
return;
|
|
1753
|
-
}
|
|
1754
|
-
throw new Error(
|
|
1755
|
-
"Auto-sync from constructor is not supported. Use syncToDb() method directly with a Connector instance."
|
|
1756
|
-
);
|
|
1757
|
-
}
|
|
1758
|
-
/**
|
|
1759
|
-
* Starts automatic syncing from database
|
|
1760
|
-
* @param bidirectional - Whether bidirectional sync is enabled
|
|
1761
|
-
* Note: Auto-sync requires Connector which is not available in constructor.
|
|
1762
|
-
* Consider using syncFromDb() directly instead of constructor options.
|
|
1763
|
-
*/
|
|
1764
|
-
async _startAutoSyncFromDb(bidirectional) {
|
|
1765
|
-
if (!this._db || !this._treeKey || !bidirectional) {
|
|
1766
|
-
return;
|
|
1767
|
-
}
|
|
1768
|
-
throw new Error(
|
|
1769
|
-
"Auto-sync from constructor is not supported. Use syncFromDb() method directly with a Connector instance."
|
|
1770
|
-
);
|
|
1771
|
-
}
|
|
1772
|
-
/**
|
|
1773
|
-
* Stops automatic syncing and cleans up resources
|
|
2679
|
+
* Abandons a join this agent is still waiting on.
|
|
2680
|
+
*
|
|
2681
|
+
* **This method used to do nothing at all**, and the host application calls
|
|
2682
|
+
* it in
|
|
2683
|
+
* six places on shutdown. It read two fields that were never assigned —
|
|
2684
|
+
* leftovers of the constructor auto-sync pattern, which was removed — each
|
|
2685
|
+
* behind a `v8 ignore` that hid the fact. The real stopping is done by the
|
|
2686
|
+
* functions `syncToDb` and `syncFromDb` return, which the client already
|
|
2687
|
+
* calls first.
|
|
2688
|
+
*
|
|
2689
|
+
* What it does now is the one thing those cannot: cancel a pending join. A
|
|
2690
|
+
* folder that deferred its first announcement keeps asking the network for a
|
|
2691
|
+
* head every {@link JOIN_ASK_INTERVAL_MS} until the wait expires, and a
|
|
2692
|
+
* `stop()` does not end it — so a node shut down mid-join went on asking a
|
|
2693
|
+
* connector that was being torn down, and every refusal reached the sync
|
|
2694
|
+
* error log. The timers are `unref`'d, so this was never a reason the
|
|
2695
|
+
* process stayed alive; it was noise at exactly the moment a shutdown is
|
|
2696
|
+
* being diagnosed.
|
|
1774
2697
|
*/
|
|
1775
2698
|
dispose() {
|
|
1776
|
-
|
|
1777
|
-
this._stopSync();
|
|
1778
|
-
this._stopSync = void 0;
|
|
1779
|
-
}
|
|
1780
|
-
if (this._stopSyncFromDb) {
|
|
1781
|
-
this._stopSyncFromDb();
|
|
1782
|
-
this._stopSyncFromDb = void 0;
|
|
1783
|
-
}
|
|
2699
|
+
this._endJoinWait();
|
|
1784
2700
|
}
|
|
1785
2701
|
/**
|
|
1786
2702
|
* Extracts filesystem into tree structure with file content in blobs
|
|
@@ -1788,7 +2704,7 @@ ${err.stack}` : String(err);
|
|
|
1788
2704
|
* @returns Tree structure with blobIds in file metadata
|
|
1789
2705
|
*/
|
|
1790
2706
|
async extract() {
|
|
1791
|
-
const tree = await this._scanner.scan();
|
|
2707
|
+
const tree = await this._timed("push.scan", () => this._scanner.scan());
|
|
1792
2708
|
return tree;
|
|
1793
2709
|
}
|
|
1794
2710
|
/**
|
|
@@ -1803,12 +2719,18 @@ ${err.stack}` : String(err);
|
|
|
1803
2719
|
tree,
|
|
1804
2720
|
target
|
|
1805
2721
|
);
|
|
2722
|
+
const expectedByLowerCase = /* @__PURE__ */ new Map();
|
|
2723
|
+
for (const expected of expectedFiles) {
|
|
2724
|
+
expectedByLowerCase.set(expected.toLowerCase(), expected);
|
|
2725
|
+
}
|
|
1806
2726
|
const preRestore = options?.cleanTarget ? await this._collectAllFiles(target) : /* @__PURE__ */ new Set();
|
|
1807
2727
|
this._restoreWritten = 0;
|
|
1808
2728
|
this._restoreSkipped = 0;
|
|
1809
2729
|
this._restorePruned = 0;
|
|
1810
2730
|
this._restoreLocked = [];
|
|
1811
2731
|
this._restoreUnavailable = [];
|
|
2732
|
+
this._restoreImpossible = [];
|
|
2733
|
+
this._restoreRetyped = 0;
|
|
1812
2734
|
await this._restoreTree(
|
|
1813
2735
|
tree.rootHash,
|
|
1814
2736
|
tree.trees,
|
|
@@ -1816,19 +2738,35 @@ ${err.stack}` : String(err);
|
|
|
1816
2738
|
target === this._rootPath
|
|
1817
2739
|
);
|
|
1818
2740
|
if (options?.cleanTarget) {
|
|
2741
|
+
const incomingBlobs = /* @__PURE__ */ new Set();
|
|
2742
|
+
for (const [, node] of tree.trees) {
|
|
2743
|
+
const blobId = node?.meta?.blobId;
|
|
2744
|
+
if (blobId) incomingBlobs.add(blobId);
|
|
2745
|
+
}
|
|
1819
2746
|
let wouldPrune = 0;
|
|
2747
|
+
let moved = 0;
|
|
1820
2748
|
for (const existing of preRestore) {
|
|
1821
|
-
if (
|
|
2749
|
+
if (expectedFiles.has(existing)) continue;
|
|
2750
|
+
const rel = relative(this._rootPath, existing).split(sep).join("/");
|
|
2751
|
+
const known = this._scanner.knownFile(rel)?.blobId;
|
|
2752
|
+
if (known !== void 0 && incomingBlobs.has(known)) {
|
|
2753
|
+
moved++;
|
|
2754
|
+
continue;
|
|
2755
|
+
}
|
|
2756
|
+
wouldPrune++;
|
|
1822
2757
|
}
|
|
1823
|
-
if (
|
|
1824
|
-
console.
|
|
1825
|
-
|
|
2758
|
+
if (moved > 0) {
|
|
2759
|
+
console.log(
|
|
2760
|
+
`${this._tag} ${moved} file(s) moved rather than deleted — not counted against the mass-delete guard`
|
|
1826
2761
|
);
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
2762
|
+
}
|
|
2763
|
+
if (wouldPrune > MASS_DELETE_MIN_FILES && (expectedFiles.size === 0 || wouldPrune / preRestore.size > MASS_DELETE_MAX_RATIO)) {
|
|
2764
|
+
this._refuseDeletion(
|
|
2765
|
+
"restore",
|
|
2766
|
+
wouldPrune,
|
|
2767
|
+
preRestore.size,
|
|
2768
|
+
[...preRestore].filter((p) => !expectedFiles.has(p)),
|
|
2769
|
+
`The incoming tree has ${expectedFiles.size}.`
|
|
1832
2770
|
);
|
|
1833
2771
|
throw new MassDeleteRefusedError(
|
|
1834
2772
|
wouldPrune,
|
|
@@ -1840,19 +2778,29 @@ ${err.stack}` : String(err);
|
|
|
1840
2778
|
target,
|
|
1841
2779
|
expectedDirs,
|
|
1842
2780
|
expectedFiles,
|
|
1843
|
-
preRestore
|
|
2781
|
+
preRestore,
|
|
2782
|
+
expectedByLowerCase
|
|
1844
2783
|
);
|
|
1845
2784
|
}
|
|
1846
2785
|
if (this._restoreSkipped > 0 || this._restorePruned > 0) {
|
|
1847
2786
|
console.log(
|
|
1848
|
-
|
|
2787
|
+
`${this._tag} restore: wrote ${this._restoreWritten}, left ${this._restoreSkipped} already-correct file${this._restoreSkipped === 1 ? "" : "s"} untouched` + (this._restorePruned > 0 ? `, DELETED ${this._restorePruned}` : "")
|
|
1849
2788
|
);
|
|
1850
2789
|
}
|
|
1851
2790
|
if (this._restoreLocked.length > 0) {
|
|
1852
|
-
throw new PartialRestoreError([...this._restoreLocked]);
|
|
2791
|
+
throw new PartialRestoreError([...this._restoreLocked].sort());
|
|
1853
2792
|
}
|
|
1854
2793
|
if (this._restoreUnavailable.length > 0) {
|
|
1855
|
-
throw new BlobUnavailableError([...this._restoreUnavailable]);
|
|
2794
|
+
throw new BlobUnavailableError([...this._restoreUnavailable].sort());
|
|
2795
|
+
}
|
|
2796
|
+
if (this._restoreImpossible.length > 0) {
|
|
2797
|
+
this._signal({
|
|
2798
|
+
kind: "path/unwritable",
|
|
2799
|
+
paths: [...this._restoreImpossible],
|
|
2800
|
+
action: "required",
|
|
2801
|
+
detail: `${this._restoreImpossible.length} path(s) cannot be written on this machine — too long, a reserved name, or otherwise rejected by the filesystem. They will not arrive until they are renamed.`
|
|
2802
|
+
});
|
|
2803
|
+
throw new UnwritablePathError([...this._restoreImpossible].sort());
|
|
1856
2804
|
}
|
|
1857
2805
|
}
|
|
1858
2806
|
/**
|
|
@@ -1898,29 +2846,37 @@ ${err.stack}` : String(err);
|
|
|
1898
2846
|
throw new Error(`Tree node is missing meta for hash: ${treeHash}`);
|
|
1899
2847
|
}
|
|
1900
2848
|
if (meta.type === "file") {
|
|
2849
|
+
if (!FsAgent._isInsideRoot(targetPath, meta.relativePath)) {
|
|
2850
|
+
console.error(
|
|
2851
|
+
`${this._tag} REFUSED a tree path that leaves the sync folder: "${meta.relativePath}". Nothing was written. This is a tree that should not exist; the rest of it is still applied.`
|
|
2852
|
+
);
|
|
2853
|
+
this._writeSyncError(
|
|
2854
|
+
"restore/pathEscapesRoot",
|
|
2855
|
+
new Error(`"${meta.relativePath}" resolves outside ${targetPath}`)
|
|
2856
|
+
);
|
|
2857
|
+
this._restoreImpossible.push(meta.relativePath);
|
|
2858
|
+
return;
|
|
2859
|
+
}
|
|
1901
2860
|
const filePath = join(targetPath, meta.relativePath);
|
|
2861
|
+
await this._makeRoomFor(filePath, "file");
|
|
1902
2862
|
if (meta.blobId) {
|
|
1903
2863
|
if (await this._alreadyOnDisk(filePath, meta, isOwnRoot)) {
|
|
1904
2864
|
this._restoreSkipped++;
|
|
1905
2865
|
return;
|
|
1906
2866
|
}
|
|
1907
|
-
if (this._pendingDeletes.has(filePath)) {
|
|
1908
|
-
this._restoreSkipped++;
|
|
1909
|
-
return;
|
|
1910
|
-
}
|
|
1911
2867
|
let fileStream;
|
|
1912
2868
|
try {
|
|
1913
2869
|
fileStream = await this._bs.getBlobStream(meta.blobId);
|
|
1914
2870
|
} catch (error) {
|
|
1915
2871
|
console.warn(
|
|
1916
|
-
|
|
2872
|
+
`${this._tag} cannot fetch blob for "${meta.relativePath}" (blobId: ${meta.blobId}): ${error instanceof Error ? error.message : String(error)} — skipping this file and applying the rest of the tree.`
|
|
1917
2873
|
);
|
|
1918
2874
|
this._restoreUnavailable.push(meta.relativePath);
|
|
1919
2875
|
return;
|
|
1920
2876
|
}
|
|
1921
2877
|
if (!fileStream) {
|
|
1922
2878
|
console.warn(
|
|
1923
|
-
|
|
2879
|
+
`${this._tag} missing blob content for "${meta.relativePath}" (blobId: ${meta.blobId}) — skipping this file and applying the rest of the tree.`
|
|
1924
2880
|
);
|
|
1925
2881
|
this._restoreUnavailable.push(meta.relativePath);
|
|
1926
2882
|
return;
|
|
@@ -1933,7 +2889,11 @@ ${err.stack}` : String(err);
|
|
|
1933
2889
|
const mtime = new Date(meta.mtime);
|
|
1934
2890
|
await utimes(filePath, mtime, mtime);
|
|
1935
2891
|
}
|
|
1936
|
-
|
|
2892
|
+
const written = await stat(filePath).catch(
|
|
2893
|
+
/* v8 ignore next -- @preserve the file was just written successfully */
|
|
2894
|
+
() => void 0
|
|
2895
|
+
);
|
|
2896
|
+
if (meta.size !== void 0 && written !== void 0) {
|
|
1937
2897
|
if (this._restoredBlobs.size >= RESTORED_BLOB_MEMORY_MAX) {
|
|
1938
2898
|
const oldest = this._restoredBlobs.keys().next().value;
|
|
1939
2899
|
this._restoredBlobs.delete(oldest);
|
|
@@ -1941,26 +2901,62 @@ ${err.stack}` : String(err);
|
|
|
1941
2901
|
this._restoredBlobs.set(filePath, {
|
|
1942
2902
|
blobId: meta.blobId,
|
|
1943
2903
|
size: meta.size,
|
|
1944
|
-
mtime:
|
|
2904
|
+
mtime: written.mtime.getTime()
|
|
1945
2905
|
});
|
|
2906
|
+
if (isOwnRoot) {
|
|
2907
|
+
this._scanner.noteWrite(
|
|
2908
|
+
meta.relativePath,
|
|
2909
|
+
meta.blobId,
|
|
2910
|
+
meta.size,
|
|
2911
|
+
written.mtime.getTime()
|
|
2912
|
+
);
|
|
2913
|
+
}
|
|
1946
2914
|
}
|
|
1947
2915
|
} catch (error) {
|
|
1948
2916
|
if (FsAgent._isBlobReadError(error)) {
|
|
1949
2917
|
console.warn(
|
|
1950
|
-
|
|
2918
|
+
`${this._tag} blob transfer for "${meta.relativePath}" broke off (blobId: ${meta.blobId}): ${error instanceof Error ? error.message : String(error)} — skipping this file and applying the rest of the tree.`
|
|
1951
2919
|
);
|
|
1952
2920
|
this._restoreUnavailable.push(meta.relativePath);
|
|
1953
2921
|
return;
|
|
1954
2922
|
}
|
|
2923
|
+
if (error?.code === "ENOSPC") {
|
|
2924
|
+
console.error(
|
|
2925
|
+
`${this._tag} NO SPACE LEFT on the volume holding ${this._rootPath} — "${meta.relativePath}" could not be written. Sync is stopped for this folder until space is freed.`
|
|
2926
|
+
);
|
|
2927
|
+
this._writeSyncError("restore/diskFull", error);
|
|
2928
|
+
throw new DiskFullError(meta.relativePath);
|
|
2929
|
+
}
|
|
2930
|
+
if (FsAgent._isImpossiblePath(error)) {
|
|
2931
|
+
console.warn(
|
|
2932
|
+
`${this._tag} restore: "${meta.relativePath}" cannot exist on this filesystem (${error.code}) — skipped, and the rest of the tree applied.`
|
|
2933
|
+
);
|
|
2934
|
+
this._restoreImpossible.push(meta.relativePath);
|
|
2935
|
+
return;
|
|
2936
|
+
}
|
|
1955
2937
|
if (!FsAgent._isLocked(error)) throw error;
|
|
1956
2938
|
console.warn(
|
|
1957
|
-
|
|
2939
|
+
`${this._tag} restore: "${meta.relativePath}" is held open by another process (${error.code}) — skipped, will retry`
|
|
1958
2940
|
);
|
|
1959
2941
|
this._restoreLocked.push(meta.relativePath);
|
|
1960
2942
|
}
|
|
1961
2943
|
}
|
|
1962
2944
|
} else if (meta.type === "directory") {
|
|
2945
|
+
if (!FsAgent._isInsideRoot(targetPath, meta.relativePath)) {
|
|
2946
|
+
console.error(
|
|
2947
|
+
`${this._tag} REFUSED a tree directory that leaves the sync folder: "${meta.relativePath}". Nothing was created.`
|
|
2948
|
+
);
|
|
2949
|
+
this._writeSyncError(
|
|
2950
|
+
"restore/pathEscapesRoot",
|
|
2951
|
+
new Error(`"${meta.relativePath}" resolves outside ${targetPath}`)
|
|
2952
|
+
);
|
|
2953
|
+
this._restoreImpossible.push(meta.relativePath);
|
|
2954
|
+
return;
|
|
2955
|
+
}
|
|
1963
2956
|
const dirPath = meta.relativePath === "." ? targetPath : join(targetPath, meta.relativePath);
|
|
2957
|
+
if (meta.relativePath !== ".") {
|
|
2958
|
+
await this._makeRoomFor(dirPath, "directory");
|
|
2959
|
+
}
|
|
1964
2960
|
await mkdir(dirPath, { recursive: true });
|
|
1965
2961
|
if (treeNode.children && Array.isArray(treeNode.children)) {
|
|
1966
2962
|
const children = [...treeNode.children];
|
|
@@ -1996,6 +2992,122 @@ ${err.stack}` : String(err);
|
|
|
1996
2992
|
* @param err - The caught value.
|
|
1997
2993
|
* @returns `true` for a lock-shaped error.
|
|
1998
2994
|
*/
|
|
2995
|
+
/**
|
|
2996
|
+
* Whether a write failed because the PATH is impossible here, rather than
|
|
2997
|
+
* because the file is busy.
|
|
2998
|
+
*
|
|
2999
|
+
* The rules differ per platform and this agent must not encode them: Windows
|
|
3000
|
+
* refuses a component over 255, a total path over 260, the reserved device
|
|
3001
|
+
* names (`CON`, `PRN`, `AUX`, `NUL`, `COM1`…), a trailing space or dot;
|
|
3002
|
+
* POSIX refuses a component over 255 and an embedded NUL. What they share is
|
|
3003
|
+
* the errno, so the errno is what this reads.
|
|
3004
|
+
*
|
|
3005
|
+
* Deliberately NOT retried, unlike a lock: a name does not become legal by
|
|
3006
|
+
* waiting. The file is reported as unavailable and the tree is applied
|
|
3007
|
+
* around it.
|
|
3008
|
+
* @param err - The caught value.
|
|
3009
|
+
* @returns Whether the path itself is the problem.
|
|
3010
|
+
*/
|
|
3011
|
+
/**
|
|
3012
|
+
* Whether a tree's path stays inside the folder being restored.
|
|
3013
|
+
*
|
|
3014
|
+
* A tree is DATA FROM ANOTHER MACHINE. Nothing has checked where its paths
|
|
3015
|
+
* point, and `join(target, '../escaped.txt')` resolves outside the target —
|
|
3016
|
+
* so a peer, or one corrupted node, could write anywhere this process can.
|
|
3017
|
+
* Measured before this existed: a tree carrying `../escaped.txt` put a file
|
|
3018
|
+
* next to the sync folder, and the restore reported success.
|
|
3019
|
+
*
|
|
3020
|
+
* It needs no malice to matter. A relative path assembled wrongly, a
|
|
3021
|
+
* `relativePath` left absolute by a future scanner, a tree edited by hand to
|
|
3022
|
+
* reproduce a bug — all of them become an arbitrary file write on every node
|
|
3023
|
+
* that applies the tree.
|
|
3024
|
+
*
|
|
3025
|
+
* Checked by RESOLVING rather than by looking for `..`, because `a/../../b`,
|
|
3026
|
+
* a symlinked parent and an absolute path are all the same question and only
|
|
3027
|
+
* one of them contains the obvious substring.
|
|
3028
|
+
* @param target - The folder being restored into.
|
|
3029
|
+
* @param relativePath - The path the tree claims.
|
|
3030
|
+
* @returns Whether it is safe to write.
|
|
3031
|
+
*/
|
|
3032
|
+
/**
|
|
3033
|
+
* Clears whatever is at a path so a node of a DIFFERENT KIND can be written
|
|
3034
|
+
* there.
|
|
3035
|
+
*
|
|
3036
|
+
* A path does not only change its contents; it changes what it IS. A user
|
|
3037
|
+
* replaces a stray file with the folder it should have been, an export
|
|
3038
|
+
* writes a single document where an unpacked directory used to sit. Both
|
|
3039
|
+
* mature comparable projects test exactly these transitions —
|
|
3040
|
+
* Syncthing as `filetype_test.go`, Unison as "file replacement" and
|
|
3041
|
+
* "directory replacement" — and this agent did neither.
|
|
3042
|
+
*
|
|
3043
|
+
* Measured before this existed, all three aborting the WHOLE restore with a
|
|
3044
|
+
* raw errno, so a single type change stopped the folder syncing:
|
|
3045
|
+
*
|
|
3046
|
+
* file → directory EEXIST: file already exists, mkdir
|
|
3047
|
+
* empty directory → file EISDIR: illegal operation on a directory
|
|
3048
|
+
* directory with files → file the same
|
|
3049
|
+
*
|
|
3050
|
+
* Nothing is destroyed that the tree does not already say is gone, and the
|
|
3051
|
+
* mass-delete guard has already counted it: the subtree's files are in
|
|
3052
|
+
* `preRestore` and absent from `expectedFiles`, which is exactly the
|
|
3053
|
+
* population it judges. So a type change that would empty a folder is still
|
|
3054
|
+
* refused before the walk reaches here.
|
|
3055
|
+
*
|
|
3056
|
+
* `lstat`, not `stat`: a symlink is a third kind of thing and must not be
|
|
3057
|
+
* followed to decide what to remove.
|
|
3058
|
+
* @param path - Where the node is to be written.
|
|
3059
|
+
* @param want - What the tree says should be there.
|
|
3060
|
+
* @returns Whether something had to be removed.
|
|
3061
|
+
*/
|
|
3062
|
+
/**
|
|
3063
|
+
* Whether a path the prune is about to delete is actually the expected file
|
|
3064
|
+
* under another spelling of its name.
|
|
3065
|
+
*
|
|
3066
|
+
* On a case-insensitive filesystem `Angebot.docx` and `angebot.docx` are one
|
|
3067
|
+
* file, so the two paths share an inode. On a case-sensitive one they are
|
|
3068
|
+
* two files with two inodes, and the entry really is extraneous. Comparing
|
|
3069
|
+
* the inode answers both without knowing which kind of filesystem this is.
|
|
3070
|
+
* @param fullPath - The entry the prune found on disk.
|
|
3071
|
+
* @param expectedByLowerCase - Expected paths indexed by lower case.
|
|
3072
|
+
* @returns Whether the entry must be kept.
|
|
3073
|
+
*/
|
|
3074
|
+
async _isSameFileAsExpected(fullPath, expectedByLowerCase) {
|
|
3075
|
+
const expected = expectedByLowerCase.get(fullPath.toLowerCase());
|
|
3076
|
+
if (expected === void 0 || expected === fullPath) return false;
|
|
3077
|
+
const [here, there] = await Promise.all([
|
|
3078
|
+
lstat(fullPath).catch(() => void 0),
|
|
3079
|
+
lstat(expected).catch(() => void 0)
|
|
3080
|
+
]);
|
|
3081
|
+
if (here === void 0 || there === void 0) return false;
|
|
3082
|
+
const same = here.ino === there.ino && here.dev === there.dev;
|
|
3083
|
+
if (same) {
|
|
3084
|
+
console.warn(
|
|
3085
|
+
`${this._tag} restore: kept "${fullPath}" — the tree spells it "${expected}" and this filesystem treats them as one file`
|
|
3086
|
+
);
|
|
3087
|
+
}
|
|
3088
|
+
return same;
|
|
3089
|
+
}
|
|
3090
|
+
async _makeRoomFor(path, want) {
|
|
3091
|
+
const existing = await lstat(path).catch(() => void 0);
|
|
3092
|
+
if (existing === void 0) return false;
|
|
3093
|
+
const isDir = existing.isDirectory();
|
|
3094
|
+
if (isDir === (want === "directory")) return false;
|
|
3095
|
+
await rm(path, { recursive: true, force: true });
|
|
3096
|
+
this._restoreRetyped++;
|
|
3097
|
+
console.warn(
|
|
3098
|
+
`${this._tag} restore: "${path}" was a ${isDir ? "directory" : "file"} and the tree says ${want} — replacing it`
|
|
3099
|
+
);
|
|
3100
|
+
return true;
|
|
3101
|
+
}
|
|
3102
|
+
static _isInsideRoot(target, relativePath) {
|
|
3103
|
+
const root = resolve(target);
|
|
3104
|
+
const full = resolve(root, relativePath);
|
|
3105
|
+
return full === root || full.startsWith(root + sep);
|
|
3106
|
+
}
|
|
3107
|
+
static _isImpossiblePath(err) {
|
|
3108
|
+
const code = err?.code;
|
|
3109
|
+
return code === "ENAMETOOLONG" || code === "EINVAL" || code === "EILSEQ" || code === "ENOTDIR";
|
|
3110
|
+
}
|
|
1999
3111
|
static _isLocked(err) {
|
|
2000
3112
|
const code = err?.code;
|
|
2001
3113
|
return code === "EPERM" || code === "EBUSY" || code === "EACCES";
|
|
@@ -2018,15 +3130,7 @@ ${err.stack}` : String(err);
|
|
|
2018
3130
|
const written = this._restoredBlobs.get(filePath);
|
|
2019
3131
|
if (written) return written;
|
|
2020
3132
|
if (!isOwnRoot) return void 0;
|
|
2021
|
-
|
|
2022
|
-
if (scanned?.blobId === void 0 || scanned.size === void 0 || scanned.mtime === void 0) {
|
|
2023
|
-
return void 0;
|
|
2024
|
-
}
|
|
2025
|
-
return {
|
|
2026
|
-
blobId: scanned.blobId,
|
|
2027
|
-
size: scanned.size,
|
|
2028
|
-
mtime: scanned.mtime
|
|
2029
|
-
};
|
|
3133
|
+
return this._scanner.knownFile(relativePath);
|
|
2030
3134
|
}
|
|
2031
3135
|
/**
|
|
2032
3136
|
* Whether the file at `filePath` is already the content `meta` describes.
|
|
@@ -2168,7 +3272,7 @@ ${err.stack}` : String(err);
|
|
|
2168
3272
|
}
|
|
2169
3273
|
const errMsg = error instanceof Error ? error.message : String(error);
|
|
2170
3274
|
console.warn(
|
|
2171
|
-
|
|
3275
|
+
`${this._tag} _fetchTreeRecursively: db.get failed for hash=${hash.slice(0, 8)}…: ${errMsg}`
|
|
2172
3276
|
);
|
|
2173
3277
|
this._writeSyncError(
|
|
2174
3278
|
`fetchTree/db.get(${hash.slice(0, 8)}…)`,
|
|
@@ -2232,7 +3336,10 @@ ${err.stack}` : String(err);
|
|
|
2232
3336
|
*/
|
|
2233
3337
|
async loadFromDb(db, treeKey, rootRef, targetPath, options) {
|
|
2234
3338
|
const fsTree = await this._fetchTreeFromDb(db, treeKey, rootRef);
|
|
2235
|
-
await this.
|
|
3339
|
+
await this._timed(
|
|
3340
|
+
"apply.write",
|
|
3341
|
+
() => this.restore(fsTree, targetPath, options)
|
|
3342
|
+
);
|
|
2236
3343
|
}
|
|
2237
3344
|
/**
|
|
2238
3345
|
* Collects expected file and directory paths for cleanup
|
|
@@ -2266,846 +3373,954 @@ ${err.stack}` : String(err);
|
|
|
2266
3373
|
* @param expectedDirs - Allowed directory paths
|
|
2267
3374
|
* @param expectedFiles - Allowed file paths
|
|
2268
3375
|
* @param preRestore - Files present before the restore (prune candidates)
|
|
3376
|
+
* @param expectedByLowerCase - Expected paths indexed by lower case, so a
|
|
3377
|
+
* file the tree spells with different capitalisation is recognised as the
|
|
3378
|
+
* same file rather than pruned.
|
|
2269
3379
|
*/
|
|
2270
|
-
async _pruneExtraneous(currentDir, expectedDirs, expectedFiles, preRestore) {
|
|
3380
|
+
async _pruneExtraneous(currentDir, expectedDirs, expectedFiles, preRestore, expectedByLowerCase = /* @__PURE__ */ new Map()) {
|
|
2271
3381
|
let entries;
|
|
2272
3382
|
try {
|
|
2273
3383
|
entries = await readdir(currentDir, { withFileTypes: true });
|
|
2274
3384
|
} catch {
|
|
2275
3385
|
return;
|
|
2276
3386
|
}
|
|
2277
|
-
for (const entry of entries) {
|
|
2278
|
-
const fullPath = join(currentDir, entry.name);
|
|
2279
|
-
if (entry.isDirectory()) {
|
|
2280
|
-
await this._pruneExtraneous(
|
|
2281
|
-
fullPath,
|
|
2282
|
-
expectedDirs,
|
|
2283
|
-
expectedFiles,
|
|
2284
|
-
preRestore
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
3387
|
+
for (const entry of entries) {
|
|
3388
|
+
const fullPath = join(currentDir, entry.name);
|
|
3389
|
+
if (entry.isDirectory()) {
|
|
3390
|
+
await this._pruneExtraneous(
|
|
3391
|
+
fullPath,
|
|
3392
|
+
expectedDirs,
|
|
3393
|
+
expectedFiles,
|
|
3394
|
+
preRestore,
|
|
3395
|
+
expectedByLowerCase
|
|
3396
|
+
);
|
|
3397
|
+
if (!expectedDirs.has(fullPath)) {
|
|
3398
|
+
const remaining = await readdir(fullPath);
|
|
3399
|
+
if (remaining.length === 0) {
|
|
3400
|
+
await rm(fullPath, { recursive: true, force: true });
|
|
3401
|
+
}
|
|
3402
|
+
}
|
|
3403
|
+
} else if (!expectedFiles.has(fullPath) && preRestore.has(fullPath)) {
|
|
3404
|
+
if (await this._isSameFileAsExpected(fullPath, expectedByLowerCase)) {
|
|
3405
|
+
this._restoreSkipped++;
|
|
3406
|
+
continue;
|
|
3407
|
+
}
|
|
3408
|
+
await rm(fullPath, { force: true });
|
|
3409
|
+
this._restorePruned++;
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
/**
|
|
3414
|
+
* Builds a map of relativePath → blobId for all files in a tree.
|
|
3415
|
+
* Used to compare trees by content rather than by hash (which includes mtime).
|
|
3416
|
+
* @param tree - Tree structure to extract file content map from
|
|
3417
|
+
*/
|
|
3418
|
+
_getFileContentMap(tree) {
|
|
3419
|
+
const map = /* @__PURE__ */ new Map();
|
|
3420
|
+
for (const [, node] of tree.trees) {
|
|
3421
|
+
const meta = node?.meta;
|
|
3422
|
+
if (meta?.type === "file") {
|
|
3423
|
+
map.set(meta.relativePath, meta.blobId ?? "");
|
|
3424
|
+
} else if (meta?.type === "directory" && meta.relativePath !== ".") {
|
|
3425
|
+
map.set(meta.relativePath, DIR_MARKER);
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
return map;
|
|
3429
|
+
}
|
|
3430
|
+
/**
|
|
3431
|
+
* What joining actually does to the folder.
|
|
3432
|
+
* @param db - The route's database.
|
|
3433
|
+
* @param treeKey - The trees table key.
|
|
3434
|
+
* @param entry - The head this node is joining onto.
|
|
3435
|
+
*/
|
|
3436
|
+
/**
|
|
3437
|
+
* Moves one file out of the way of the state this node is joining onto.
|
|
3438
|
+
*
|
|
3439
|
+
* A method rather than a closure inside the join so that the failure can be
|
|
3440
|
+
* TESTED. A rename that cannot be performed — the source gone between the
|
|
3441
|
+
* scan and the move, the destination occupied by a directory — leaves the
|
|
3442
|
+
* file where it is, and the restore then overwrites it. That loses less than
|
|
3443
|
+
* refusing to join, which is why it is recorded rather than thrown; and a
|
|
3444
|
+
* path that is only ever recorded is a path that needs a test, because
|
|
3445
|
+
* nothing else will ever tell anybody it stopped working.
|
|
3446
|
+
* @param path - The file to move, relative to the root, `/`-separated.
|
|
3447
|
+
* @param name - Where to move it, same form.
|
|
3448
|
+
*/
|
|
3449
|
+
async _setAside(path, name) {
|
|
3450
|
+
const from = join(this._rootPath, ...path.split("/"));
|
|
3451
|
+
const to = join(this._rootPath, ...name.split("/"));
|
|
3452
|
+
await mkdir(dirname(to), { recursive: true });
|
|
3453
|
+
await rename(from, to).catch((err) => {
|
|
3454
|
+
this._writeSyncError(`join/setAside/${path}`, err);
|
|
3455
|
+
});
|
|
3456
|
+
}
|
|
3457
|
+
// ...........................................................................
|
|
3458
|
+
// THE SYNC — the chain is the only order.
|
|
3459
|
+
//
|
|
3460
|
+
// One state: the chain entry this node stands on (`_ownHead`). The send
|
|
3461
|
+
// side authors an edit when the folder moves past it and announces it; the
|
|
3462
|
+
// receive side relates every head that arrives to it and applies, announces
|
|
3463
|
+
// or merges (`fs-receive.ts`). Both run under one lock, so an apply never
|
|
3464
|
+
// interleaves with an authoring. Nothing compares two machines' clocks.
|
|
3465
|
+
/** The chain entry this node stands on, persisted across restarts. */
|
|
3466
|
+
_ownHead;
|
|
3467
|
+
/** The own head's tree, `path → blob`: what the folder is diffed against. */
|
|
3468
|
+
_ownContent = /* @__PURE__ */ new Map();
|
|
3469
|
+
/** Paths the watcher saw deleted since the own head was authored. */
|
|
3470
|
+
_watched = /* @__PURE__ */ new Set();
|
|
3471
|
+
/** Every chain entry's stamp, as this node learned it. */
|
|
3472
|
+
_stamps;
|
|
3473
|
+
/** The route this agent syncs, once a sync started. */
|
|
3474
|
+
_route;
|
|
3475
|
+
/** The newest head heard and not yet received. */
|
|
3476
|
+
_heard;
|
|
3477
|
+
/** Stamps heard, recorded in arrival order before anything decides. */
|
|
3478
|
+
_stamping = Promise.resolve();
|
|
3479
|
+
/** The lock the send and receive sides share. */
|
|
3480
|
+
_lock = Promise.resolve();
|
|
3481
|
+
/** The receive loop, while it runs. */
|
|
3482
|
+
_receiving;
|
|
3483
|
+
/** A joining folder's wait for the network's head, while it lasts. */
|
|
3484
|
+
_joinWait;
|
|
3485
|
+
/** Authors again shortly, once the watcher has caught up. */
|
|
3486
|
+
_authorSoon;
|
|
3487
|
+
/** The merge that waited for a stamp last, so a second wait is told. */
|
|
3488
|
+
_deferral;
|
|
3489
|
+
/** The last time this node announced its head to learn its stamp. */
|
|
3490
|
+
_stampAsk;
|
|
3491
|
+
/** What the last state the hub announced made this node do. */
|
|
3492
|
+
_hubStatus = null;
|
|
3493
|
+
/** How many receive sides were started; the newest one owns the status. */
|
|
3494
|
+
_receivers = 0;
|
|
3495
|
+
/**
|
|
3496
|
+
* What an apply that stopped partway — a locked file, an unreachable blob —
|
|
3497
|
+
* had already written, path → blob. Not this node's work: authoring does not
|
|
3498
|
+
* claim it, and the next apply recognises it. Cleared when the own head
|
|
3499
|
+
* moves.
|
|
3500
|
+
*/
|
|
3501
|
+
_partiallyApplied = /* @__PURE__ */ new Map();
|
|
3502
|
+
/** The chain entry this node stands on, if any. */
|
|
3503
|
+
get ownHead() {
|
|
3504
|
+
return this._ownHead;
|
|
3505
|
+
}
|
|
3506
|
+
/** When this agent last finished something that may write to the folder. */
|
|
3507
|
+
_wroteAt = 0;
|
|
3508
|
+
/**
|
|
3509
|
+
* Runs `work`, which may write to the folder, and notes when it ended —
|
|
3510
|
+
* inside the lock, so nothing queued behind it can read an older note.
|
|
3511
|
+
* @param work - A receive or a join.
|
|
3512
|
+
* @returns What `work` returned.
|
|
3513
|
+
*/
|
|
3514
|
+
async _writing(work) {
|
|
3515
|
+
try {
|
|
3516
|
+
return await work();
|
|
3517
|
+
} finally {
|
|
3518
|
+
this._wroteAt = Date.now();
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
/**
|
|
3522
|
+
* The folder for authoring a local change: a pass that began after this
|
|
3523
|
+
* agent last wrote to it.
|
|
3524
|
+
*
|
|
3525
|
+
* A pass that overlapped an apply may have read the apply half-done, and
|
|
3526
|
+
* authoring from it announced the version before the apply — a revert
|
|
3527
|
+
* (F9). After a write, then, the folder is scanned afresh. Without one, the
|
|
3528
|
+
* watcher's last pass already is such a pass, and scanning again only looks
|
|
3529
|
+
* at a file mid-copy one more time: a copy that stalls hashed a truncated
|
|
3530
|
+
* version for every extra look, two to five times as many as before.
|
|
3531
|
+
* @returns The tree.
|
|
3532
|
+
*/
|
|
3533
|
+
async _passAfterOwnWrites() {
|
|
3534
|
+
const last = this._scanner.tree;
|
|
3535
|
+
return last && this._scanner.treeStartedAt > this._wroteAt ? last : this._scanner.scanFresh();
|
|
3536
|
+
}
|
|
3537
|
+
/**
|
|
3538
|
+
* Runs `work` alone: the send and receive sides never interleave.
|
|
3539
|
+
* @param work - What to run.
|
|
3540
|
+
* @returns What `work` returned.
|
|
3541
|
+
*/
|
|
3542
|
+
_exclusive(work) {
|
|
3543
|
+
const run = this._lock.then(work, work);
|
|
3544
|
+
this._lock = run.then(
|
|
3545
|
+
() => void 0,
|
|
3546
|
+
() => void 0
|
|
3547
|
+
);
|
|
3548
|
+
return run;
|
|
3549
|
+
}
|
|
3550
|
+
/**
|
|
3551
|
+
* Opens the chain and the stamp store for a route, once.
|
|
3552
|
+
* @param db - The route's database.
|
|
3553
|
+
* @param treeKey - The trees table key.
|
|
3554
|
+
*/
|
|
3555
|
+
async _ensureChain(db, treeKey) {
|
|
3556
|
+
if (this._chain) return;
|
|
3557
|
+
const chain = new FsEditChain(db, treeKey);
|
|
3558
|
+
await chain.init();
|
|
3559
|
+
const stamps = new FsStamps(
|
|
3560
|
+
db,
|
|
3561
|
+
treeKey,
|
|
3562
|
+
async (entry) => (await chain.entry(entry).catch(() => void 0))?.previous
|
|
3563
|
+
);
|
|
3564
|
+
await stamps.init();
|
|
3565
|
+
this._chain = chain;
|
|
3566
|
+
this._stamps = stamps;
|
|
3567
|
+
}
|
|
3568
|
+
// ...........................................................................
|
|
3569
|
+
// The own head
|
|
3570
|
+
/**
|
|
3571
|
+
* The head `.fsagent-state.json` names, if it names one.
|
|
3572
|
+
* @returns The head, or `undefined`.
|
|
3573
|
+
*/
|
|
3574
|
+
_persistedHead() {
|
|
3575
|
+
try {
|
|
3576
|
+
const state = JSON.parse(
|
|
3577
|
+
readFileSync(join(this._rootPath, AGENT_STATE_FILE), "utf-8")
|
|
3578
|
+
);
|
|
3579
|
+
return typeof state?.ownHead === "string" && state.ownHead !== "" ? state.ownHead : void 0;
|
|
3580
|
+
} catch {
|
|
3581
|
+
return void 0;
|
|
3582
|
+
}
|
|
3583
|
+
}
|
|
3584
|
+
/**
|
|
3585
|
+
* Makes `head` this node's head, and remembers it across a restart.
|
|
3586
|
+
* @param head - The chain entry.
|
|
3587
|
+
* @param content - The tree it names, `path → blob`.
|
|
3588
|
+
*/
|
|
3589
|
+
_setOwn(head, content) {
|
|
3590
|
+
this._ownHead = head;
|
|
3591
|
+
this._ownContent = content;
|
|
3592
|
+
this._partiallyApplied.clear();
|
|
3593
|
+
this._writeState();
|
|
3594
|
+
}
|
|
3595
|
+
/** Writes {@link AGENT_STATE_FILE}: the own head and the stamp epochs. */
|
|
3596
|
+
_writeState() {
|
|
3597
|
+
const stampEpochs = this._stamps.epochs;
|
|
3598
|
+
this._writtenEpochs = JSON.stringify(stampEpochs);
|
|
3599
|
+
try {
|
|
3600
|
+
writeFileSync(
|
|
3601
|
+
join(this._rootPath, AGENT_STATE_FILE),
|
|
3602
|
+
JSON.stringify({ ownHead: this._ownHead, stampEpochs }),
|
|
3603
|
+
"utf-8"
|
|
3604
|
+
);
|
|
3605
|
+
} catch (err) {
|
|
3606
|
+
this._writeSyncError("state/write", err);
|
|
3607
|
+
}
|
|
3608
|
+
}
|
|
3609
|
+
/** The stamp epochs the state file holds, as written. */
|
|
3610
|
+
_writtenEpochs = "{}";
|
|
3611
|
+
/**
|
|
3612
|
+
* The tree a chain entry names.
|
|
3613
|
+
* @param head - The chain entry.
|
|
3614
|
+
* @returns Its tree ref and tree, or `undefined` when either cannot be read.
|
|
3615
|
+
*/
|
|
3616
|
+
async _treeOf(head) {
|
|
3617
|
+
const { db, treeKey } = this._route;
|
|
3618
|
+
const entry = await this._chain?.entry(head).catch(() => void 0);
|
|
3619
|
+
if (!entry) return void 0;
|
|
3620
|
+
const tree = await this._fetchTreeFromDb(db, treeKey, entry.treeRef).catch(
|
|
3621
|
+
() => void 0
|
|
3622
|
+
);
|
|
3623
|
+
return tree ? { treeRef: entry.treeRef, tree } : void 0;
|
|
3624
|
+
}
|
|
3625
|
+
/** Announces the own head, with its stamp when this node knows it. */
|
|
3626
|
+
_announceOwn() {
|
|
3627
|
+
const head = this._ownHead;
|
|
3628
|
+
const { connector } = this._route;
|
|
3629
|
+
connector.invalidateSent?.(head);
|
|
3630
|
+
const started = Date.now();
|
|
3631
|
+
try {
|
|
3632
|
+
connector.send(head, { stamp: this._stamps?.get(head) });
|
|
3633
|
+
} catch (err) {
|
|
3634
|
+
this._writeSyncError("announce", err);
|
|
3635
|
+
} finally {
|
|
3636
|
+
this._stageMs["push.announce"] = Date.now() - started;
|
|
3637
|
+
}
|
|
3638
|
+
}
|
|
3639
|
+
/**
|
|
3640
|
+
* Announces the own head so the hub stamps it — at once the first time,
|
|
3641
|
+
* then less and less often while the stamp does not come.
|
|
3642
|
+
*
|
|
3643
|
+
* Bounded because nothing else bounds it: on a hub that does not stamp,
|
|
3644
|
+
* three nodes deferring the same conflict answered each other's
|
|
3645
|
+
* announcements with announcements, 245 000 merge attempts in one test.
|
|
3646
|
+
* @param head - The own head.
|
|
3647
|
+
*/
|
|
3648
|
+
_askForStamp(head) {
|
|
3649
|
+
const now = Date.now();
|
|
3650
|
+
const ask = this._stampAsk;
|
|
3651
|
+
if (ask?.head === head && now - ask.at < ask.waitMs) return;
|
|
3652
|
+
const waitMs = ask?.head === head ? Math.min(ask.waitMs * 2, STAMP_ASK_MAX_MS) : STAMP_ASK_MIN_MS;
|
|
3653
|
+
this._stampAsk = { head, at: now, waitMs };
|
|
3654
|
+
this._announceOwn();
|
|
3655
|
+
}
|
|
3656
|
+
// ...........................................................................
|
|
3657
|
+
// Sending
|
|
3658
|
+
/**
|
|
3659
|
+
* Authors an edit for the folder as `tree` describes it, if it moved past
|
|
3660
|
+
* the own head and the edit is honest — see `planAuthoring`.
|
|
3661
|
+
* @param tree - The folder, as just scanned.
|
|
3662
|
+
*/
|
|
3663
|
+
async _author(tree) {
|
|
3664
|
+
if (this._joinWait || !this._route || !this._chain) return;
|
|
3665
|
+
const folder = this._getFileContentMap(tree);
|
|
3666
|
+
if (this._ownHead === void 0) {
|
|
3667
|
+
if (folder.size === 0) return;
|
|
3668
|
+
const treeRef2 = await this._storeTree(tree);
|
|
3669
|
+
const root = await this._chain.append({ treeRef: treeRef2, previous: [] });
|
|
3670
|
+
this._setOwn(root.head, folder);
|
|
3671
|
+
this._watched.clear();
|
|
3672
|
+
this._announceOwn();
|
|
3673
|
+
return;
|
|
3674
|
+
}
|
|
3675
|
+
const plan = planAuthoring({
|
|
3676
|
+
folder,
|
|
3677
|
+
// What a cut-short apply wrote counts as unchanged: it is not this
|
|
3678
|
+
// node's work, and claiming it would make it the author.
|
|
3679
|
+
head: this._partiallyApplied.size === 0 ? this._ownContent : new Map([...this._ownContent, ...this._partiallyApplied]),
|
|
3680
|
+
watched: this._watched,
|
|
3681
|
+
minFiles: MASS_DELETE_MIN_FILES,
|
|
3682
|
+
maxRatio: MASS_DELETE_MAX_RATIO,
|
|
3683
|
+
allGoneMinFiles: ALL_GONE_MIN_FILES
|
|
3684
|
+
});
|
|
3685
|
+
if (plan.kind === "unchanged") return;
|
|
3686
|
+
if (plan.kind === "refused") {
|
|
3687
|
+
this._refuseDeletion(
|
|
3688
|
+
"author",
|
|
3689
|
+
plan.disappeared.length,
|
|
3690
|
+
plan.held,
|
|
3691
|
+
plan.disappeared,
|
|
3692
|
+
"The watcher did not see them go, so the folder keeps its last recorded state until a person decides."
|
|
3693
|
+
);
|
|
3694
|
+
return;
|
|
3695
|
+
}
|
|
3696
|
+
for (const path of plan.removed) {
|
|
3697
|
+
if (await lstat(join(this._rootPath, ...path.split("/"))).catch(() => void 0)) {
|
|
3698
|
+
this._authorSoon?.();
|
|
3699
|
+
return;
|
|
2298
3700
|
}
|
|
2299
3701
|
}
|
|
3702
|
+
const treeRef = await this._storeTree(tree);
|
|
3703
|
+
const entry = await this._chain.append({
|
|
3704
|
+
treeRef,
|
|
3705
|
+
changed: plan.changed,
|
|
3706
|
+
removed: plan.removed,
|
|
3707
|
+
previous: [this._ownHead]
|
|
3708
|
+
});
|
|
3709
|
+
this._setOwn(entry.head, folder);
|
|
3710
|
+
this._watched.clear();
|
|
3711
|
+
this._announceOwn();
|
|
2300
3712
|
}
|
|
2301
3713
|
/**
|
|
2302
|
-
*
|
|
2303
|
-
*
|
|
2304
|
-
* @
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
3714
|
+
* Stores a tree and its blobs for the route.
|
|
3715
|
+
* @param tree - The tree.
|
|
3716
|
+
* @returns Its ref.
|
|
3717
|
+
*/
|
|
3718
|
+
async _storeTree(tree) {
|
|
3719
|
+
const { db, treeKey } = this._route;
|
|
3720
|
+
return FsAgent._withTimeout(
|
|
3721
|
+
new FsDbAdapter(db, treeKey).storeFsTree(tree, { skipNotification: true }),
|
|
3722
|
+
this._timeouts.fetchTree,
|
|
3723
|
+
`storeFsTree(${treeKey})`
|
|
3724
|
+
);
|
|
3725
|
+
}
|
|
3726
|
+
/**
|
|
3727
|
+
* Watches the folder and keeps the chain in step with it.
|
|
3728
|
+
*
|
|
3729
|
+
* On start, a folder with a head continues it; a folder without one joins
|
|
3730
|
+
* the network (`planJoin`) or, when nobody answers, becomes its origin.
|
|
3731
|
+
* @param db - The route's database.
|
|
3732
|
+
* @param connector - The transport.
|
|
3733
|
+
* @param treeKey - The trees table key.
|
|
3734
|
+
* @returns Stops watching.
|
|
3735
|
+
*/
|
|
3736
|
+
async syncToDb(db, connector, treeKey) {
|
|
3737
|
+
this._route = { db, connector, treeKey };
|
|
3738
|
+
await this._ensureChain(db, treeKey);
|
|
3739
|
+
const initial = await FsAgent._withTimeout(
|
|
2322
3740
|
this.extract(),
|
|
2323
3741
|
this._timeouts.extract,
|
|
2324
3742
|
`syncToDb → initial extract(${treeKey})`
|
|
2325
3743
|
);
|
|
2326
|
-
const
|
|
2327
|
-
const
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
this._timeouts.fetchTree,
|
|
2337
|
-
`syncToDb → initial storeFsTree(${treeKey})`
|
|
2338
|
-
);
|
|
2339
|
-
if (isSilentJoiner) {
|
|
2340
|
-
console.warn(
|
|
2341
|
-
`[FsAgent] ${this._rootPath} is empty and has no remembered state — joining quietly rather than announcing emptiness.`
|
|
2342
|
-
);
|
|
2343
|
-
this._currentRef = initialRef;
|
|
2344
|
-
this._persistCurrentRef(initialRef);
|
|
2345
|
-
this._lastSentContentKey = this._contentKeyFromTree(initialTree);
|
|
2346
|
-
this._rememberAnnounced(initialTree);
|
|
2347
|
-
}
|
|
2348
|
-
if (initialRef && !isSilentJoiner) {
|
|
2349
|
-
this._lastSentRef = initialRef;
|
|
2350
|
-
this._lastPushedRef = initialRef;
|
|
2351
|
-
this._currentRef = initialRef;
|
|
2352
|
-
this._persistCurrentRef(initialRef);
|
|
2353
|
-
this._lastSentContentKey = this._contentKeyFromTree(initialTree);
|
|
2354
|
-
this._rememberAnnounced(initialTree);
|
|
2355
|
-
await this._sendRef(
|
|
2356
|
-
connector,
|
|
2357
|
-
initialRef,
|
|
2358
|
-
initialIsNew ? [initialParentRef] : void 0
|
|
2359
|
-
);
|
|
3744
|
+
const persisted = this._persistedHead();
|
|
3745
|
+
const resumed = persisted !== void 0 && await this._treeOf(persisted);
|
|
3746
|
+
if (resumed) {
|
|
3747
|
+
this._setOwn(persisted, this._getFileContentMap(resumed.tree));
|
|
3748
|
+
await this._exclusive(() => this._author(initial));
|
|
3749
|
+
this._announceOwn();
|
|
3750
|
+
} else if (this._joinWaitMs > 0) {
|
|
3751
|
+
this._startJoinWait();
|
|
3752
|
+
} else {
|
|
3753
|
+
await this._exclusive(() => this._author(initial));
|
|
2360
3754
|
}
|
|
2361
|
-
let
|
|
2362
|
-
|
|
2363
|
-
if (!this._rescanDeferred) return;
|
|
2364
|
-
this._rescanDeferred = false;
|
|
2365
|
-
debouncedSync({ type: "safety-rescan", path: "." });
|
|
2366
|
-
};
|
|
2367
|
-
const debouncedSync = (change) => {
|
|
3755
|
+
let debounce = null;
|
|
3756
|
+
const onChange = (change) => {
|
|
2368
3757
|
if (change?.type === "deleted" && change.path !== ".") {
|
|
2369
|
-
this.
|
|
2370
|
-
}
|
|
2371
|
-
if (change?.type === "safety-rescan" && this._remoteApplyInFlight) {
|
|
2372
|
-
this._rescanDeferred = true;
|
|
2373
|
-
return;
|
|
3758
|
+
this._watched.add(change.path);
|
|
2374
3759
|
}
|
|
2375
|
-
if (
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
const contentKey = this._contentKeyFromTree(tree);
|
|
2382
|
-
if (contentKey === this._lastSentContentKey) {
|
|
2383
|
-
return;
|
|
2384
|
-
}
|
|
2385
|
-
const dbAdapter = new FsDbAdapter(db, treeKey);
|
|
2386
|
-
const head = this._currentRef;
|
|
2387
|
-
const parentRef = head !== void 0 && head === tree.rootHash ? this._lastAppliedRef ?? head : head;
|
|
2388
|
-
const previous = await this._ancestryPrevious(
|
|
2389
|
-
db,
|
|
2390
|
-
treeKey,
|
|
2391
|
-
parentRef ? [parentRef] : void 0
|
|
2392
|
-
);
|
|
2393
|
-
const ref = await FsAgent._withRetry(
|
|
2394
|
-
() => FsAgent._withTimeout(
|
|
2395
|
-
// skipNotification, because THIS AGENT broadcasts the ref
|
|
2396
|
-
// itself a few lines below, with the ancestry attached.
|
|
2397
|
-
//
|
|
2398
|
-
// Letting the insert notify sends the ref twice, and the
|
|
2399
|
-
// first copy is the wrong one: the connector attaches
|
|
2400
|
-
// whatever predecessors it currently holds, and this push has
|
|
2401
|
-
// not set its own yet — so the ref goes out carrying the
|
|
2402
|
-
// PREVIOUS push's parent. `_sendRef` then sets the right
|
|
2403
|
-
// ancestry and sends again, and every receiver drops that
|
|
2404
|
-
// second copy as already-received.
|
|
2405
|
-
//
|
|
2406
|
-
// Measured on the lab, sender against receivers:
|
|
2407
|
-
//
|
|
2408
|
-
// sent 6guj63Ox parent yNAJN-wC | seen parent CtAgdd1w
|
|
2409
|
-
// sent UBl35ZQQ parent 6guj63Ox | seen parent yNAJN-wC
|
|
2410
|
-
//
|
|
2411
|
-
// Every push arriving one parent behind. Harmless while
|
|
2412
|
-
// nothing read the ancestry; now that a receiver prunes only
|
|
2413
|
-
// for a sender that names a state it is in, it means a
|
|
2414
|
-
// correctly-formed deletion is refused by everyone — which is
|
|
2415
|
-
// exactly what the large-folder recipe has been reporting.
|
|
2416
|
-
//
|
|
2417
|
-
// The doubled `[sync:out]` line in every log was this, in
|
|
2418
|
-
// plain sight, for the whole investigation.
|
|
2419
|
-
dbAdapter.storeFsTree(tree, {
|
|
2420
|
-
...options,
|
|
2421
|
-
previous,
|
|
2422
|
-
skipNotification: true
|
|
2423
|
-
}),
|
|
2424
|
-
this._timeouts.fetchTree,
|
|
2425
|
-
`syncToDb → storeFsTree(${treeKey})`
|
|
2426
|
-
),
|
|
2427
|
-
3,
|
|
2428
|
-
200,
|
|
2429
|
-
`syncToDb storeFsTree(${treeKey})`
|
|
2430
|
-
);
|
|
2431
|
-
this._currentRef = ref;
|
|
2432
|
-
this._persistCurrentRef(ref);
|
|
2433
|
-
if (ref === this._lastSentRef) {
|
|
2434
|
-
return;
|
|
2435
|
-
}
|
|
2436
|
-
this._lastSentRef = ref;
|
|
2437
|
-
this._lastPushedRef = ref;
|
|
2438
|
-
this._lastSentContentKey = contentKey;
|
|
2439
|
-
this._rememberAnnounced(tree);
|
|
2440
|
-
if (parentRef && parentRef !== ref) {
|
|
2441
|
-
connector.invalidateReceived(parentRef);
|
|
2442
|
-
}
|
|
2443
|
-
if (ref) {
|
|
2444
|
-
console.log(
|
|
2445
|
-
`[FsAgent] pushing ref=${ref.slice(0, 8)}… parent=${parentRef?.slice(0, 8) ?? "none"} files=${this._getFileContentMap(tree).size}`
|
|
2446
|
-
);
|
|
2447
|
-
await this._sendRef(
|
|
2448
|
-
connector,
|
|
2449
|
-
ref,
|
|
2450
|
-
parentRef ? [parentRef] : void 0
|
|
2451
|
-
);
|
|
2452
|
-
}
|
|
2453
|
-
} catch (err) {
|
|
2454
|
-
console.error("[FsAgent] syncToDb failed:", err);
|
|
2455
|
-
this._writeSyncError("syncToDb", err);
|
|
2456
|
-
}
|
|
2457
|
-
}
|
|
3760
|
+
if (debounce) clearTimeout(debounce);
|
|
3761
|
+
debounce = setTimeout(() => {
|
|
3762
|
+
debounce = null;
|
|
3763
|
+
void this._exclusive(
|
|
3764
|
+
async () => this._author(await this._passAfterOwnWrites())
|
|
3765
|
+
).catch((err) => this._writeSyncError("syncToDb", err));
|
|
2458
3766
|
}, this._timeouts.debounceMs);
|
|
2459
3767
|
};
|
|
2460
|
-
this._scanner.onChange(
|
|
3768
|
+
this._scanner.onChange(onChange);
|
|
3769
|
+
this._authorSoon = () => onChange();
|
|
2461
3770
|
await this._ensureWatching();
|
|
2462
3771
|
return () => {
|
|
2463
|
-
|
|
2464
|
-
|
|
3772
|
+
this._authorSoon = void 0;
|
|
3773
|
+
if (debounce) clearTimeout(debounce);
|
|
3774
|
+
this._scanner.offChange(onChange);
|
|
2465
3775
|
this._scanner.stopWatch();
|
|
2466
3776
|
};
|
|
2467
3777
|
}
|
|
3778
|
+
// ...........................................................................
|
|
3779
|
+
// Joining
|
|
2468
3780
|
/**
|
|
2469
|
-
*
|
|
2470
|
-
*
|
|
2471
|
-
* map each shared parent ref to *this* db's local timeId(s). Returns undefined
|
|
2472
|
-
* when ancestry tracking is off (default) or no parent is known — in which
|
|
2473
|
-
* case the store behaves exactly as before.
|
|
2474
|
-
* @param db - Database instance
|
|
2475
|
-
* @param treeKey - Tree table key
|
|
2476
|
-
* @param parentRefs - Parent content refs (local head, or received predecessors)
|
|
3781
|
+
* Waits up to `joinWaitMs` for the network's head before this folder says
|
|
3782
|
+
* anything about itself.
|
|
2477
3783
|
*/
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
/**
|
|
2489
|
-
* Classifies an incoming revision relative to our current head using the
|
|
2490
|
-
* local InsertHistory DAG (keyed on shared content refs):
|
|
2491
|
-
* - `behind` → incoming descends from our head → fast-forward (restore).
|
|
2492
|
-
* - `ahead` → our head descends from incoming (e.g. a reconnect bootstrap
|
|
2493
|
-
* re-sending an older ancestor) → ignore; we are newer.
|
|
2494
|
-
* - `diverged` → siblings produced by concurrent edits → resolve the fork.
|
|
2495
|
-
* @param db - Database instance
|
|
2496
|
-
* @param treeKey - Tree table key
|
|
2497
|
-
* @param currentRef - Our current head's content ref
|
|
2498
|
-
* @param incomingRef - The incoming revision's content ref
|
|
2499
|
-
* @param incomingPredecessorRefs - The incoming revision's predecessor refs
|
|
2500
|
-
*/
|
|
2501
|
-
async _ancestryRelation(db, treeKey, currentRef, incomingRef, incomingPredecessorRefs) {
|
|
2502
|
-
const dump = await db.getInsertHistory(treeKey);
|
|
2503
|
-
const rows = dump[`${treeKey}InsertHistory`]?._data ?? [];
|
|
2504
|
-
const refKey = `${treeKey}Ref`;
|
|
2505
|
-
const refOfTimeId = /* @__PURE__ */ new Map();
|
|
2506
|
-
for (const r of rows) {
|
|
2507
|
-
refOfTimeId.set(r.timeId, r[refKey]);
|
|
2508
|
-
}
|
|
2509
|
-
const prevRefsOf = /* @__PURE__ */ new Map();
|
|
2510
|
-
for (const r of rows) {
|
|
2511
|
-
const prev = (r.previous ?? []).map((t) => refOfTimeId.get(t)).filter((x) => x !== void 0);
|
|
2512
|
-
prevRefsOf.set(r[refKey], prev);
|
|
2513
|
-
}
|
|
2514
|
-
const ancestorsOf = (startRefs) => {
|
|
2515
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2516
|
-
const stack = [...startRefs];
|
|
2517
|
-
while (stack.length > 0) {
|
|
2518
|
-
const ref = stack.pop();
|
|
2519
|
-
if (seen.has(ref)) {
|
|
2520
|
-
continue;
|
|
2521
|
-
}
|
|
2522
|
-
seen.add(ref);
|
|
2523
|
-
for (const p of prevRefsOf.get(ref) ?? []) {
|
|
2524
|
-
stack.push(p);
|
|
2525
|
-
}
|
|
3784
|
+
_startJoinWait() {
|
|
3785
|
+
const timer = setTimeout(() => this._joinWait?.done(void 0), this._joinWaitMs);
|
|
3786
|
+
timer.unref?.();
|
|
3787
|
+
this._joinWait = {
|
|
3788
|
+
timer,
|
|
3789
|
+
done: (head) => {
|
|
3790
|
+
this._endJoinWait();
|
|
3791
|
+
void this._exclusive(() => this._writing(() => this._join(head))).catch(
|
|
3792
|
+
(err) => this._writeSyncError("join", err)
|
|
3793
|
+
);
|
|
2526
3794
|
}
|
|
2527
|
-
return seen;
|
|
2528
3795
|
};
|
|
2529
|
-
|
|
2530
|
-
|
|
3796
|
+
}
|
|
3797
|
+
/** Ends a join wait without acting on it. */
|
|
3798
|
+
_endJoinWait() {
|
|
3799
|
+
if (this._joinWait) clearTimeout(this._joinWait.timer);
|
|
3800
|
+
this._joinWait = void 0;
|
|
3801
|
+
}
|
|
3802
|
+
/**
|
|
3803
|
+
* Joins the network's head, or — when none came — makes this folder the
|
|
3804
|
+
* origin of its history.
|
|
3805
|
+
*
|
|
3806
|
+
* **The chain applies first; the filesystem only then.** What the folder
|
|
3807
|
+
* holds beyond the head is judged by the history: a path the history never
|
|
3808
|
+
* named is new work and is authored on top of the head; a path it removed is
|
|
3809
|
+
* a stale copy and is set aside, not announced; a path both hold with
|
|
3810
|
+
* different bytes keeps the head's version and the local one as a copy.
|
|
3811
|
+
* @param head - The network's head, or `undefined`.
|
|
3812
|
+
*/
|
|
3813
|
+
async _join(head) {
|
|
3814
|
+
const folderTree = await this._scanner.scanFresh();
|
|
3815
|
+
const joined = head === void 0 ? void 0 : await this._treeOf(head);
|
|
3816
|
+
if (head === void 0 || !joined) {
|
|
3817
|
+
await this._author(folderTree);
|
|
3818
|
+
return;
|
|
3819
|
+
}
|
|
3820
|
+
const headContent = this._getFileContentMap(joined.tree);
|
|
3821
|
+
const folder = this._getFileContentMap(folderTree);
|
|
3822
|
+
const walk = await this._chain.collectRemovals(head, void 0).catch(() => void 0);
|
|
3823
|
+
const plan = planJoin({
|
|
3824
|
+
head: headContent,
|
|
3825
|
+
folder,
|
|
3826
|
+
removedEver: new Set(walk?.complete ? walk.removed : [])
|
|
3827
|
+
});
|
|
3828
|
+
const taken = /* @__PURE__ */ new Set([...folder.keys(), ...headContent.keys()]);
|
|
3829
|
+
for (const path of plan.recover) {
|
|
3830
|
+
await this._setAside(path, `${RECOVERED_DIR}/${recoveredName(path, taken)}`);
|
|
2531
3831
|
}
|
|
2532
|
-
|
|
2533
|
-
|
|
3832
|
+
for (const path of plan.conflict) {
|
|
3833
|
+
await this._setAside(
|
|
3834
|
+
path,
|
|
3835
|
+
joinCopyName(path, Date.now(), taken)
|
|
3836
|
+
);
|
|
2534
3837
|
}
|
|
2535
|
-
|
|
3838
|
+
this._signalJoinOutcome(plan.recover, plan.conflict);
|
|
3839
|
+
await this.restore(joined.tree, void 0, { cleanTarget: false });
|
|
3840
|
+
this._setOwn(head, headContent);
|
|
3841
|
+
await this._author(await this._scanner.scanFresh());
|
|
3842
|
+
this._announceOwn();
|
|
2536
3843
|
}
|
|
3844
|
+
// ...........................................................................
|
|
3845
|
+
// Receiving
|
|
2537
3846
|
/**
|
|
2538
|
-
*
|
|
2539
|
-
*
|
|
2540
|
-
*
|
|
2541
|
-
*
|
|
2542
|
-
* materialised to disk and broadcast.
|
|
2543
|
-
* @param db - Database instance
|
|
2544
|
-
* @param treeKey - Tree table key
|
|
2545
|
-
* @param incomingRef - The incoming revision's content ref
|
|
2546
|
-
* @param incomingTree - The fetched incoming tree
|
|
2547
|
-
* @param predecessorRefs - The incoming revision's predecessor content refs
|
|
3847
|
+
* Hears a head — from an announcement, a bootstrap or a state beacon.
|
|
3848
|
+
* @param head - The head.
|
|
3849
|
+
* @param stamp - The stamp it arrived with, if any.
|
|
3850
|
+
* @param fromHub - Whether the hub said it: what `antiEntropyStatus` reports.
|
|
2548
3851
|
*/
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
);
|
|
2565
|
-
await resolver.resolve({
|
|
2566
|
-
table: treeKey,
|
|
2567
|
-
type: "dagBranch",
|
|
2568
|
-
detectedAt: Date.now(),
|
|
2569
|
-
branches: [...headTimeIds, ...incomingTimeIds]
|
|
2570
|
-
});
|
|
3852
|
+
_hear(head, stamp, fromHub = false) {
|
|
3853
|
+
if (typeof head !== "string" || head === "") return;
|
|
3854
|
+
this._recordStamp(head, stamp);
|
|
3855
|
+
if (fromHub) this._hubHead = head;
|
|
3856
|
+
if (this._joinWait) {
|
|
3857
|
+
this._joinWait.done(head);
|
|
3858
|
+
return;
|
|
3859
|
+
}
|
|
3860
|
+
if (this._ownHead === void 0) {
|
|
3861
|
+
void this._exclusive(() => this._writing(() => this._join(head))).catch(
|
|
3862
|
+
(err) => this._writeSyncError("join", err)
|
|
3863
|
+
);
|
|
3864
|
+
return;
|
|
3865
|
+
}
|
|
3866
|
+
this._heard = head;
|
|
3867
|
+
this._drain();
|
|
2571
3868
|
}
|
|
3869
|
+
/** The head the hub said last. */
|
|
3870
|
+
_hubHead;
|
|
2572
3871
|
/**
|
|
2573
|
-
*
|
|
2574
|
-
*
|
|
2575
|
-
* @param
|
|
3872
|
+
* Records the stamp a head arrived with, in arrival order.
|
|
3873
|
+
* @param head - The head.
|
|
3874
|
+
* @param stamp - Its stamp, if any.
|
|
2576
3875
|
*/
|
|
2577
|
-
|
|
2578
|
-
const
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
map.set(meta.relativePath, "<dir>");
|
|
3876
|
+
_recordStamp(head, stamp) {
|
|
3877
|
+
const stamps = this._stamps;
|
|
3878
|
+
if (stamp === void 0 || !stamps) return;
|
|
3879
|
+
this._stamping = this._stamping.then(async () => {
|
|
3880
|
+
await stamps.heard(head, stamp);
|
|
3881
|
+
if (JSON.stringify(stamps.epochs) !== this._writtenEpochs) {
|
|
3882
|
+
this._writeState();
|
|
2585
3883
|
}
|
|
2586
|
-
}
|
|
2587
|
-
|
|
3884
|
+
}).catch((err) => this._writeSyncError("stamps/heard", err));
|
|
3885
|
+
}
|
|
3886
|
+
/** Receives the newest head heard, one at a time, until none is left. */
|
|
3887
|
+
_drain() {
|
|
3888
|
+
if (this._receiving) return;
|
|
3889
|
+
this._receiving = (async () => {
|
|
3890
|
+
while (this._heard !== void 0) {
|
|
3891
|
+
const head = this._heard;
|
|
3892
|
+
this._heard = void 0;
|
|
3893
|
+
await this._stamping;
|
|
3894
|
+
const own = this._ownHead;
|
|
3895
|
+
const outcome = await this._exclusive(
|
|
3896
|
+
() => this._writing(() => receive(head, this._receiveDeps()))
|
|
3897
|
+
).catch((err) => {
|
|
3898
|
+
this._writeSyncError("receive", err);
|
|
3899
|
+
return "blocked";
|
|
3900
|
+
});
|
|
3901
|
+
if (outcome !== "in-sync") {
|
|
3902
|
+
console.log(
|
|
3903
|
+
`${this._tag} received ${head.slice(0, 8)}… on ${own?.slice(0, 8)}… — ${outcome}`
|
|
3904
|
+
);
|
|
3905
|
+
}
|
|
3906
|
+
this._noteOutcome(head, outcome);
|
|
3907
|
+
}
|
|
3908
|
+
})().finally(() => {
|
|
3909
|
+
this._receiving = void 0;
|
|
3910
|
+
});
|
|
2588
3911
|
}
|
|
2589
3912
|
/**
|
|
2590
|
-
*
|
|
2591
|
-
*
|
|
2592
|
-
*
|
|
2593
|
-
* @param
|
|
3913
|
+
* Keeps `antiEntropyStatus` true to what the last head from the hub made
|
|
3914
|
+
* this node do.
|
|
3915
|
+
* @param head - The head that was received.
|
|
3916
|
+
* @param outcome - What was done.
|
|
2594
3917
|
*/
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
3918
|
+
_noteOutcome(head, outcome) {
|
|
3919
|
+
if (head !== this._hubHead) return;
|
|
3920
|
+
const now = Date.now();
|
|
3921
|
+
const settled = outcome === "in-sync" || this._ownHead === head;
|
|
3922
|
+
const was = this._hubStatus;
|
|
3923
|
+
const acted = outcome !== "in-sync";
|
|
3924
|
+
this._hubStatus = {
|
|
3925
|
+
diverged: !settled,
|
|
3926
|
+
divergedSince: settled ? null : was?.divergedSince ?? now,
|
|
3927
|
+
hubRef: head,
|
|
3928
|
+
localRef: this._ownHead,
|
|
3929
|
+
repairs: (was?.repairs ?? 0) + (acted ? 1 : 0),
|
|
3930
|
+
lastRepair: acted ? {
|
|
3931
|
+
action: REPAIR_ACTION[outcome],
|
|
3932
|
+
at: now,
|
|
3933
|
+
hubRef: head,
|
|
3934
|
+
localRef: this._ownHead,
|
|
3935
|
+
attempt: was?.lastRepair?.hubRef === head ? was.lastRepair.attempt + 1 : 1
|
|
3936
|
+
} : was?.lastRepair ?? null
|
|
3937
|
+
};
|
|
2600
3938
|
}
|
|
2601
3939
|
/**
|
|
2602
|
-
*
|
|
2603
|
-
*
|
|
2604
|
-
*
|
|
2605
|
-
* A tree ref is a pure content hash, so a folder that returns to an earlier
|
|
2606
|
-
* state re-derives that state's exact ref. The connector drops an incoming
|
|
2607
|
-
* ref it has already received, which assumes a state is reached once and
|
|
2608
|
-
* never returned to — false for content-addressed state, and false in the
|
|
2609
|
-
* most ordinary way possible: create a file, then delete it again.
|
|
2610
|
-
*
|
|
2611
|
-
* Retiring the SUPERSEDED ref is what keeps the return trip deliverable.
|
|
2612
|
-
* The ref just adopted stays deduped, so a peer re-advertising the state
|
|
2613
|
-
* this folder is actually in is still suppressed as the echo it is. That
|
|
2614
|
-
* only works if every adopted state passes through here — a state adopted
|
|
2615
|
-
* silently is never retired and blocks its own return for good.
|
|
2616
|
-
* @param connector - Connector whose dedup sets to retire from.
|
|
2617
|
-
* @param treeRef - The ref that now describes this folder.
|
|
3940
|
+
* How often in a row an apply found the folder moved under this node's own
|
|
3941
|
+
* head. Counted per own head, not per incoming one: two heads arriving in
|
|
3942
|
+
* turn must not reset each other's count.
|
|
2618
3943
|
*/
|
|
3944
|
+
_movedAgain;
|
|
2619
3945
|
/**
|
|
2620
|
-
*
|
|
2621
|
-
*
|
|
2622
|
-
*
|
|
2623
|
-
*
|
|
2624
|
-
*
|
|
2625
|
-
* new to push, and nothing moves until an unrelated edit happens somewhere.
|
|
2626
|
-
*
|
|
2627
|
-
* Rate-limited because two nodes can refuse each other — each holding files
|
|
2628
|
-
* the other lacks — and an unthrottled answer to every refusal is a loop.
|
|
2629
|
-
* @param connector - Connector to broadcast on.
|
|
3946
|
+
* Receives a head once more after the folder moved under an apply — the
|
|
3947
|
+
* local work is authored first then, which turns the apply into a merge.
|
|
3948
|
+
* Bounded, so a cache that never catches up cannot loop; the next head the
|
|
3949
|
+
* hub says tries again.
|
|
3950
|
+
* @param head - The head.
|
|
2630
3951
|
*/
|
|
2631
|
-
|
|
2632
|
-
const
|
|
2633
|
-
|
|
2634
|
-
const
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
`[FsAgent] refused an incoming tree — re-announcing ${ref.slice(0, 8)}… so the sender can catch up.`
|
|
2639
|
-
);
|
|
2640
|
-
try {
|
|
2641
|
-
await this._sendRef(connector, ref);
|
|
2642
|
-
} catch (err) {
|
|
2643
|
-
console.warn(`[FsAgent] re-announcement failed: ${String(err)}`);
|
|
2644
|
-
}
|
|
3952
|
+
_receiveAgain(head) {
|
|
3953
|
+
const own = this._ownHead;
|
|
3954
|
+
const was = this._movedAgain;
|
|
3955
|
+
const times = was && was.own === own ? was.times + 1 : 1;
|
|
3956
|
+
this._movedAgain = { own, times };
|
|
3957
|
+
if (times > RECEIVE_AGAIN_MAX) return;
|
|
3958
|
+
this._heard ??= head;
|
|
2645
3959
|
}
|
|
2646
3960
|
/**
|
|
2647
|
-
*
|
|
2648
|
-
*
|
|
2649
|
-
* Deliberately conservative: an empty DIRECTORY counts as content. A user who
|
|
2650
|
-
* creates a folder and puts a directory in it has made a statement about what
|
|
2651
|
-
* should be there, and the silence this gates is only correct for an agent
|
|
2652
|
-
* that has established nothing at all. Being wrong in that direction would
|
|
2653
|
-
* mean a folder that never advertises until something else happens to change.
|
|
2654
|
-
* @param tree - The tree to inspect.
|
|
2655
|
-
* @returns `true` when the tree carries no entries at all.
|
|
3961
|
+
* What `receive` needs from this agent.
|
|
3962
|
+
* @returns The agent's side of a receive.
|
|
2656
3963
|
*/
|
|
2657
|
-
|
|
2658
|
-
|
|
3964
|
+
_receiveDeps() {
|
|
3965
|
+
const chain = this._chain;
|
|
3966
|
+
return {
|
|
3967
|
+
ownHead: () => this._ownHead,
|
|
3968
|
+
flushLocal: async () => this._author(await this._scanner.scanFresh()),
|
|
3969
|
+
relate: (ours, theirs) => chain.relate(ours, theirs),
|
|
3970
|
+
treeRefOf: async (head) => (await chain.entry(head))?.treeRef,
|
|
3971
|
+
applyBehind: (head) => this._applyBehind(head),
|
|
3972
|
+
adopt: (head) => this._adopt(head),
|
|
3973
|
+
announceOwn: () => this._announceOwn(),
|
|
3974
|
+
merge: (theirs, base) => this._merge(theirs, base),
|
|
3975
|
+
blocked: (head, reason) => this._signalOnce(`blocked\0${this._ownHead}\0${head}`, {
|
|
3976
|
+
kind: "repair/blocked",
|
|
3977
|
+
paths: [],
|
|
3978
|
+
action: "review",
|
|
3979
|
+
decidedBy: "chain",
|
|
3980
|
+
detail: `${reason}; nothing was changed. It is retried when the hub says its state again.`
|
|
3981
|
+
})
|
|
3982
|
+
};
|
|
2659
3983
|
}
|
|
2660
3984
|
/**
|
|
2661
|
-
*
|
|
2662
|
-
*
|
|
2663
|
-
*
|
|
2664
|
-
* wrong. It has been answered in five separate places — the connector's sent
|
|
2665
|
-
* and received dedup sets, `_lastSentContentKey`, `_lastSentRef`,
|
|
2666
|
-
* `_lastAppliedRef` — and each has been wrong at least once:
|
|
2667
|
-
*
|
|
2668
|
-
* - an agent applied its OWN last advertisement over its own newer edit,
|
|
2669
|
-
* destroying it and then declining to re-send (fixed 0.0.30);
|
|
2670
|
-
* - a delete propagated only from the client that had created the file,
|
|
2671
|
-
* because the send path never retired the state it left (0.0.31);
|
|
2672
|
-
* - a refusal consumed the ref it refused, so the same emptiness arriving
|
|
2673
|
-
* twice was silent the second time (0.0.33);
|
|
2674
|
-
* - a restarted agent inherited its predecessor's conclusions (0.0.34);
|
|
2675
|
-
* - a quiet join announced anyway, because the connector broadcasts on
|
|
2676
|
-
* local insert and the gate was on the send (0.0.38).
|
|
2677
|
-
*
|
|
2678
|
-
* Collecting the pre-fetch gates here does not fix a sixth. It makes the
|
|
2679
|
-
* question answerable in one place, in one order, with the reasoning
|
|
2680
|
-
* attached — which is what the previous five each lacked.
|
|
2681
|
-
*
|
|
2682
|
-
* Order matters and is deliberate. The own-echo check comes first because it
|
|
2683
|
-
* is the only one that holds regardless of what the sender believes: the two
|
|
2684
|
-
* defences that ought to catch an echo both miss it. The origin filter
|
|
2685
|
-
* compares the payload's origin to this connector's, and a bootstrap carries
|
|
2686
|
-
* the SERVER as origin rather than the client the ref came from; the
|
|
2687
|
-
* staleness check then measures the server's sequence, which did advance, so
|
|
2688
|
-
* the echo reads as news.
|
|
2689
|
-
*
|
|
2690
|
-
* KNOWN LIMIT, stated because the next person will meet it: this compares
|
|
2691
|
-
* against the LAST ref this agent sent, so an echo of an OLDER
|
|
2692
|
-
* self-originated ref still gets through. Widening it to a set would also
|
|
2693
|
-
* suppress a peer's legitimate revert to a state this agent once held. The
|
|
2694
|
-
* real fix is for the bootstrap to carry the originating client, so the
|
|
2695
|
-
* origin filter works and this check stops being needed at all.
|
|
2696
|
-
* @param treeRef - The inbound ref.
|
|
2697
|
-
* @param isNewestFromSender - Whether the connector judged it the newest
|
|
2698
|
-
* thing its sender has advertised. Unknown answers `true`.
|
|
2699
|
-
* @returns `apply`, or the reason it is not news.
|
|
3985
|
+
* Makes a head this node's own without touching the folder: its content
|
|
3986
|
+
* is what the folder already holds.
|
|
3987
|
+
* @param head - The head.
|
|
2700
3988
|
*/
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
if (!isNewestFromSender) return "stale";
|
|
2704
|
-
return "apply";
|
|
3989
|
+
async _adopt(head) {
|
|
3990
|
+
this._setOwn(head, this._ownContent);
|
|
2705
3991
|
}
|
|
2706
3992
|
/**
|
|
2707
|
-
*
|
|
3993
|
+
* Applies a head that descends from the own one: writes what it changed,
|
|
3994
|
+
* deletes what it removed — every absence in it is a deletion its author
|
|
3995
|
+
* chose, because its author held this node's state.
|
|
2708
3996
|
*
|
|
2709
|
-
*
|
|
2710
|
-
*
|
|
2711
|
-
*
|
|
3997
|
+
* Only what changed between the two heads is touched, and only while the
|
|
3998
|
+
* folder still holds the own head's version of it. A file the user changed
|
|
3999
|
+
* since is never overwritten: the apply stops, that work is authored, and
|
|
4000
|
+
* the head is received again — as a fork, which merges.
|
|
4001
|
+
* @param head - The head.
|
|
4002
|
+
* A deletion beyond the receiver's floors is the exception: the files stay,
|
|
4003
|
+
* the head is adopted all the same, and the files are authored again on top
|
|
4004
|
+
* of it — which is what refills a node that lost them.
|
|
4005
|
+
* @returns `applied`, or `refused` when the head cannot be read or local
|
|
4006
|
+
* work stopped it.
|
|
2712
4007
|
*/
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
4008
|
+
async _applyBehind(head) {
|
|
4009
|
+
const theirs = await this._treeOf(head);
|
|
4010
|
+
if (!theirs) return "refused";
|
|
4011
|
+
const target = this._getFileContentMap(theirs.tree);
|
|
4012
|
+
const applied = await this._applyContent(
|
|
4013
|
+
target,
|
|
4014
|
+
(paths) => this._restorePaths(theirs.tree, paths)
|
|
4015
|
+
);
|
|
4016
|
+
if (applied === "moved") {
|
|
4017
|
+
this._receiveAgain(head);
|
|
4018
|
+
return "refused";
|
|
2722
4019
|
}
|
|
4020
|
+
this._setOwn(head, target);
|
|
4021
|
+
if (applied === "kept") await this._author(await this._scanner.scanFresh());
|
|
4022
|
+
return "applied";
|
|
2723
4023
|
}
|
|
2724
4024
|
/**
|
|
2725
|
-
*
|
|
2726
|
-
*
|
|
2727
|
-
*
|
|
4025
|
+
* Moves the folder from the own content to `target`: writes what differs,
|
|
4026
|
+
* deletes what `target` lacks.
|
|
4027
|
+
*
|
|
4028
|
+
* The receiver guard: a deletion that would lose more than the floors allow
|
|
4029
|
+
* — content `target` holds nowhere else — is not made. Everything else is,
|
|
4030
|
+
* and the files kept become this node's work, so the folder never holds a
|
|
4031
|
+
* state the chain does not describe.
|
|
4032
|
+
* @param target - Where the folder should end up, `path → blob`.
|
|
4033
|
+
* @param write - Writes the given paths' `target` versions.
|
|
4034
|
+
* @returns `applied`; `kept` when the guard kept files `target` lacks;
|
|
4035
|
+
* `moved` when the folder had moved past the own head.
|
|
2728
4036
|
*/
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
4037
|
+
async _applyContent(target, write) {
|
|
4038
|
+
const own = this._ownContent;
|
|
4039
|
+
const landed = this._partiallyApplied;
|
|
4040
|
+
const writes = [...target.keys()].filter(
|
|
4041
|
+
(p) => target.get(p) !== own.get(p) && target.get(p) !== landed.get(p)
|
|
2733
4042
|
);
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
4043
|
+
const deletes = [...own.keys()].filter((p) => !target.has(p));
|
|
4044
|
+
const isFile = (v) => v !== void 0 && v !== DIR_MARKER;
|
|
4045
|
+
const held = [...own.values()].filter(isFile).length;
|
|
4046
|
+
const deletedFiles = deletes.filter((p) => isFile(own.get(p)));
|
|
4047
|
+
const stillThere = new Set([...target.values()].filter(isFile));
|
|
4048
|
+
const lost = deletedFiles.filter((p) => !stillThere.has(own.get(p)));
|
|
4049
|
+
const keep = new Set(
|
|
4050
|
+
lost.length > MASS_DELETE_MIN_FILES && lost.length / held > MASS_DELETE_MAX_RATIO || lost.length > 0 && held > ALL_GONE_MIN_FILES && [...target.values()].filter(isFile).length <= ALL_GONE_MIN_FILES ? lost : []
|
|
4051
|
+
);
|
|
4052
|
+
const deleting = deletes.filter((p) => !keep.has(p));
|
|
4053
|
+
if (!await this._unchangedSinceOwn([...writes, ...deleting])) return "moved";
|
|
4054
|
+
if (writes.length > 0) {
|
|
4055
|
+
try {
|
|
4056
|
+
await write(writes);
|
|
4057
|
+
} catch (err) {
|
|
4058
|
+
for (const path of writes) {
|
|
4059
|
+
const blob = target.get(path);
|
|
4060
|
+
if (await this._blobOnDisk(path) === blob) landed.set(path, blob);
|
|
4061
|
+
}
|
|
4062
|
+
throw err;
|
|
4063
|
+
}
|
|
2739
4064
|
}
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
4065
|
+
for (const path of deletedFiles.filter((p) => !keep.has(p))) {
|
|
4066
|
+
await rm(join(this._rootPath, ...path.split("/")), { force: true });
|
|
4067
|
+
}
|
|
4068
|
+
for (const path of deletes.filter((p) => own.get(p) === DIR_MARKER).sort().reverse()) {
|
|
4069
|
+
await rmdir(join(this._rootPath, ...path.split("/"))).catch(() => void 0);
|
|
2745
4070
|
}
|
|
2746
|
-
|
|
4071
|
+
if (keep.size === 0) return "applied";
|
|
4072
|
+
this._refuseDeletion(
|
|
4073
|
+
"restore",
|
|
4074
|
+
keep.size,
|
|
4075
|
+
held,
|
|
4076
|
+
[...keep],
|
|
4077
|
+
"Everything else was applied; the files stay and are authored again."
|
|
4078
|
+
);
|
|
4079
|
+
return "kept";
|
|
2747
4080
|
}
|
|
2748
4081
|
/**
|
|
2749
|
-
*
|
|
2750
|
-
*
|
|
4082
|
+
* Whether every given path still holds what the own head says — or what a
|
|
4083
|
+
* cut-short apply already wrote there: no local change the watcher has not
|
|
4084
|
+
* reported yet.
|
|
4085
|
+
* @param paths - Relative paths.
|
|
4086
|
+
* @returns `true` when none of them changed since the own head.
|
|
2751
4087
|
*/
|
|
2752
|
-
|
|
2753
|
-
|
|
4088
|
+
async _unchangedSinceOwn(paths) {
|
|
4089
|
+
for (const path of paths) {
|
|
4090
|
+
const expected = this._partiallyApplied.get(path) ?? this._ownContent.get(path);
|
|
4091
|
+
if (expected === DIR_MARKER) continue;
|
|
4092
|
+
const blob = await this._blobOnDisk(path);
|
|
4093
|
+
if (expected === void 0 ? blob !== null : blob !== expected) {
|
|
4094
|
+
return false;
|
|
4095
|
+
}
|
|
4096
|
+
}
|
|
4097
|
+
return true;
|
|
2754
4098
|
}
|
|
2755
4099
|
/**
|
|
2756
|
-
*
|
|
2757
|
-
*
|
|
2758
|
-
*
|
|
2759
|
-
*
|
|
2760
|
-
* @param
|
|
2761
|
-
* @
|
|
4100
|
+
* The blob a file holds, as far as this agent knows without reading it: what
|
|
4101
|
+
* it last wrote there, or what the scanner last read — whichever a `stat`
|
|
4102
|
+
* confirms. Both, because either goes stale on its own: a restore's record
|
|
4103
|
+
* once anything else rewrites the file, the scanner's until its next pass.
|
|
4104
|
+
* @param path - Relative path.
|
|
4105
|
+
* @returns The blob; `null` when no file is there; `undefined` when the file
|
|
4106
|
+
* changed since this agent last knew it.
|
|
2762
4107
|
*/
|
|
2763
|
-
|
|
2764
|
-
const
|
|
2765
|
-
const
|
|
2766
|
-
if (
|
|
2767
|
-
for (const
|
|
2768
|
-
|
|
4108
|
+
async _blobOnDisk(path) {
|
|
4109
|
+
const full = join(this._rootPath, ...path.split("/"));
|
|
4110
|
+
const st = await stat(full).catch(() => void 0);
|
|
4111
|
+
if (!st?.isFile()) return null;
|
|
4112
|
+
for (const known of [
|
|
4113
|
+
this._restoredBlobs.get(full),
|
|
4114
|
+
this._scanner.knownFile(path)
|
|
4115
|
+
]) {
|
|
4116
|
+
if (known && st.size === known.size && Math.abs(st.mtimeMs - known.mtime) < 1) {
|
|
4117
|
+
return known.blobId;
|
|
4118
|
+
}
|
|
2769
4119
|
}
|
|
2770
|
-
return
|
|
4120
|
+
return void 0;
|
|
2771
4121
|
}
|
|
2772
4122
|
/**
|
|
2773
|
-
*
|
|
2774
|
-
*
|
|
2775
|
-
*
|
|
2776
|
-
*
|
|
2777
|
-
* so the watcher-driven re-scan that follows the on-disk materialisation
|
|
2778
|
-
* settles to a no-op instead of re-broadcasting.
|
|
2779
|
-
* @param db - Database instance
|
|
2780
|
-
* @param treeKey - Tree table key
|
|
4123
|
+
* Writes the given paths of a tree into the folder, with everything a
|
|
4124
|
+
* restore does for a write: streams, locks, impossible names, a full disk.
|
|
4125
|
+
* @param tree - The tree.
|
|
4126
|
+
* @param paths - The relative paths to write.
|
|
2781
4127
|
*/
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
},
|
|
2799
|
-
deleteFileAt: async (relativePath) => {
|
|
2800
|
-
await rm(join(this._rootPath, relativePath), {
|
|
2801
|
-
force: true,
|
|
2802
|
-
recursive: true
|
|
2803
|
-
});
|
|
2804
|
-
},
|
|
2805
|
-
scan: () => this._scanner.scan(),
|
|
2806
|
-
storeMerge: async (tree, previous) => {
|
|
2807
|
-
const dbAdapter = new FsDbAdapter(db, treeKey);
|
|
2808
|
-
const ref = await dbAdapter.storeFsTree(tree, { previous });
|
|
2809
|
-
this._lastSentRef = ref;
|
|
2810
|
-
this._lastPushedRef = ref;
|
|
2811
|
-
this._lastSentContentKey = this._contentKeyFromTree(tree);
|
|
2812
|
-
this._rememberAnnounced(tree);
|
|
2813
|
-
this._currentRef = ref;
|
|
2814
|
-
return ref;
|
|
2815
|
-
}
|
|
2816
|
-
// Resolution failures are surfaced by `_onConflict`; success is silent.
|
|
4128
|
+
async _restorePaths(tree, paths) {
|
|
4129
|
+
const wanted = new Set(paths);
|
|
4130
|
+
const keep = /* @__PURE__ */ new Map();
|
|
4131
|
+
const visit = (hash) => {
|
|
4132
|
+
const node = tree.trees.get(hash);
|
|
4133
|
+
if (!node) return false;
|
|
4134
|
+
const path = node.meta?.relativePath;
|
|
4135
|
+
if (node.meta?.type === "file") {
|
|
4136
|
+
if (!wanted.has(path)) return false;
|
|
4137
|
+
keep.set(hash, node);
|
|
4138
|
+
return true;
|
|
4139
|
+
}
|
|
4140
|
+
const children = (node.children ?? []).filter(visit);
|
|
4141
|
+
if (children.length === 0 && !wanted.has(path)) return false;
|
|
4142
|
+
keep.set(hash, { ...node, children });
|
|
4143
|
+
return true;
|
|
2817
4144
|
};
|
|
4145
|
+
visit(tree.rootHash);
|
|
4146
|
+
await FsAgent._withTimeout(
|
|
4147
|
+
this.restore({ rootHash: tree.rootHash, trees: keep }, void 0, {
|
|
4148
|
+
cleanTarget: false
|
|
4149
|
+
}),
|
|
4150
|
+
this._timeouts.restore,
|
|
4151
|
+
`restore(${paths.length} paths)`
|
|
4152
|
+
);
|
|
2818
4153
|
}
|
|
2819
4154
|
/**
|
|
2820
|
-
*
|
|
2821
|
-
*
|
|
2822
|
-
* @param
|
|
2823
|
-
* @param
|
|
2824
|
-
* @
|
|
2825
|
-
*
|
|
2826
|
-
* @returns Function to stop watching
|
|
4155
|
+
* Merges a forked head into the own one against their common base — the
|
|
4156
|
+
* conflict table in `fs-merge.ts` — and authors the merge.
|
|
4157
|
+
* @param theirs - The forked head.
|
|
4158
|
+
* @param base - Their common ancestor, if any.
|
|
4159
|
+
* @returns `merged`; `deferred` when a stamp the verdict needs is not known
|
|
4160
|
+
* yet; `refused` when the merge could not be applied.
|
|
2827
4161
|
*/
|
|
2828
|
-
async
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
const
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
const incomingTree = await FsAgent._withTimeout(
|
|
2852
|
-
this._fetchTreeFromDb(db, treeKey, treeRef),
|
|
2853
|
-
this._timeouts.fetchTree,
|
|
2854
|
-
`syncFromDb → fetchTree(${treeKey}@${treeRef.slice(0, 8)}…)`
|
|
2855
|
-
);
|
|
2856
|
-
const incomingNodeCount = incomingTree.trees.size;
|
|
2857
|
-
console.log(
|
|
2858
|
-
`[FsAgent] syncFromDb: fetched tree with ${incomingNodeCount} nodes for ref=${treeRef.slice(0, 8)}…`
|
|
2859
|
-
);
|
|
2860
|
-
const currentTree = await FsAgent._withTimeout(
|
|
2861
|
-
this.extract(),
|
|
2862
|
-
this._timeouts.extract,
|
|
2863
|
-
`syncFromDb → extract(${this._rootPath})`
|
|
2864
|
-
);
|
|
2865
|
-
if (this._treesHaveEquivalentContent(currentTree, incomingTree)) {
|
|
2866
|
-
const incomingFiles2 = this._getFileContentMap(incomingTree);
|
|
2867
|
-
const currentFiles = this._getFileContentMap(currentTree);
|
|
2868
|
-
console.log(
|
|
2869
|
-
`[FsAgent] syncFromDb: equivalent content, skipping restore (incoming=${incomingFiles2.size} entries, current=${currentFiles.size} entries, ref=${treeRef.slice(0, 8)}…)`
|
|
2870
|
-
);
|
|
2871
|
-
this._adoptAppliedRef(connector, treeRef);
|
|
2872
|
-
this._currentRef = treeRef;
|
|
2873
|
-
this._persistCurrentRef(treeRef);
|
|
2874
|
-
this._lastSentContentKey = this._contentKeyFromTree(currentTree);
|
|
2875
|
-
this._rememberAnnounced(currentTree);
|
|
2876
|
-
return;
|
|
2877
|
-
}
|
|
2878
|
-
if (this._resolveConflicts && this._currentRef && predecessorRefs && predecessorRefs.length > 0) {
|
|
2879
|
-
const relation = await this._ancestryRelation(
|
|
2880
|
-
db,
|
|
2881
|
-
treeKey,
|
|
2882
|
-
this._currentRef,
|
|
2883
|
-
treeRef,
|
|
2884
|
-
predecessorRefs
|
|
2885
|
-
);
|
|
2886
|
-
if (relation === "ahead") {
|
|
2887
|
-
return;
|
|
2888
|
-
}
|
|
2889
|
-
if (relation === "diverged") {
|
|
2890
|
-
await this._resolveConflictInline(
|
|
2891
|
-
db,
|
|
2892
|
-
treeKey,
|
|
2893
|
-
treeRef,
|
|
2894
|
-
incomingTree,
|
|
2895
|
-
predecessorRefs
|
|
2896
|
-
);
|
|
2897
|
-
return;
|
|
2898
|
-
}
|
|
2899
|
-
}
|
|
2900
|
-
const ancestryExpected = this._resolveConflicts || connector.syncConfig?.causalOrdering === true;
|
|
2901
|
-
const declaresAncestry = (predecessorRefs?.length ?? 0) > 0;
|
|
2902
|
-
const ancestryIsCarried = connector.syncConfig?.causalOrdering === true;
|
|
2903
|
-
const statesIAmIn = [this._currentRef, this._lastAppliedRef].filter(
|
|
2904
|
-
(r) => r !== void 0
|
|
2905
|
-
);
|
|
2906
|
-
const senderSawMyState = !ancestryIsCarried || !declaresAncestry || statesIAmIn.some((r) => predecessorRefs.includes(r));
|
|
2907
|
-
if (ancestryIsCarried && declaresAncestry && this._senderIsBehind(predecessorRefs)) {
|
|
2908
|
-
console.warn(
|
|
2909
|
-
`[FsAgent] ref=${treeRef.slice(0, 8)}… descends from a state this node has already left — ignoring, the sender will catch up and re-push.`
|
|
2910
|
-
);
|
|
2911
|
-
return;
|
|
2912
|
-
}
|
|
2913
|
-
const withholdPrune = restoreOptions?.cleanTarget && (ancestryExpected && !declaresAncestry || !senderSawMyState);
|
|
2914
|
-
const applyOptions = withholdPrune ? { ...restoreOptions, cleanTarget: false } : restoreOptions;
|
|
2915
|
-
if (applyOptions !== restoreOptions) {
|
|
2916
|
-
console.warn(
|
|
2917
|
-
`[FsAgent] ref=${treeRef.slice(0, 8)}… ` + (declaresAncestry ? `descends from ${predecessorRefs?.map((r) => r.slice(0, 8)).join(", ")}, not from a state this node is in (${statesIAmIn.map((r) => r.slice(0, 8)).join(", ") || "none"})` : "declares no ancestry") + ` — applying additively, not pruning.`
|
|
2918
|
-
);
|
|
2919
|
-
}
|
|
2920
|
-
if (restoreOptions?.cleanTarget) {
|
|
2921
|
-
console.log(
|
|
2922
|
-
`[FsAgent] applying ref=${treeRef.slice(0, 8)}… newestFromSender=${isNewestFromSender} declaresAncestry=${declaresAncestry} mayPrune=${applyOptions === restoreOptions} incomingFiles=${this._getFileContentMap(incomingTree).size} currentFiles=${this._getFileContentMap(currentTree).size}`
|
|
2923
|
-
);
|
|
2924
|
-
}
|
|
2925
|
-
await FsAgent._withTimeout(
|
|
2926
|
-
this.restore(incomingTree, void 0, applyOptions),
|
|
2927
|
-
this._timeouts.restore,
|
|
2928
|
-
`syncFromDb → restore(${treeKey})`
|
|
2929
|
-
);
|
|
2930
|
-
const postRestoreTree = await this._scanner.scan();
|
|
2931
|
-
const dbAdapter = new FsDbAdapter(db, treeKey);
|
|
2932
|
-
const previous = await this._ancestryPrevious(
|
|
2933
|
-
db,
|
|
2934
|
-
treeKey,
|
|
2935
|
-
predecessorRefs
|
|
2936
|
-
);
|
|
2937
|
-
const postRestoreRef = await dbAdapter.storeFsTree(postRestoreTree, {
|
|
2938
|
-
skipNotification: true,
|
|
2939
|
-
previous
|
|
2940
|
-
});
|
|
2941
|
-
this._adoptAppliedRef(connector, treeRef);
|
|
2942
|
-
this._currentRef = postRestoreRef;
|
|
2943
|
-
this._persistCurrentRef(postRestoreRef);
|
|
2944
|
-
const postRestoreFiles = this._getFileContentMap(postRestoreTree);
|
|
2945
|
-
const incomingFiles = this._getFileContentMap(incomingTree);
|
|
2946
|
-
let hasNewsOfOurOwn = false;
|
|
2947
|
-
for (const path of postRestoreFiles.keys()) {
|
|
2948
|
-
if (!incomingFiles.has(path)) {
|
|
2949
|
-
hasNewsOfOurOwn = true;
|
|
2950
|
-
break;
|
|
2951
|
-
}
|
|
2952
|
-
}
|
|
2953
|
-
if (!hasNewsOfOurOwn) {
|
|
2954
|
-
this._lastSentRef = postRestoreRef;
|
|
2955
|
-
this._lastSentContentKey = this._contentKeyFromTree(postRestoreTree);
|
|
2956
|
-
this._rememberAnnounced(postRestoreTree);
|
|
2957
|
-
if (postRestoreFiles.size < incomingFiles.size) {
|
|
2958
|
-
console.log(
|
|
2959
|
-
`[FsAgent] ref=${treeRef.slice(0, 8)}… left this node behind (${postRestoreFiles.size} of ${incomingFiles.size} files) — not announcing a state that is catching up.`
|
|
2960
|
-
);
|
|
2961
|
-
}
|
|
2962
|
-
}
|
|
2963
|
-
return;
|
|
2964
|
-
} catch (err) {
|
|
2965
|
-
if (err instanceof MassDeleteRefusedError) {
|
|
2966
|
-
connector.invalidateReceived(treeRef);
|
|
2967
|
-
await this._readvertiseAfterRefusal(connector);
|
|
2968
|
-
return;
|
|
2969
|
-
}
|
|
2970
|
-
if (err instanceof PartialRestoreError || err instanceof BlobUnavailableError) {
|
|
2971
|
-
try {
|
|
2972
|
-
const halfApplied = await this._scanner.scan();
|
|
2973
|
-
this._lastSentContentKey = this._contentKeyFromTree(halfApplied);
|
|
2974
|
-
} catch {
|
|
2975
|
-
}
|
|
2976
|
-
}
|
|
2977
|
-
if (attempt === maxAttempts) {
|
|
2978
|
-
if (recoveryAttempt >= this._timeouts.recoveryRetries) {
|
|
2979
|
-
console.error(
|
|
2980
|
-
`[FsAgent] syncFromDb processRef failed after ${maxAttempts} attempts and ${recoveryAttempt} recoveries:`,
|
|
2981
|
-
err
|
|
2982
|
-
);
|
|
2983
|
-
this._writeSyncError("syncFromDb/processRef", err);
|
|
2984
|
-
connector.invalidateReceived(treeRef);
|
|
2985
|
-
} else {
|
|
2986
|
-
if (pendingRef === null) {
|
|
2987
|
-
console.warn(
|
|
2988
|
-
`[FsAgent] syncFromDb: ref=${treeRef.slice(0, 8)}… not yet fetchable after ${maxAttempts} attempts, re-queueing (recovery ${recoveryAttempt + 1}/${this._timeouts.recoveryRetries}): ${FsAgent._errMessage(err)}`
|
|
2989
|
-
);
|
|
2990
|
-
scheduleProcess(
|
|
2991
|
-
treeRef,
|
|
2992
|
-
this._timeouts.processRefRetryDelayMs * maxAttempts,
|
|
2993
|
-
recoveryAttempt + 1,
|
|
2994
|
-
predecessorRefs
|
|
2995
|
-
);
|
|
2996
|
-
}
|
|
2997
|
-
}
|
|
2998
|
-
} else {
|
|
2999
|
-
const delaySec = attempt * this._timeouts.processRefRetryDelayMs / 1e3;
|
|
3000
|
-
console.warn(
|
|
3001
|
-
`[FsAgent] syncFromDb: attempt ${attempt}/${maxAttempts} failed for ref=${treeRef.slice(0, 8)}…, retrying in ${delaySec}s: ${FsAgent._errMessage(err)}`
|
|
3002
|
-
);
|
|
3003
|
-
}
|
|
3004
|
-
} finally {
|
|
3005
|
-
this._remoteApplyInFlight = false;
|
|
3006
|
-
this._scanner.resumeWatch();
|
|
3007
|
-
this._flushDeferredRescan?.();
|
|
3008
|
-
}
|
|
3009
|
-
await new Promise(
|
|
3010
|
-
(r) => setTimeout(r, attempt * this._timeouts.processRefRetryDelayMs)
|
|
3011
|
-
);
|
|
4162
|
+
async _merge(theirs, base) {
|
|
4163
|
+
const own = this._ownHead;
|
|
4164
|
+
const chain = this._chain;
|
|
4165
|
+
const stamps = this._stamps;
|
|
4166
|
+
const [theirTree, baseTree] = await Promise.all([
|
|
4167
|
+
this._treeOf(theirs),
|
|
4168
|
+
base === void 0 ? Promise.resolve(void 0) : this._treeOf(base)
|
|
4169
|
+
]);
|
|
4170
|
+
if (!theirTree || base !== void 0 && !baseTree) return "refused";
|
|
4171
|
+
const ours = this._ownContent;
|
|
4172
|
+
const theirContent = this._getFileContentMap(theirTree.tree);
|
|
4173
|
+
console.log(
|
|
4174
|
+
`${this._tag} merging ${theirs.slice(0, 8)}… into ${own.slice(0, 8)}… against ${base?.slice(0, 8) ?? "no common history"}`
|
|
4175
|
+
);
|
|
4176
|
+
const baseContent = baseTree ? this._getFileContentMap(baseTree.tree) : /* @__PURE__ */ new Map();
|
|
4177
|
+
const contested = [.../* @__PURE__ */ new Set([...ours.keys(), ...theirContent.keys()])].filter(
|
|
4178
|
+
(p) => ours.get(p) !== theirContent.get(p) && ours.get(p) !== baseContent.get(p) && theirContent.get(p) !== baseContent.get(p)
|
|
4179
|
+
);
|
|
4180
|
+
const introducers = async (head) => {
|
|
4181
|
+
const found = /* @__PURE__ */ new Map();
|
|
4182
|
+
for (const path of contested) {
|
|
4183
|
+
const entry2 = (await chain.lastEditOf(head, path))?.head ?? head;
|
|
4184
|
+
found.set(path, { entry: entry2, stamp: stamps.get(entry2), nodeId: "" });
|
|
3012
4185
|
}
|
|
4186
|
+
return found;
|
|
3013
4187
|
};
|
|
3014
|
-
const
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
pendingPredecessorRefs = predecessorRefs;
|
|
3021
|
-
pendingIsNewest = isNewestFromSender;
|
|
3022
|
-
if (fromDbTimer) clearTimeout(fromDbTimer);
|
|
3023
|
-
fromDbTimer = setTimeout(async () => {
|
|
3024
|
-
fromDbTimer = null;
|
|
3025
|
-
const r = pendingRef;
|
|
3026
|
-
const ra = pendingRecoveryAttempt;
|
|
3027
|
-
const pr = pendingPredecessorRefs;
|
|
3028
|
-
const newest = pendingIsNewest;
|
|
3029
|
-
pendingRef = null;
|
|
3030
|
-
if (r) {
|
|
3031
|
-
processing = true;
|
|
3032
|
-
try {
|
|
3033
|
-
await processRef(r, ra, pr, newest);
|
|
3034
|
-
} finally {
|
|
3035
|
-
processing = false;
|
|
3036
|
-
}
|
|
3037
|
-
}
|
|
3038
|
-
}, delayMs);
|
|
3039
|
-
};
|
|
3040
|
-
const syncCallback = (treeRef, predecessorRefs, info) => {
|
|
3041
|
-
if (!treeRef || typeof treeRef !== "string") {
|
|
3042
|
-
return Promise.resolve();
|
|
3043
|
-
}
|
|
3044
|
-
scheduleProcess(
|
|
3045
|
-
treeRef,
|
|
3046
|
-
this._timeouts.debounceMs,
|
|
3047
|
-
0,
|
|
3048
|
-
predecessorRefs,
|
|
3049
|
-
info?.isNewestFromSender ?? true
|
|
4188
|
+
const decide = async () => {
|
|
4189
|
+
const [mine, yours] = await Promise.all([introducers(own), introducers(theirs)]);
|
|
4190
|
+
const outcome2 = merge3(
|
|
4191
|
+
baseContent,
|
|
4192
|
+
{ content: ours, introducer: (p) => mine.get(p) },
|
|
4193
|
+
{ content: theirContent, introducer: (p) => yours.get(p) }
|
|
3050
4194
|
);
|
|
3051
|
-
|
|
4195
|
+
const ownUnstamped2 = outcome2.unknownStamps.some((p) => !mine.get(p)?.stamp);
|
|
4196
|
+
return { outcome: outcome2, ownUnstamped: ownUnstamped2 };
|
|
3052
4197
|
};
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
}
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3077
|
-
|
|
4198
|
+
let { outcome, ownUnstamped } = await decide();
|
|
4199
|
+
if (outcome.unknownStamps.length > 0) {
|
|
4200
|
+
await stamps.settle();
|
|
4201
|
+
({ outcome, ownUnstamped } = await decide());
|
|
4202
|
+
}
|
|
4203
|
+
if (outcome.unknownStamps.length > 0) {
|
|
4204
|
+
if (ownUnstamped) this._askForStamp(own);
|
|
4205
|
+
const key = `await-stamp\0${own}\0${theirs}`;
|
|
4206
|
+
if (this._deferral === key) {
|
|
4207
|
+
this._signalOnce(key, {
|
|
4208
|
+
kind: "repair/blocked",
|
|
4209
|
+
paths: outcome.unknownStamps,
|
|
4210
|
+
action: "review",
|
|
4211
|
+
decidedBy: "stamp",
|
|
4212
|
+
detail: "two versions of these files wait for the hub to say which reached the fleet first; nothing was changed"
|
|
4213
|
+
});
|
|
4214
|
+
}
|
|
4215
|
+
this._deferral = key;
|
|
4216
|
+
return "deferred";
|
|
4217
|
+
}
|
|
4218
|
+
const applied = await this._applyContent(outcome.merged, async (paths) => {
|
|
4219
|
+
const fromTheirs = paths.filter((p) => outcome.merged.get(p) === theirContent.get(p));
|
|
4220
|
+
if (fromTheirs.length > 0) await this._restorePaths(theirTree.tree, fromTheirs);
|
|
4221
|
+
for (const path of paths.filter((p) => !fromTheirs.includes(p))) {
|
|
4222
|
+
const blob = outcome.merged.get(path);
|
|
4223
|
+
const full = join(this._rootPath, ...path.split("/"));
|
|
4224
|
+
await mkdir(dirname(full), { recursive: true });
|
|
4225
|
+
await FsAgent._atomicWriteFile(full, await this._adapter.getFileContent(blob));
|
|
4226
|
+
const st = await stat(full);
|
|
4227
|
+
this._scanner.noteWrite(path, blob, st.size, st.mtime.getTime());
|
|
3078
4228
|
}
|
|
3079
4229
|
});
|
|
3080
|
-
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
4230
|
+
if (applied === "moved") {
|
|
4231
|
+
this._receiveAgain(theirs);
|
|
4232
|
+
return "refused";
|
|
4233
|
+
}
|
|
4234
|
+
const merged = await this._scanner.scanFresh();
|
|
4235
|
+
const mergedContent = this._getFileContentMap(merged);
|
|
4236
|
+
const treeRef = await this._storeTree(merged);
|
|
4237
|
+
const touched = [.../* @__PURE__ */ new Set([...mergedContent.keys(), ...ours.keys(), ...theirContent.keys()])];
|
|
4238
|
+
const previous = [own, theirs].sort();
|
|
4239
|
+
const entry = await chain.append({
|
|
4240
|
+
treeRef,
|
|
4241
|
+
previous,
|
|
4242
|
+
changed: touched.filter((p) => mergedContent.has(p) && (mergedContent.get(p) !== ours.get(p) || mergedContent.get(p) !== theirContent.get(p))).sort(),
|
|
4243
|
+
removed: touched.filter((p) => !mergedContent.has(p)).sort(),
|
|
4244
|
+
timeId: `0:${hip({ previous, treeRef, _hash: "" })._hash}`
|
|
4245
|
+
});
|
|
4246
|
+
this._setOwn(entry.head, mergedContent);
|
|
4247
|
+
for (const conflict of outcome.conflicts) {
|
|
4248
|
+
this._signal({
|
|
4249
|
+
kind: conflict.kind,
|
|
4250
|
+
paths: [conflict.path],
|
|
4251
|
+
action: conflict.kind === "collision/type" ? "required" : "review",
|
|
4252
|
+
decidedBy: conflict.kind === "collision/type" ? "chain" : "stamp",
|
|
4253
|
+
...conflict.copyPath ? { copyPath: conflict.copyPath } : {},
|
|
4254
|
+
detail: conflict.copyPath ? `two machines changed "${conflict.path}" at once; both versions were kept and the other one is at "${conflict.copyPath}"` : `"${conflict.path}" was deleted on one machine and edited on another; the edit was kept`
|
|
3087
4255
|
});
|
|
3088
|
-
};
|
|
3089
|
-
const hubEvents = [
|
|
3090
|
-
connector.events.bootstrap,
|
|
3091
|
-
stateBeaconEvent(connector.route.flat)
|
|
3092
|
-
];
|
|
3093
|
-
for (const event of hubEvents) {
|
|
3094
|
-
connector.socket.on(event, onHubAnnouncement);
|
|
3095
4256
|
}
|
|
4257
|
+
this._announceOwn();
|
|
4258
|
+
return "merged";
|
|
4259
|
+
}
|
|
4260
|
+
/**
|
|
4261
|
+
* Hears the network: announcements, the stamps of this node's own, and the
|
|
4262
|
+
* hub's state beacon.
|
|
4263
|
+
* @param db - The route's database.
|
|
4264
|
+
* @param connector - The transport.
|
|
4265
|
+
* @param treeKey - The trees table key.
|
|
4266
|
+
* @returns Stops listening.
|
|
4267
|
+
*/
|
|
4268
|
+
async syncFromDb(db, connector, treeKey) {
|
|
4269
|
+
this._route = { db, connector, treeKey };
|
|
4270
|
+
await this._ensureChain(db, treeKey);
|
|
4271
|
+
await this._ensureWatching();
|
|
4272
|
+
connector.resetReceived?.();
|
|
4273
|
+
const generation = ++this._receivers;
|
|
4274
|
+
connector.listen(async (ref, _predecessors, info) => {
|
|
4275
|
+
this._hear(ref, info?.stamp);
|
|
4276
|
+
});
|
|
4277
|
+
const offStamp = connector.onStamp(
|
|
4278
|
+
(ref, stamp) => this._recordStamp(ref, stamp)
|
|
4279
|
+
);
|
|
4280
|
+
const beacon = (payload) => this._hear(payload?.r, payload?.stamp, true);
|
|
4281
|
+
const events = [connector.events.bootstrap, stateBeaconEvent(connector.route.flat)];
|
|
4282
|
+
for (const event of events) connector.socket.on(event, beacon);
|
|
3096
4283
|
return () => {
|
|
3097
|
-
|
|
3098
|
-
for (const event of
|
|
3099
|
-
connector.socket.off(event, onHubAnnouncement);
|
|
3100
|
-
}
|
|
3101
|
-
if (this._antiEntropy === antiEntropy) this._antiEntropy = void 0;
|
|
4284
|
+
offStamp();
|
|
4285
|
+
for (const event of events) connector.socket.off(event, beacon);
|
|
3102
4286
|
connector.tearDown();
|
|
4287
|
+
if (generation === this._receivers) {
|
|
4288
|
+
this._hubStatus = null;
|
|
4289
|
+
this._hubHead = void 0;
|
|
4290
|
+
}
|
|
3103
4291
|
};
|
|
3104
4292
|
}
|
|
4293
|
+
/**
|
|
4294
|
+
* Says, once, that a deletion was refused — in the log and as one
|
|
4295
|
+
* `deletion/refused` signal.
|
|
4296
|
+
*
|
|
4297
|
+
* Three call sites had three copies of this, which is how they came to say
|
|
4298
|
+
* three different things about the same decision. A client reading one of
|
|
4299
|
+
* them saw a third of the picture.
|
|
4300
|
+
* @param route - Which rule refused it.
|
|
4301
|
+
* @param wouldRemove - How many paths it would have deleted.
|
|
4302
|
+
* @param held - How many this folder holds.
|
|
4303
|
+
* @param paths - The paths, of which the first few are kept.
|
|
4304
|
+
* @param detail - Extra wording for the log line, where a route has some.
|
|
4305
|
+
*/
|
|
4306
|
+
_refuseDeletion(route, wouldRemove, held, paths, detail = "") {
|
|
4307
|
+
const what = route === "author" ? `${wouldRemove} of ${held} files disappeared and were not recorded, so no node deletes them.` : `${route} would have removed ${wouldRemove} of ${held} files, so nothing was deleted.`;
|
|
4308
|
+
const said = what + (detail === "" ? "" : ` ${detail}`) + " If the deletion is real it has to be applied deliberately.";
|
|
4309
|
+
console.error(
|
|
4310
|
+
`${this._tag} MASS DELETE REFUSED on ${this._rootPath}: ${said}`
|
|
4311
|
+
);
|
|
4312
|
+
this._signal({
|
|
4313
|
+
kind: "deletion/refused",
|
|
4314
|
+
paths,
|
|
4315
|
+
action: "required",
|
|
4316
|
+
decidedBy: "guard",
|
|
4317
|
+
detail: said
|
|
4318
|
+
});
|
|
4319
|
+
}
|
|
3105
4320
|
/**
|
|
3106
4321
|
* Creates a fully configured FsAgent from a Client instance.
|
|
3107
|
-
* This factory method provides a simplified API where sync methods don't
|
|
3108
|
-
* db, connector, and treeKey parameters - they are stored internally.
|
|
4322
|
+
* This factory method provides a simplified API where sync methods don't
|
|
4323
|
+
* require db, connector, and treeKey parameters - they are stored internally.
|
|
3109
4324
|
* @param filePath - Directory path to sync
|
|
3110
4325
|
* @param treeKey - Tree table key (route will be `/${treeKey}`)
|
|
3111
4326
|
* @param client - Client instance with io and bs properties
|
|
@@ -3141,17 +4356,17 @@ ${err.stack}` : String(err);
|
|
|
3141
4356
|
db,
|
|
3142
4357
|
route,
|
|
3143
4358
|
socket,
|
|
3144
|
-
|
|
4359
|
+
{
|
|
4360
|
+
causalOrdering: true,
|
|
4361
|
+
includeClientIdentity: true,
|
|
4362
|
+
...options?.syncConfig
|
|
4363
|
+
},
|
|
3145
4364
|
options?.clientIdentity
|
|
3146
4365
|
);
|
|
3147
4366
|
const agent = new FsAgent(filePath, client.bs, options);
|
|
3148
4367
|
const enhancedAgent = agent;
|
|
3149
|
-
enhancedAgent.syncToDbSimple = async (
|
|
3150
|
-
|
|
3151
|
-
};
|
|
3152
|
-
enhancedAgent.syncFromDbSimple = async (restoreOpts) => {
|
|
3153
|
-
return agent.syncFromDb(db, connector, treeKey, restoreOpts);
|
|
3154
|
-
};
|
|
4368
|
+
enhancedAgent.syncToDbSimple = async () => agent.syncToDb(db, connector, treeKey);
|
|
4369
|
+
enhancedAgent.syncFromDbSimple = async () => agent.syncFromDb(db, connector, treeKey);
|
|
3155
4370
|
if (typeof client.onDisconnect === "function") {
|
|
3156
4371
|
client.onDisconnect(() => {
|
|
3157
4372
|
agent.scanner.pauseWatch(DISCONNECT_PAUSE_MAX_MS);
|
|
@@ -3189,7 +4404,7 @@ async function runClientServerSetup(opts = {}) {
|
|
|
3189
4404
|
const { BsMem: BsMem2 } = await import("@rljson/bs");
|
|
3190
4405
|
const serverBsMem = new BsMem2();
|
|
3191
4406
|
await createSharedTreeTable(serverIo, treeKey);
|
|
3192
|
-
const server = new Server(route, serverIo, serverBsMem);
|
|
4407
|
+
const server = new Server(route, serverIo, serverBsMem, { stamp: { domain: "test", hub: "hub" } });
|
|
3193
4408
|
await server.init();
|
|
3194
4409
|
const [serverSocketA, clientSocketA] = createSocketPair();
|
|
3195
4410
|
serverSocketA.connect();
|
|
@@ -3226,22 +4441,24 @@ async function runClientServerSetup(opts = {}) {
|
|
|
3226
4441
|
return { baseDir, folderA, folderB, contentB, cleanup };
|
|
3227
4442
|
}
|
|
3228
4443
|
export {
|
|
3229
|
-
|
|
3230
|
-
|
|
4444
|
+
ATOMIC_TMP_PREFIX,
|
|
4445
|
+
FS_EDIT_ACTION,
|
|
3231
4446
|
FsAgent,
|
|
3232
|
-
FsAntiEntropy,
|
|
3233
4447
|
FsBlobAdapter,
|
|
3234
|
-
FsConflictResolver,
|
|
3235
4448
|
FsDbAdapter,
|
|
4449
|
+
FsEditChain,
|
|
3236
4450
|
FsScanner,
|
|
4451
|
+
FsSignals,
|
|
4452
|
+
SIGNAL_LOG_FILE,
|
|
4453
|
+
SIGNAL_LOG_MAX,
|
|
4454
|
+
SIGNAL_ONCE_MAX,
|
|
4455
|
+
SIGNAL_PATHS_MAX,
|
|
3237
4456
|
SYNC_ERROR_FILE,
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
runClientServerSetup,
|
|
3246
|
-
threeWayMerge
|
|
4457
|
+
atomicTmpPath,
|
|
4458
|
+
atomicWriteFile,
|
|
4459
|
+
atomicWriteStream,
|
|
4460
|
+
compileIgnore,
|
|
4461
|
+
createFsChainTables,
|
|
4462
|
+
globToRegExp,
|
|
4463
|
+
runClientServerSetup
|
|
3247
4464
|
};
|