@rljson/fs-agent 0.0.85 → 0.1.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.
@@ -0,0 +1,159 @@
1
+ /**
2
+ * How many buckets a manifest is divided into.
3
+ *
4
+ * **Must be identical on every node**, so it is a constant and never scaled to
5
+ * folder size: two nodes that bucketed differently cannot compare anything.
6
+ */
7
+ export declare const BUCKET_COUNT = 4096;
8
+ /** The blob id a TOMBSTONED path is advertised with. */
9
+ export declare const TOMBSTONE_BLOB = "";
10
+ /**
11
+ * One manifest entry: a path, the blob holding its content, and whether the
12
+ * sender's own HISTORY says it edited that path.
13
+ *
14
+ * **The claim is the whole point of the third element.** Without it a same-path
15
+ * conflict is settled by comparing content hashes (see `reconcile`), which
16
+ * converges on the greater hash and has nothing to do with who edited last —
17
+ * measured as a writer at version 8 and a peer still holding version 5 ending
18
+ * up on version 5, about half the time, the writer's own folder included.
19
+ *
20
+ * **It is deliberately NOT part of {@link digestOf}.** The bucket roots must
21
+ * depend on content alone: two nodes holding identical bytes have to agree
22
+ * their buckets match, whatever either of them claims about who wrote them.
23
+ * Folding the claim in would make a node see differences that are not there,
24
+ * which is the one failure the roots exist to avoid.
25
+ *
26
+ * Absent means "the sender did not say", which is how an older peer's two-element
27
+ * entry arrives — and then the hash rule decides, exactly as before.
28
+ */
29
+ export type ManifestEntry = readonly [
30
+ path: string,
31
+ blobId: string,
32
+ claimed?: 0 | 1,
33
+ /**
34
+ * `timeId` of the newest edit the sender knows of for this path — the write
35
+ * that produced the blob, or the removal that produced the tombstone.
36
+ *
37
+ * WHAT A MANIFEST COULD NOT SAY BEFORE. A manifest states what a node
38
+ * HOLDS; it never stated when the node decided. So a tombstone was authority
39
+ * on its own, and a deletion made before a re-creation still won. Measured
40
+ * by `I7b: a delivered deletion does not beat a later re-creation`.
41
+ *
42
+ * It is not the claim: a claim says WHO, and two nodes that both claim a
43
+ * path still need to know which claim is later. It is also not a wall-clock
44
+ * reading taken here — it is the identity of an edit in the chain, minted
45
+ * once by whoever made it, so both sides of a round order it identically.
46
+ *
47
+ * Absent means "the sender did not say", exactly as for {@link claimed}: an
48
+ * older peer sends two or three elements and the rules that shipped before
49
+ * decide, unchanged. **Deliberately not part of {@link digestOf}**, for the
50
+ * same reason the claim is not — bucket roots must depend on content alone.
51
+ */
52
+ editedAt?: string
53
+ ];
54
+ /** `bucketIndex → root`, non-empty buckets only. */
55
+ export type BucketRoots = Readonly<Record<number, string>>;
56
+ /**
57
+ * Which bucket a path belongs to.
58
+ *
59
+ * On the PATH alone, never on the content: a file whose content changes must
60
+ * stay in the same bucket, or a modification would look like a delete in one
61
+ * bucket and an add in another — two differences where there is one.
62
+ * @param path - The relative path, `/`-separated.
63
+ * @returns A bucket index in `[0, BUCKET_COUNT)`.
64
+ */
65
+ export declare const bucketOf: (path: string) => number;
66
+ /**
67
+ * The per-bucket roots of a manifest.
68
+ *
69
+ * XOR, so a root does not depend on the order its entries were visited in —
70
+ * two nodes that walked their folders differently must still agree.
71
+ *
72
+ * Sparse: a bucket with no entries is ABSENT rather than zero. An empty bucket
73
+ * and a bucket whose digests happen to cancel are not the same thing, and only
74
+ * one of them is worth a slot on the wire.
75
+ * @param manifest - `path → blobId`, tombstones included with
76
+ * {@link TOMBSTONE_BLOB}.
77
+ * @returns `bucketIndex → root`, non-empty buckets only.
78
+ */
79
+ export declare const bucketRoots: (manifest: ReadonlyMap<string, string>) => BucketRoots;
80
+ /**
81
+ * The buckets two sides disagree about.
82
+ *
83
+ * A bucket present on one side and absent on the other differs: absent means
84
+ * empty, and empty is not equal to anything with content in it.
85
+ * @param ours - Our roots.
86
+ * @param theirs - The peer's roots.
87
+ * @returns Bucket indices to exchange entries for, ascending.
88
+ */
89
+ export declare const differingBuckets: (ours: BucketRoots, theirs: BucketRoots) => number[];
90
+ /**
91
+ * The entries of a manifest that fall in the given buckets.
92
+ * @param manifest - `path → blobId`.
93
+ * @param buckets - Bucket indices wanted.
94
+ * @param claimed - Paths this node's history says it EDITED. Marked on the
95
+ * entry so a peer can settle a same-path conflict by who wrote the file
96
+ * rather than by which content hash sorts higher. Never folded into the
97
+ * bucket digest — see {@link ManifestEntry}.
98
+ * @returns The entries, sorted by path so two nodes serialise them alike.
99
+ * @param editTimes - `path → timeId` of the newest edit known for each path,
100
+ * which fills `ManifestEntry.editedAt`. Empty means the sender cannot date
101
+ * its edits, and the entries then carry no time.
102
+ */
103
+ export declare const entriesInBuckets: (manifest: ReadonlyMap<string, string>, buckets: readonly number[], claimed?: ReadonlySet<string>, editTimes?: ReadonlyMap<string, string>) => ManifestEntry[];
104
+ /** What one side should do about a peer's entries. */
105
+ export interface ReconcilePlan {
106
+ /**
107
+ * Paths to fetch from the peer, with the blob to fetch.
108
+ *
109
+ * Additive, always: the peer has content we lack. Nothing here overwrites
110
+ * anything — a path we hold with DIFFERENT content is a conflict, not a
111
+ * fetch, and it is reported separately.
112
+ */
113
+ fetch: ManifestEntry[];
114
+ /**
115
+ * Paths the peer has TOMBSTONED that we still hold live.
116
+ *
117
+ * The delete-wins direction. Applying them is destructive and therefore
118
+ * bounded elsewhere; this function only says which they are.
119
+ */
120
+ drop: string[];
121
+ /**
122
+ * Paths WE have tombstoned that the peer still holds live.
123
+ *
124
+ * The other delete-wins direction. Our tombstone has to be re-advertised, or
125
+ * the two sides sit at different manifests for ever whenever a delete is
126
+ * missed — mongo's `redelete`, and the exact failure its demo hit.
127
+ */
128
+ redelete: string[];
129
+ /**
130
+ * Paths both sides hold with DIFFERENT content.
131
+ *
132
+ * Reported for every conflict, whether or not this side adopts the peer's
133
+ * version, so a caller can preserve the losing content as a conflict copy
134
+ * and so the event is visible rather than silent.
135
+ *
136
+ * It is also RESOLVED, deterministically — see {@link reconcile}. Naming it
137
+ * and doing nothing was tried: three clients editing one file then never
138
+ * converge, because nothing decides and an additive step cannot. A sync
139
+ * engine that leaves three versions in place has not reconciled anything.
140
+ */
141
+ conflict: string[];
142
+ }
143
+ /**
144
+ * What to do about a peer's entries for the buckets we disagreed about.
145
+ *
146
+ * **Additive by construction.** The only outcomes it can produce are "fetch
147
+ * something we lack", "adopt the peer's side of a conflict", "drop something
148
+ * the peer proved it deleted" and "re-assert a deletion of our own". There is
149
+ * no outcome in which one side's FOLDER replaces the other's, which is the
150
+ * property that makes the two measured failures impossible instead of merely
151
+ * rarer — a conflict is resolved one path at a time, never by wholesale.
152
+ * @param ours - Our entries for those buckets, tombstones included.
153
+ * @param theirs - The peer's entries for those buckets.
154
+ * @param claimed - Paths THIS node's history says it edited. The peer's own
155
+ * claims ride in its entries, so both sides are known here and the rule is
156
+ * symmetric — see the conflict branch.
157
+ * @returns The plan. Every list is sorted, so two nodes agree on its contents.
158
+ */
159
+ export declare const reconcile: (ours: readonly ManifestEntry[], theirs: readonly ManifestEntry[], claimed?: ReadonlySet<string>) => ReconcilePlan;
@@ -68,6 +68,21 @@ export type FsChangeCallback = (change: FsChange) => void | Promise<void>;
68
68
  /**
69
69
  * Options for scanning
70
70
  */
71
+ /**
72
+ * Default for {@link FsScanOptions.settleMs}.
73
+ *
74
+ * Matched to the agent's debounce: below it a scan can still catch a copy
75
+ * mid-flight, and above it every new file pays latency for a hazard that is
76
+ * already covered.
77
+ */
78
+ export declare const DEFAULT_SETTLE_MS = 100;
79
+ /**
80
+ * Default for {@link FsScanOptions.settleMinBytes}.
81
+ *
82
+ * One megabyte: above the size anything is written in a single operation, and
83
+ * at the order where a copy takes long enough for a scan to land inside it.
84
+ */
85
+ export declare const DEFAULT_SETTLE_MIN_BYTES: number;
71
86
  export interface FsScanOptions {
72
87
  /** Patterns to ignore (glob patterns) */
73
88
  ignore?: string[];
@@ -88,6 +103,42 @@ export interface FsScanOptions {
88
103
  * after a restart. Omit to disable (default: full read+hash every scan).
89
104
  */
90
105
  scanCachePath?: string;
106
+ /**
107
+ * How long to wait before coming back for a file that was still being
108
+ * written.
109
+ *
110
+ * A copy takes seconds, and for those seconds the file on disk is a PREFIX
111
+ * of the real one. Reading it there produces a blob of the prefix, and a
112
+ * blob is what gets announced — so the fleet is told a truncated file is the
113
+ * complete state, and on every peer it then IS the complete state.
114
+ *
115
+ * Measured before this existed: a 2 MB file written in 8 slices was hashed
116
+ * at 262 144 bytes, matching the field report exactly — *"eine große Datei
117
+ * wird 0,3 Sekunden nach dem ersten Byte gelesen und als vollständiger Stand
118
+ * an alle verteilt"*.
119
+ *
120
+ * The cost is latency: a new file waits this long before it can propagate.
121
+ * Kept at the same order as the agent's debounce so it adds nothing a user
122
+ * would notice, and a deferral schedules its own follow-up scan rather than
123
+ * waiting for the five-second safety rescan.
124
+ */
125
+ settleMs?: number;
126
+ /**
127
+ * Below this size a file is never held back for settling.
128
+ *
129
+ * The two halves of the rule cost different things. Asking "did it change
130
+ * since this scan began" is free and catches a write that lands while the
131
+ * scan runs. Asking "has it been quiet for a moment" catches a writer whose
132
+ * gaps are wider than one scan — and costs every file that much latency.
133
+ *
134
+ * So the second half is spent only where the hazard is, which the register
135
+ * names: *"eine große Datei wird 0,3 Sekunden nach dem ersten Byte gelesen
136
+ * und als vollständiger Stand an alle verteilt"*. A document somebody saves
137
+ * is written in one go and propagates as fast as it ever did; a
138
+ * multi-megabyte copy waits a moment longer, and the alternative for it is
139
+ * being published truncated.
140
+ */
141
+ settleMinBytes?: number;
91
142
  }
92
143
  /**
93
144
  * Scans and watches file system changes, extracting RLJSON tree structure
@@ -98,6 +149,15 @@ export declare class FsScanner {
98
149
  private _watcher;
99
150
  private _changeCallbacks;
100
151
  private _options;
152
+ /**
153
+ * The ignore list, compiled once.
154
+ *
155
+ * Compiled rather than re-read per entry because a scan of a production
156
+ * catalogue asks this question once per file, and a glob is a regular
157
+ * expression that should be built once. `fs-ignore.ts` carries the
158
+ * compatibility rule that keeps every prefix pattern working.
159
+ */
160
+ private readonly _ignoreMatcher;
101
161
  private _bs;
102
162
  private _paused;
103
163
  private _missedChangesDuringPause;
@@ -111,6 +171,31 @@ export declare class FsScanner {
111
171
  private _stopRequested;
112
172
  /** Path→content cache backing {@link FsScanOptions.scanCachePath} (unused when unset). */
113
173
  private _scanCachePath?;
174
+ /**
175
+ * Paths this scan refused to read because they were still being written.
176
+ *
177
+ * Counted so {@link scan} knows to come back, and reported so a folder that
178
+ * never settles is diagnosable rather than mysteriously stale.
179
+ */
180
+ private _unsettledDuringScan;
181
+ /**
182
+ * When the scan now running began.
183
+ *
184
+ * A file whose timestamp is newer than this is still being written: the
185
+ * bytes moved while this scan was in progress. See the gate in
186
+ * {@link _scanDirectory}.
187
+ */
188
+ private _scanStartedAt;
189
+ /**
190
+ * Large files whose size this scanner has seen but not yet seen settle.
191
+ *
192
+ * path → the size observed last time. A file leaves the map the scan after
193
+ * its size stops changing, which is when it is finally read. Bounded by the
194
+ * number of large files being written at once, which is a handful.
195
+ */
196
+ private readonly _growing;
197
+ /** Pending follow-up scan for {@link _unsettledDuringScan}. */
198
+ private _settleTimer;
114
199
  /** Last-scan cache (loaded from disk); consulted to skip re-read/re-hash. */
115
200
  private _blobCache;
116
201
  /** Cache rebuilt during the CURRENT scan; becomes `_blobCache` at the end (self-pruning). */
@@ -146,12 +231,12 @@ export declare class FsScanner {
146
231
  *
147
232
  * `fs.watch` in recursive mode reports a path RELATIVE TO THE ROOT
148
233
  * (`sub/dir/.fsagent-tmp-abc`), while the ignore patterns are basenames.
149
- * {@link _shouldIgnore} tests `startsWith`, so a nested match never fired:
234
+ * The matcher tested a basename only, so a nested match never fired:
150
235
  * every atomic write the agent itself makes during a restore came back as a
151
236
  * change event, each event triggered a scan, and the debounce that batches a
152
237
  * push was reset before it could fire.
153
238
  *
154
- * Measured on the customer's folder: after a 3 642-file restore the watcher
239
+ * Measured on a large production folder: after a 3 642-file restore the watcher
155
240
  * reported the SAME newly added file nine times and the agent never emitted a
156
241
  * ref for it — `[fs] added: …/probe-….txt` nine times, no `sync:out`. The
157
242
  * file did not fail to arrive; it was never sent.
@@ -159,10 +244,12 @@ export declare class FsScanner {
159
244
  * Every segment is tested, because the pattern may match a directory as
160
245
  * easily as a file.
161
246
  * @param relativePath - Path as the watcher reports it.
162
- * @returns True when any segment matches an ignore pattern.
247
+ * @param isDirectory - Whether the path is a directory, when the caller
248
+ * knows. A directory-only pattern (`build/`) needs it; the watcher cannot
249
+ * say, and not knowing never widens what is ignored.
250
+ * @returns True when the ignore list covers this path.
163
251
  */
164
252
  private _shouldIgnorePath;
165
- private _shouldIgnore;
166
253
  watch(): Promise<void>;
167
254
  /**
168
255
  * One safety-rescan pass: rescans the tree and, if its content differs from
@@ -170,6 +257,38 @@ export declare class FsScanner {
170
257
  * notification so syncToDb reconciles the drift. Paused/stopped scanners and
171
258
  * scan failures are no-ops.
172
259
  */
260
+ /**
261
+ * Re-reads the folder once a file this scan would not read has settled.
262
+ *
263
+ * Through the coalescer, like the safety rescan, so a settle landing inside
264
+ * a burst does not add a whole extra pass. Notifies unconditionally: the
265
+ * caller already knows something was deferred, and the point is to get the
266
+ * file out now rather than on the five-second rescan.
267
+ * @param path - The path that was deferred, for the change event.
268
+ */
269
+ /**
270
+ * Carries a file's PREVIOUS node into the scan being built, because the file
271
+ * on disk right now is still being written.
272
+ *
273
+ * A path simply left out of a tree reads as a DELETION to every peer that
274
+ * holds it, so a user saving over a document would have it deleted
275
+ * everywhere. Reusing the last node says the truthful thing instead: as far
276
+ * as the network is concerned this change has not happened yet.
277
+ *
278
+ * A file nobody has ever seen has no previous node and IS left out, which is
279
+ * correct — it cannot be a deletion of something no peer holds.
280
+ *
281
+ * The node must go into `trees` as well as into the parent's children. It is
282
+ * the kind of thing that looks redundant and is not: leaving it out gave the
283
+ * root a child hash with no node behind it, and the whole folder came out
284
+ * empty.
285
+ * @param relativePath - The deferred path.
286
+ * @param trees - The node map this scan is building.
287
+ * @param childTrees - The parent's child nodes.
288
+ * @param childRefs - The parent's child hashes.
289
+ */
290
+ private _reuse;
291
+ private _rescanAfterSettle;
173
292
  private _runSafetyRescan;
174
293
  /**
175
294
  * Path+blobId content fingerprint used by the safety rescan to detect drift
@@ -209,12 +328,12 @@ export declare class FsScanner {
209
328
  * callback, so those scans all run AT ONCE. Copying 1 200 tiny files into a
210
329
  * watched folder took 1 200 concurrent full scans: the CPU sat 82% idle
211
330
  * waiting on the filesystem, RSS climbed from 263 MB to 785 MB, and after two
212
- * minutes the peer had received nothing. On the customer's 3 702-file folder
331
+ * minutes the peer had received nothing. On a 3 702-file folder
213
332
  * the same burst wedged the client outright.
214
333
  *
215
334
  * Started-after is the part that cannot be traded away. Joining a scan that
216
335
  * began BEFORE the event would let a push carry a tree that predates the file
217
- * that triggered it — which is precisely the partial trees the lab saw
336
+ * that triggered it — which is precisely the partial trees a real fleet saw
218
337
  * advertised: 64 nodes, then 103, then 204, each a stale snapshot of a folder
219
338
  * that already held twelve hundred files. So a caller either starts a scan
220
339
  * now, or waits for the one that begins when the current pass ends. A burst
@@ -235,6 +354,22 @@ export declare class FsScanner {
235
354
  */
236
355
  private _pauseLooksStuck;
237
356
  private _notifyChange;
357
+ /**
358
+ * What the last completed scan saw on disk for one path.
359
+ *
360
+ * The agent asks this to decide whether a restore may skip writing a file:
361
+ * a matching blobId means the bytes are already right, and the recorded
362
+ * size and mtime are what a `stat` is checked against. Reading it from here
363
+ * rather than from the tree is deliberate — mtime is no longer part of a
364
+ * tree node, precisely so refs do not depend on it.
365
+ * @param relativePath - Path relative to the scan root.
366
+ * @returns What the scan recorded, or `undefined` if it saw no such file.
367
+ */
368
+ knownFile(relativePath: string): {
369
+ mtime: number;
370
+ size: number;
371
+ blobId: string;
372
+ } | undefined;
238
373
  onChange(callback: FsChangeCallback): void;
239
374
  offChange(callback: FsChangeCallback): void;
240
375
  stopWatch(): void;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
- export { FsAgent, SYNC_ERROR_FILE, type FsAgentOptions, type RestoreOptions, type TimeoutConfig, } from './fs-agent.ts';
2
- export { antiEntropyDecision, DEFAULT_ANTI_ENTROPY, FsAntiEntropy, type AntiEntropyAction, type AntiEntropyDecision, type AntiEntropyDeps, type AntiEntropyOptions, type AntiEntropyStatus, type AntiEntropyView, type HubAnnouncement, } from './fs-anti-entropy.ts';
1
+ export { FsAgent, REFUSED_DELETION_LOG_MAX, SYNC_ERROR_FILE, type FsAgentOptions, type RefusedDeletion, type RestoreOptions, type TimeoutConfig, } from './fs-agent.ts';
2
+ export { ATOMIC_TMP_PREFIX, atomicTmpPath, atomicWriteFile, atomicWriteStream, } from './fs-atomic-write.ts';
3
+ export { compileIgnore, globToRegExp, type IgnoreMatcher, } from './fs-ignore.ts';
4
+ export { antiEntropyDecision, DEFAULT_ANTI_ENTROPY, FsAntiEntropy, type AntiEntropyAction, type AntiEntropyDecision, type AntiEntropyDeps, type AntiEntropyOptions, type AntiEntropyStatus, type AntiEntropyView, type HubAnnouncement, type Reachability, } from './fs-anti-entropy.ts';
5
+ export { BE, BG, BQ, BR, BUCKET_SYNC_PREFIXES, decodeEntries, decodeRoots, decodeWanted, encodeEntries, encodeRoots, encodeWanted, FsBucketSync, isBucketSync, type BucketSyncHost, } from './fs-bucket-sync.ts';
6
+ export { BUCKET_COUNT, bucketOf, bucketRoots, differingBuckets, entriesInBuckets, reconcile, TOMBSTONE_BLOB, type BucketRoots, type ManifestEntry, type ReconcilePlan, } from './fs-manifest.ts';
7
+ export { createFsChainTables, FS_EDIT_ACTION, FsEditChain, compareTimeId, planRemovals, type FsAppendOptions, type FsChainEntry, type FsEditData, type RemovalPlan, type RemovalQuestion, } from './fs-edit-chain.ts';
3
8
  export { FsBlobAdapter, type BlobToFileOptions, type FileBlobMeta, type FileToBlobOptions, } from './fs-blob-adapter.ts';
4
9
  export { FsDbAdapter, type StoreFsTreeOptions } from './fs-db-adapter.ts';
5
10
  export { compareTips, conflictCopyName, decideWinner, DIR_MARKER, findCommonAncestor, formatConflictTimestamp, FsConflictResolver, fsTreeToContentMap, threeWayMerge, type BranchTip, type ConflictCopy, type ConflictResolverDeps, type ContentMap, type MergePlan, } from './fs-conflict-resolver.ts';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rljson/fs-agent",
3
- "version": "0.0.85",
3
+ "version": "0.1.0",
4
4
  "description": "Rljson fs-agent description",
5
5
  "homepage": "https://github.com/rljson/fs-agent",
6
6
  "bugs": "https://github.com/rljson/fs-agent/issues",
@@ -28,7 +28,7 @@
28
28
  "updateGoldens": "cross-env UPDATE_GOLDENS=true pnpm test"
29
29
  },
30
30
  "devDependencies": {
31
- "@rljson/server": "0.0.71",
31
+ "@rljson/server": "0.0.74",
32
32
  "@types/node": "^25.3.1",
33
33
  "@typescript-eslint/eslint-plugin": "^8.56.1",
34
34
  "@typescript-eslint/parser": "^8.56.1",
@@ -50,10 +50,10 @@
50
50
  "vitest-dom": "^0.1.1"
51
51
  },
52
52
  "dependencies": {
53
- "@rljson/bs": "0.0.27",
54
- "@rljson/db": "0.0.48",
53
+ "@rljson/bs": "0.0.29",
54
+ "@rljson/db": "0.0.52",
55
55
  "@rljson/hash": "0.0.19",
56
- "@rljson/io": "0.0.80",
56
+ "@rljson/io": "0.0.84",
57
57
  "@rljson/json": "0.0.23",
58
58
  "@rljson/rljson": "0.0.83",
59
59
  "socket.io": "^4.8.3",
@@ -64,13 +64,13 @@
64
64
  "esbuild"
65
65
  ],
66
66
  "overrides": {
67
- "@rljson/bs": "0.0.27",
68
- "@rljson/db": "0.0.48",
67
+ "@rljson/bs": "0.0.29",
68
+ "@rljson/db": "0.0.52",
69
69
  "@rljson/hash": "0.0.19",
70
- "@rljson/io": "0.0.80",
70
+ "@rljson/io": "0.0.84",
71
71
  "@rljson/json": "0.0.23",
72
72
  "@rljson/rljson": "0.0.83",
73
- "@rljson/server": "0.0.71"
73
+ "@rljson/server": "0.0.74"
74
74
  }
75
75
  },
76
76
  "packageManager": "pnpm@10.11.0"