@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/README.public.md
CHANGED
|
@@ -8,919 +8,532 @@ found in the LICENSE file in the root of this package.
|
|
|
8
8
|
|
|
9
9
|
# @rljson/fs-agent
|
|
10
10
|
|
|
11
|
-
> **
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
-
|
|
23
|
-
-
|
|
24
|
-
-
|
|
25
|
-
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
-
|
|
30
|
-
|
|
31
|
-
|
|
11
|
+
> **Keeps a folder on several machines the same, without a central authority
|
|
12
|
+
> deciding what the folder contains.**
|
|
13
|
+
|
|
14
|
+
Each machine watches its own folder, writes down what changed, and tells the
|
|
15
|
+
others. There is no master copy: a hub relays, it does not arbitrate. Two
|
|
16
|
+
people editing at once get one agreed result with both versions kept, and a
|
|
17
|
+
machine switched off for a week catches up without replaying the week.
|
|
18
|
+
|
|
19
|
+
- [What it is, in one page](#what-it-is-in-one-page)
|
|
20
|
+
- [Install](#install)
|
|
21
|
+
- [Quick start](#quick-start)
|
|
22
|
+
- [Starting and stopping](#starting-and-stopping)
|
|
23
|
+
- [Configuration](#configuration)
|
|
24
|
+
- [Ignore patterns](#ignore-patterns)
|
|
25
|
+
- [Knowing what happened to the folder](#knowing-what-happened-to-the-folder)
|
|
26
|
+
- [Reading what the agent is doing](#reading-what-the-agent-is-doing)
|
|
27
|
+
- [Using it without sync](#using-it-without-sync)
|
|
28
|
+
- [What it guarantees β and what it does not](#what-it-guarantees--and-what-it-does-not)
|
|
29
|
+
- [Troubleshooting](#troubleshooting)
|
|
30
|
+
- [Known constraints](#known-constraints)
|
|
31
|
+
- [Further reading](#further-reading)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## What it is, in one page
|
|
36
|
+
|
|
37
|
+
Three things, and the third is the one that matters.
|
|
38
|
+
|
|
39
|
+
**A folder becomes a tree.** The scanner walks the folder and produces an
|
|
40
|
+
RLJSON tree: one node per directory, one entry per file, each file's bytes in
|
|
41
|
+
content-addressed blob storage. Two files with the same bytes are stored once,
|
|
42
|
+
anywhere in the fleet. The tree has a **ref** β a content hash β and two
|
|
43
|
+
machines holding the same bytes compute the same ref. A file's modification
|
|
44
|
+
time is deliberately *not* part of that identity, because it does not survive a
|
|
45
|
+
restore byte for byte and on Windows regularly does not.
|
|
46
|
+
|
|
47
|
+
**A change becomes an edit.** Every change a machine makes is written into an
|
|
48
|
+
**edit chain**: what changed, what was removed, when, and which state it
|
|
49
|
+
followed. The chain is one shared history, identical on every machine, and it
|
|
50
|
+
is the only thing that answers a question. The filesystem is an *event source
|
|
51
|
+
only* β the watcher says something happened, and what that means is read from
|
|
52
|
+
the chain.
|
|
53
|
+
|
|
54
|
+
**That is why a deletion works.** An absence is not a deletion. A tree lacks a
|
|
55
|
+
path because the sender removed it, or because the sender never had it, and a
|
|
56
|
+
content hash cannot tell the two apart. So a machine deletes a file for one
|
|
57
|
+
reason only: the edit that lacks it **descends from what this machine holds** β
|
|
58
|
+
its author had the file and chose not to. Anywhere else an absence reaches the
|
|
59
|
+
folder only through a three-way merge, which knows what each side did.
|
|
60
|
+
|
|
61
|
+
Consequences worth knowing before you start:
|
|
62
|
+
|
|
63
|
+
| | |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| **A deletion is a fact, not a gap** | so it survives a partition, a restart, and a peer who never heard about it |
|
|
66
|
+
| **A receiver never claims authorship** | so a machine catching up cannot out-order the person who actually typed |
|
|
67
|
+
| **A conflict keeps both versions** | the version that reached the fleet later keeps the name β by the hub's stamp, never by a clock β the other is kept as a renamed copy, and the conflict is reported |
|
|
68
|
+
| **Nothing is pruned on a peer's authority** | only an edit that descends from this machine's own state can delete anything here |
|
|
69
|
+
| **A joining machine applies the history first** | and a file the history deliberately deleted is moved aside, not resurrected and not destroyed |
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Install
|
|
32
74
|
|
|
33
75
|
```bash
|
|
34
76
|
npm install @rljson/fs-agent
|
|
35
77
|
```
|
|
36
78
|
|
|
37
|
-
|
|
79
|
+
Peers: `@rljson/rljson`, `@rljson/db`, `@rljson/io`, `@rljson/bs`,
|
|
80
|
+
`@rljson/server`. Node 22 or newer.
|
|
81
|
+
|
|
82
|
+
---
|
|
38
83
|
|
|
39
|
-
|
|
84
|
+
## Quick start
|
|
40
85
|
|
|
41
|
-
|
|
86
|
+
**This is the production configuration.** Every option is here for the reason
|
|
87
|
+
named beside it; a setup without them runs, and quietly gives up guarantees you
|
|
88
|
+
probably want.
|
|
42
89
|
|
|
43
90
|
```typescript
|
|
44
91
|
import { FsAgent } from '@rljson/fs-agent';
|
|
92
|
+
import { BsMem } from '@rljson/bs';
|
|
45
93
|
import { Connector, Db } from '@rljson/db';
|
|
46
94
|
import { IoMem, SocketMock } from '@rljson/io';
|
|
47
|
-
import {
|
|
48
|
-
import { Route, createTreesTableCfg } from '@rljson/rljson';
|
|
95
|
+
import { createTreesTableCfg, Route } from '@rljson/rljson';
|
|
49
96
|
|
|
50
|
-
//
|
|
97
|
+
// --- the database the folder is mirrored through -------------------------
|
|
51
98
|
const io = new IoMem();
|
|
52
99
|
await io.init();
|
|
53
100
|
const db = new Db(io);
|
|
54
101
|
|
|
55
|
-
//
|
|
102
|
+
// The table name MUST end in `Tree`. That suffix is what selects the
|
|
103
|
+
// filesystem engine at runtime β it is not a naming convention.
|
|
56
104
|
const treeKey = 'projectFilesTree';
|
|
57
|
-
|
|
58
|
-
await db.core.createTableWithInsertHistory(treeTableCfg);
|
|
105
|
+
await db.core.createTableWithInsertHistory(createTreesTableCfg(treeKey));
|
|
59
106
|
|
|
60
|
-
//
|
|
107
|
+
// --- the agent ----------------------------------------------------------
|
|
61
108
|
const agent = new FsAgent('./my-project', new BsMem(), {
|
|
62
|
-
ignore: ['node_modules', '.git', 'dist'],
|
|
63
|
-
maxDepth: 10,
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
// Create Connector for socket-based synchronization
|
|
67
|
-
const socket = new SocketMock();
|
|
68
|
-
const route = Route.fromFlat(`/${treeKey}`);
|
|
69
|
-
const connector = new Connector(db, route, socket);
|
|
109
|
+
ignore: ['node_modules', '.git', 'dist', '*.log'],
|
|
70
110
|
|
|
71
|
-
//
|
|
72
|
-
|
|
111
|
+
// Told, not discovered: everything a person might care about, from a
|
|
112
|
+
// conflict to a refused deletion.
|
|
113
|
+
onSignal: (signal) => console.warn(signal.kind, signal.paths),
|
|
73
114
|
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
// β Extracts tree structures from directories
|
|
77
|
-
// β Stores file content in blob storage
|
|
78
|
-
// β Broadcasts changes via Connector
|
|
79
|
-
|
|
80
|
-
// When you're done:
|
|
81
|
-
stopSync();
|
|
82
|
-
agent.dispose();
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
### Bidirectional Sync
|
|
86
|
-
|
|
87
|
-
Enable two-way synchronization so changes in the database also update the filesystem:
|
|
88
|
-
|
|
89
|
-
```typescript
|
|
90
|
-
import { Connector } from '@rljson/db';
|
|
91
|
-
import { Route } from '@rljson/rljson';
|
|
92
|
-
import { SocketMock } from '@rljson/io';
|
|
93
|
-
|
|
94
|
-
const agent = new FsAgent('./my-project', new BsMem(), {
|
|
95
|
-
ignore: ['node_modules', '.git', 'dist'],
|
|
115
|
+
// So a restart does not re-read and re-hash the whole folder.
|
|
116
|
+
scanCachePath: '.cache/fs-agent-scan.json',
|
|
96
117
|
});
|
|
97
118
|
|
|
98
|
-
//
|
|
119
|
+
// --- the transport ------------------------------------------------------
|
|
99
120
|
const socket = new SocketMock();
|
|
100
121
|
const route = Route.fromFlat(`/${treeKey}`);
|
|
101
|
-
const connector = new Connector(db, route, socket
|
|
122
|
+
const connector = new Connector(db, route, socket, {
|
|
123
|
+
// `includeClientIdentity` lets the hub tell a machine saying its head
|
|
124
|
+
// again from an echo; `causalOrdering` gives the hub a log to fill gaps from.
|
|
125
|
+
causalOrdering: true,
|
|
126
|
+
includeClientIdentity: true,
|
|
127
|
+
});
|
|
102
128
|
|
|
103
|
-
//
|
|
104
|
-
|
|
129
|
+
// The HUB must stamp what it relays β `new Server(route, io, bs,
|
|
130
|
+
// { stamp: { domain, hub } })` in `@rljson/server`. The stamp is what decides
|
|
131
|
+
// which of two versions of one file keeps its name; without it such a
|
|
132
|
+
// conflict waits, both versions kept, and says so as `repair/blocked`.
|
|
105
133
|
|
|
106
|
-
//
|
|
134
|
+
// --- start: RECEIVE FIRST, then push ------------------------------------
|
|
135
|
+
// A machine that announces before it can hear speaks about a state it may be
|
|
136
|
+
// about to replace.
|
|
107
137
|
const stopFromDb = await agent.syncFromDb(db, connector, treeKey);
|
|
138
|
+
const stopToDb = await agent.syncToDb(db, connector, treeKey);
|
|
108
139
|
|
|
109
|
-
//
|
|
110
|
-
// 1. Filesystem changes β automatically synced to database
|
|
111
|
-
// 2. Database changes β automatically synced to filesystem
|
|
112
|
-
// 3. Loop prevention ensures no infinite sync cycles
|
|
113
|
-
// 4. Both sides stay perfectly synchronized
|
|
114
|
-
|
|
115
|
-
// Stop syncing
|
|
140
|
+
// ... later
|
|
116
141
|
stopToDb();
|
|
117
142
|
stopFromDb();
|
|
143
|
+
agent.dispose();
|
|
118
144
|
```
|
|
119
145
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
### Tree Structures
|
|
123
|
-
|
|
124
|
-
`fs-agent` represents your filesystem as RLJSON tree structures:
|
|
125
|
-
|
|
126
|
-
```typescript
|
|
127
|
-
// Directory hierarchy:
|
|
128
|
-
// my-project/
|
|
129
|
-
// βββ src/
|
|
130
|
-
// β βββ index.ts
|
|
131
|
-
// β βββ utils.ts
|
|
132
|
-
// βββ package.json
|
|
133
|
-
|
|
134
|
-
// Becomes a tree structure where:
|
|
135
|
-
// - Each file/directory is a tree node
|
|
136
|
-
// - Nodes are content-addressed (identified by hash)
|
|
137
|
-
// - Parent-child relationships are preserved
|
|
138
|
-
// - Changes are tracked via insert history
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
### Blob Storage
|
|
142
|
-
|
|
143
|
-
Files are stored efficiently using content-addressed blob storage:
|
|
146
|
+
### Against a `Client` from `@rljson/server`
|
|
144
147
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
148
|
+
What the host application does, and **the path that defaults to the
|
|
149
|
+
configuration above**. `fromClient` builds the `Db`, the `Connector` and the
|
|
150
|
+
blob store from an initialised client, adds two convenience wrappers, and
|
|
151
|
+
defaults `causalOrdering` and `includeClientIdentity` to `true`, because that is
|
|
152
|
+
the only mode this package measures end to end. Your own values still win if
|
|
153
|
+
you pass them.
|
|
149
154
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
### Automatic Synchronization (Constructor-based)
|
|
153
|
-
|
|
154
|
-
**Note:** Constructor-based automatic synchronization using `db`, `treeKey`, and `bidirectional` options is deprecated and will throw an error. Use the explicit `syncToDb()` and `syncFromDb()` methods with a `Connector` instance instead (see examples above).
|
|
155
|
-
|
|
156
|
-
The new approach provides better control and uses the Connector pattern for socket-based synchronization:
|
|
155
|
+
`new FsAgent(...)` keeps the primitive defaults β it is the building block, and
|
|
156
|
+
the quick start above sets them explicitly for exactly that reason.
|
|
157
157
|
|
|
158
158
|
```typescript
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
treeKey,
|
|
163
|
-
bidirectional: true,
|
|
159
|
+
const agent = await FsAgent.fromClient(folder, treeKey, client, socket, {
|
|
160
|
+
ignore,
|
|
161
|
+
scanCachePath,
|
|
164
162
|
});
|
|
165
163
|
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
const connector = new Connector(db, route, socket);
|
|
169
|
-
const stopToDb = await agent.syncToDb(db, connector, treeKey);
|
|
170
|
-
const stopFromDb = await agent.syncFromDb(db, connector, treeKey);
|
|
164
|
+
const stopFromDb = await agent.syncFromDbSimple();
|
|
165
|
+
const stopToDb = await agent.syncToDbSimple();
|
|
171
166
|
```
|
|
172
167
|
|
|
173
|
-
|
|
168
|
+
---
|
|
174
169
|
|
|
175
|
-
|
|
170
|
+
## Starting and stopping
|
|
176
171
|
|
|
177
|
-
|
|
178
|
-
pnpm exec vite-node src/live-client-server.ts
|
|
179
|
-
```
|
|
172
|
+
Three calls, and they are not interchangeable.
|
|
180
173
|
|
|
181
|
-
|
|
174
|
+
| call | starts | returns |
|
|
175
|
+
| --- | --- | --- |
|
|
176
|
+
| `syncFromDb(db, connector, treeKey)` | receiving β acting on the heads the network says | a `stop()` |
|
|
177
|
+
| `syncToDb(db, connector, treeKey)` | sending β watching the folder, authoring and announcing | a `stop()` |
|
|
178
|
+
| `dispose()` | β | nothing; **abandons a pending join** |
|
|
182
179
|
|
|
183
|
-
|
|
180
|
+
**Start receiving first.** A machine that pushes before it can receive
|
|
181
|
+
announces a state it may be about to replace, and on an established fleet that
|
|
182
|
+
is how a stale folder becomes the newest claim.
|
|
184
183
|
|
|
185
|
-
|
|
184
|
+
**Each `stop()` stops its own direction** β the watcher, the debounce, the
|
|
185
|
+
poll. Call both.
|
|
186
186
|
|
|
187
|
-
|
|
187
|
+
**`dispose()` is not the stopper.** It cancels a join this agent is still
|
|
188
|
+
waiting on. A folder that starts with files and no history defers its first
|
|
189
|
+
announcement and asks the network for its state repeatedly until a bounded wait
|
|
190
|
+
expires, and no `stop()` ends that β so a machine shut down mid-join keeps
|
|
191
|
+
asking a transport that is being torn down. Call it last, after both stops.
|
|
188
192
|
|
|
189
|
-
|
|
193
|
+
### What happens in the first few seconds
|
|
190
194
|
|
|
191
|
-
|
|
192
|
-
new FsAgent(rootPath: string, bs?: Bs, options?: FsAgentOptions)
|
|
193
|
-
```
|
|
195
|
+
Worth knowing, because it looks like a stall and is not.
|
|
194
196
|
|
|
195
|
-
**
|
|
197
|
+
1. **The folder is scanned.** A cold scan of a large catalogue is minutes, not
|
|
198
|
+
milliseconds. Pass `scanCachePath`.
|
|
199
|
+
2. **If the folder has files but no history, the agent says nothing yet.** It
|
|
200
|
+
asks the network for its state first (`joinWaitMs`, default 1 500 ms). This
|
|
201
|
+
is what stops a restored backup pushing a month of deleted files back to the
|
|
202
|
+
fleet.
|
|
203
|
+
3. **If a head arrives**, the agent reconciles against it: writes what it
|
|
204
|
+
lacks, keeps its own new work, moves anything the history deliberately
|
|
205
|
+
deleted into `.fsagent-recovered/`, and keeps a locally edited file as a
|
|
206
|
+
conflict copy.
|
|
207
|
+
4. **If nothing arrives** within the wait, this folder is the origin of its own
|
|
208
|
+
history and announces normally.
|
|
196
209
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
- `options` - Configuration options
|
|
210
|
+
If your folder *is* the origin β a fixture, a test, a brand-new network β set
|
|
211
|
+
`joinWaitMs: 0` and skip the wait honestly.
|
|
200
212
|
|
|
201
|
-
|
|
213
|
+
---
|
|
202
214
|
|
|
203
|
-
|
|
204
|
-
interface FsAgentOptions {
|
|
205
|
-
// Scanning options
|
|
206
|
-
ignore?: string[]; // Patterns to ignore (e.g., ['node_modules', '*.log'])
|
|
207
|
-
maxDepth?: number; // Maximum directory depth to scan
|
|
208
|
-
followSymlinks?: boolean; // Whether to follow symbolic links (default: false)
|
|
209
|
-
|
|
210
|
-
// Deprecated options (will throw error if used)
|
|
211
|
-
// Use syncToDb()/syncFromDb() methods with Connector instead
|
|
212
|
-
db?: Db; // DEPRECATED
|
|
213
|
-
treeKey?: string; // DEPRECATED
|
|
214
|
-
bidirectional?: boolean; // DEPRECATED
|
|
215
|
-
storageOptions?: StoreFsTreeOptions; // DEPRECATED
|
|
216
|
-
restoreOptions?: RestoreOptions; // DEPRECATED
|
|
217
|
-
}
|
|
218
|
-
maxDepth?: number; // Maximum directory depth (default: 10)
|
|
219
|
-
followSymlinks?: boolean; // Follow symbolic links (default: false)
|
|
220
|
-
|
|
221
|
-
// Automatic sync options
|
|
222
|
-
db?: Db; // Database instance for auto-sync
|
|
223
|
-
treeKey?: string; // Tree table key for storage
|
|
224
|
-
storageOptions?: {
|
|
225
|
-
// Options for database storage
|
|
226
|
-
includeBlobs?: boolean; // Include blob data in tree (default: true)
|
|
227
|
-
};
|
|
228
|
-
|
|
229
|
-
// Bidirectional sync
|
|
230
|
-
bidirectional?: boolean; // Enable database β filesystem sync (default: false)
|
|
231
|
-
|
|
232
|
-
// Restore options applied when syncing from DB (e.g., cleanTarget)
|
|
233
|
-
restoreOptions?: RestoreOptions;
|
|
234
|
-
}
|
|
235
|
-
```
|
|
236
|
-
|
|
237
|
-
#### Properties
|
|
238
|
-
|
|
239
|
-
```typescript
|
|
240
|
-
agent.rootPath: string // Root directory path
|
|
241
|
-
agent.bs: Bs // Blob storage instance
|
|
242
|
-
agent.scanner: FsScanner // File scanner instance
|
|
243
|
-
agent.adapter: FsBlobAdapter // Blob adapter instance
|
|
244
|
-
```
|
|
245
|
-
|
|
246
|
-
#### Methods
|
|
247
|
-
|
|
248
|
-
##### `extract(): Promise<FsTree>`
|
|
215
|
+
## Configuration
|
|
249
216
|
|
|
250
|
-
|
|
217
|
+
Everything `FsAgentOptions` accepts, its default, and what choosing otherwise
|
|
218
|
+
costs.
|
|
251
219
|
|
|
252
|
-
|
|
253
|
-
const tree = await agent.extract();
|
|
254
|
-
// Returns: { rootHash: string, trees: Map<string, Tree> }
|
|
255
|
-
```
|
|
220
|
+
### Sync behaviour
|
|
256
221
|
|
|
257
|
-
|
|
222
|
+
| option | default | what it does |
|
|
223
|
+
| --- | --- | --- |
|
|
224
|
+
| `joinWaitMs` | `1500` | How long a folder with files and no history waits for the network before speaking. `0` means "this folder is its own origin" |
|
|
225
|
+
| `syncConfig` | **`causalOrdering` and `includeClientIdentity` default to `true` via `fromClient`** | Forwarded to the `Connector` `fromClient` builds. Without `includeClientIdentity` the hub cannot tell a machine saying its head again from an echo, and holds the re-announcement back |
|
|
226
|
+
| `clientIdentity` | β | Who this machine is, on the wire |
|
|
258
227
|
|
|
259
|
-
|
|
228
|
+
### Scanning
|
|
260
229
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
230
|
+
| option | default | what it does |
|
|
231
|
+
| --- | --- | --- |
|
|
232
|
+
| `ignore` | `[]` | Patterns not to sync β see [Ignore patterns](#ignore-patterns) |
|
|
233
|
+
| `maxDepth` | unlimited | Stop descending after N levels |
|
|
234
|
+
| `followSymlinks` | `false` | Follow links out of the folder. Leave it off unless you mean it |
|
|
235
|
+
| `scanCachePath` | β | Where to persist file hashes between runs. **Pass this.** Without it every restart re-reads and re-hashes the whole folder |
|
|
264
236
|
|
|
265
|
-
|
|
237
|
+
### Timeouts (`timeouts`)
|
|
266
238
|
|
|
267
|
-
|
|
239
|
+
Every async step is bounded, because an unbounded one is a silent hang.
|
|
268
240
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
241
|
+
| field | default |
|
|
242
|
+
| --- | --- |
|
|
243
|
+
| `dbQuery` | 10 000 ms |
|
|
244
|
+
| `fetchTree` | 20 000 ms |
|
|
245
|
+
| `extract` | 15 000 ms |
|
|
246
|
+
| `restore` | 15 000 ms |
|
|
247
|
+
| `debounceMs` | 300 ms |
|
|
272
248
|
|
|
273
|
-
|
|
249
|
+
`debounceMs` coalesces a burst of filesystem events into one edit. Raise it on a
|
|
250
|
+
folder under constant churn, lower it to make a single save feel immediate.
|
|
251
|
+
`restore` bounds every apply: sending and receiving share one lock, so an apply
|
|
252
|
+
waiting on a blob nobody serves would keep this machine from recording its own
|
|
253
|
+
work. A timed-out apply is tried again the next time the hub says its head. A
|
|
254
|
+
large catalogue wants a larger `extract` and `restore` than the defaults.
|
|
274
255
|
|
|
275
|
-
|
|
256
|
+
### `restoreOptions.cleanTarget` β read this before setting it
|
|
276
257
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
258
|
+
`cleanTarget: true` makes `restore()` prune anything not in the tree. **The sync
|
|
259
|
+
never uses it**: an apply deletes exactly what an edit descending from this
|
|
260
|
+
machine's state removed, and nothing else. It is honoured only by a direct
|
|
261
|
+
`restore()` or `loadFromDb()` call, where *you* are asserting the tree is the
|
|
262
|
+
whole truth.
|
|
281
263
|
|
|
282
|
-
|
|
283
|
-
const route = Route.fromFlat(`/${treeKey}+`);
|
|
284
|
-
const connector = new Connector(db, route, socket);
|
|
264
|
+
---
|
|
285
265
|
|
|
286
|
-
|
|
287
|
-
// Later: stopSync();
|
|
288
|
-
```
|
|
266
|
+
## Ignore patterns
|
|
289
267
|
|
|
290
|
-
|
|
268
|
+
Glob syntax, matched case-insensitively, with `/` and `\` equivalent in both
|
|
269
|
+
the path and the pattern.
|
|
291
270
|
|
|
292
|
-
|
|
271
|
+
| | |
|
|
272
|
+
| --- | --- |
|
|
273
|
+
| `*` | any run of characters within one path segment |
|
|
274
|
+
| `?` | one character within one segment |
|
|
275
|
+
| `**` | crosses separators. A leading `**/` also matches at the root, so `**/tmp` means `tmp` anywhere |
|
|
276
|
+
| `/` in the pattern | matches the whole path, **anchored at the folder root** β `build/out.txt` is the top-level one, not every `build` |
|
|
277
|
+
| trailing `/` | names a directory, and covers its contents |
|
|
278
|
+
| leading `!` | an exception, rescuing what an earlier line ignored |
|
|
293
279
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
import { SocketMock } from '@rljson/io';
|
|
280
|
+
**Order matters: the last matching line decides.** `['*.log', '!keep.log']`
|
|
281
|
+
keeps `keep.log`; reversed, it does not. A scan does not descend into an
|
|
282
|
+
ignored directory, so an `!` line cannot rescue a file inside one.
|
|
298
283
|
|
|
299
|
-
|
|
300
|
-
const route = Route.fromFlat(`/${treeKey}+`);
|
|
301
|
-
const connector = new Connector(db, route, socket);
|
|
284
|
+
Blank lines and `#` comments are allowed.
|
|
302
285
|
|
|
303
|
-
|
|
304
|
-
cleanTarget: true // Optional: remove files not in tree
|
|
305
|
-
});
|
|
306
|
-
// Later: stopSync();
|
|
307
|
-
```
|
|
286
|
+
### The compatibility rule
|
|
308
287
|
|
|
309
|
-
|
|
288
|
+
**A pattern containing none of `*`, `?`, `/` or `\`, not starting with `!` and
|
|
289
|
+
not ending with `/` keeps its older meaning: equal to, or a prefix of, any path
|
|
290
|
+
segment.**
|
|
310
291
|
|
|
311
|
-
|
|
292
|
+
That is deliberate and load-bearing, not politeness to old configuration files.
|
|
293
|
+
`~$` is Word's lock-file prefix and `.~lock.` is LibreOffice's β neither is a
|
|
294
|
+
fixed name β and `.fsagent-tmp-` is how this agent hides its own in-progress
|
|
295
|
+
writes from its own watcher. Read as globs they would match only a file named
|
|
296
|
+
exactly that.
|
|
312
297
|
|
|
313
298
|
```typescript
|
|
314
|
-
|
|
299
|
+
ignore: [
|
|
300
|
+
'node_modules', // prefix: also matches anything starting with it
|
|
301
|
+
'~$', // every Word lock file
|
|
302
|
+
'*.log', // every log file, at any depth
|
|
303
|
+
'build/', // the top-level build folder and its contents
|
|
304
|
+
'**/tmp', // tmp anywhere
|
|
305
|
+
'!build/keep.txt', // ...except this one
|
|
306
|
+
]
|
|
315
307
|
```
|
|
316
308
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
Factory method that creates an FsAgent wired to a `@rljson/server` Client. Returns an enhanced agent with simplified sync methods:
|
|
309
|
+
`compileIgnore` is exported, so a UI can validate or preview a list before
|
|
310
|
+
saving it:
|
|
320
311
|
|
|
321
312
|
```typescript
|
|
322
|
-
import {
|
|
323
|
-
|
|
324
|
-
const agent = await FsAgent.fromClient(
|
|
325
|
-
'./my-project',
|
|
326
|
-
'sharedTree',
|
|
327
|
-
client,
|
|
328
|
-
socket,
|
|
329
|
-
{ ignore: ['node_modules', '.git'] },
|
|
330
|
-
);
|
|
313
|
+
import { compileIgnore } from '@rljson/fs-agent';
|
|
331
314
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
const stopFromDb = await agent.syncFromDbSimple({ cleanTarget: true });
|
|
335
|
-
|
|
336
|
-
// Stop when done
|
|
337
|
-
stopToDb();
|
|
338
|
-
stopFromDb();
|
|
315
|
+
const matcher = compileIgnore(patterns);
|
|
316
|
+
matcher.ignores('src/server.log'); // true
|
|
339
317
|
```
|
|
340
318
|
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
- **Pauses** the filesystem watcher on disconnect (prevents futile sync attempts while the server is unreachable)
|
|
344
|
-
- **Resumes** the watcher on reconnect (the server's bootstrap message triggers a catch-up sync via the Connector)
|
|
345
|
-
|
|
346
|
-
No application code is needed β the wiring is built into `fromClient()`. Clients created with older server versions that lack these methods continue to work without interruption.
|
|
319
|
+
---
|
|
347
320
|
|
|
348
|
-
|
|
321
|
+
## Knowing what happened to the folder
|
|
349
322
|
|
|
350
|
-
|
|
323
|
+
**Start here, and read one thing:** `agent.signalsNeedingAction`. It is the list
|
|
324
|
+
of things this machine could not resolve and will not resolve β a deletion the
|
|
325
|
+
guard refused, a path this filesystem rejects. If it is empty, the folder has
|
|
326
|
+
dealt with everything it met.
|
|
351
327
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
// Start watching for changes
|
|
359
|
-
await scanner.watch();
|
|
360
|
-
|
|
361
|
-
// Register change callback
|
|
362
|
-
scanner.onChange(async (change) => {
|
|
363
|
-
console.log(change.type, change.path);
|
|
328
|
+
```ts
|
|
329
|
+
const agent = await FsAgent.fromClient(folder, 'fileTree', client, socket, {
|
|
330
|
+
onSignal: (signal) => {
|
|
331
|
+
if (signal.action === 'required') alertSomebody(signal.detail);
|
|
332
|
+
},
|
|
364
333
|
});
|
|
365
334
|
|
|
366
|
-
//
|
|
367
|
-
|
|
368
|
-
scanner.resumeWatch();
|
|
369
|
-
|
|
370
|
-
// Get root tree
|
|
371
|
-
const rootTree = scanner.getRootTree();
|
|
335
|
+
// On start, for whatever happened while this process was not running:
|
|
336
|
+
for (const signal of agent.signalsNeedingAction) alertSomebody(signal.detail);
|
|
372
337
|
```
|
|
373
338
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
```typescript
|
|
381
|
-
import { Connector } from '@rljson/db';
|
|
382
|
-
import { Route } from '@rljson/rljson';
|
|
383
|
-
import { SocketMock } from '@rljson/io';
|
|
384
|
-
|
|
385
|
-
const agent = new FsAgent('./my-project', new BsMem());
|
|
386
|
-
|
|
387
|
-
// Create Connector for synchronization
|
|
388
|
-
const treeKey = 'myFilesTree';
|
|
389
|
-
const socket = new SocketMock();
|
|
390
|
-
const route = Route.fromFlat(`/${treeKey}`);
|
|
391
|
-
const connector = new Connector(db, route, socket);
|
|
392
|
-
|
|
393
|
-
// Start filesystem β database sync
|
|
394
|
-
const stopToDb = await agent.syncToDb(db, connector, treeKey);
|
|
339
|
+
| | |
|
|
340
|
+
| --- | --- |
|
|
341
|
+
| `agent.signals` | everything that happened to this folder worth telling somebody, oldest first. Survives a restart: it is read back from `.fsagent-signals.json` the first time you ask |
|
|
342
|
+
| `agent.signalsNeedingAction` | only the ones a **person** has to act on |
|
|
343
|
+
| `agent.signalTotals` | how many of each kind ever happened β unbounded, so "and 1 240 more" stays answerable after the list has dropped the oldest |
|
|
344
|
+
| `agent.onSignal(cb)` | subscribe at any time; returns an unsubscribe |
|
|
395
345
|
|
|
396
|
-
|
|
397
|
-
|
|
346
|
+
Each signal says what happened (`kind`), to what (`paths`, `pathCount`), who
|
|
347
|
+
decided (`decidedBy`), and whether somebody has to act (`action`). Three of the
|
|
348
|
+
seven kinds are `required` β a refused deletion, a directory and a file at one
|
|
349
|
+
path, and an unwritable path β because those wait for a person.
|
|
398
350
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
351
|
+
**The one to read is `conflict/arbitrary`.** Two machines changed one file at
|
|
352
|
+
once: both versions were kept, and the one that reached the fleet later keeps
|
|
353
|
+
the name. That is the order the hub heard them in, not who edited last β which
|
|
354
|
+
nobody can know without trusting two machines' clocks.
|
|
403
355
|
|
|
404
|
-
|
|
356
|
+
The full table of kinds and the field reference are in
|
|
357
|
+
[README.api.md Β§ Signals](README.api.md#signals).
|
|
405
358
|
|
|
406
|
-
|
|
359
|
+
## Reading what the agent is doing
|
|
407
360
|
|
|
408
|
-
|
|
409
|
-
|
|
361
|
+
| | |
|
|
362
|
+
| --- | --- |
|
|
363
|
+
| `agent.stageTimings` | milliseconds per stage of the **last** cycle β scan, announce, fetch, write. A total says a run was slow; this says where |
|
|
364
|
+
| `agent.ownHead` | the chain entry this folder stands on |
|
|
365
|
+
| `agent.antiEntropyStatus` | what the last head the hub said made this machine do β `diverged`, since when, and the last action (`pull`, `push`, `merge` or `blocked`) |
|
|
366
|
+
| `agent.scanner.onChange(cb)` | every filesystem event the scanner accepted |
|
|
367
|
+
| `SYNC_ERROR_FILE` | `.sync-errors.log` in the folder: a keyed, append-only record of internal failures β a locked file, an unfetchable blob, an impossible path. A refused mass deletion is a signal, not an error |
|
|
368
|
+
| `.fsagent-signals.json` | every signal, bounded, plus the per-kind totals that are not |
|
|
369
|
+
| `.fsagent-recovered/` | files a join kept but deliberately did not announce |
|
|
370
|
+
| `.fsagent-state.json` | what this machine remembers across restarts: the chain entry it stands on, and the highest stamp epoch it has heard β which a hub taking office on this machine continues above (`minEpoch`) |
|
|
410
371
|
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
db,
|
|
415
|
-
treeKey: 'filesTree',
|
|
416
|
-
});
|
|
417
|
-
```
|
|
418
|
-
|
|
419
|
-
### Ignore Patterns
|
|
372
|
+
All of these live inside the synced folder and all are ignored by the scanner β
|
|
373
|
+
otherwise the notification would itself be content, propagate, and be rewritten
|
|
374
|
+
by every peer.
|
|
420
375
|
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
```typescript
|
|
424
|
-
const agent = new FsAgent('./my-project', new BsMem(), {
|
|
425
|
-
db,
|
|
426
|
-
treeKey: 'filesTree',
|
|
427
|
-
ignore: [
|
|
428
|
-
'node_modules',
|
|
429
|
-
'.git',
|
|
430
|
-
'dist',
|
|
431
|
-
'coverage',
|
|
432
|
-
'*.log',
|
|
433
|
-
'.DS_Store',
|
|
434
|
-
'tmp/**',
|
|
435
|
-
],
|
|
436
|
-
});
|
|
437
|
-
```
|
|
376
|
+
---
|
|
438
377
|
|
|
439
|
-
|
|
378
|
+
## Using it without sync
|
|
440
379
|
|
|
441
|
-
|
|
380
|
+
The scanner and the tree are useful on their own.
|
|
442
381
|
|
|
443
382
|
```typescript
|
|
444
|
-
const agent = new FsAgent('./
|
|
445
|
-
db,
|
|
446
|
-
treeKey: 'filesTree',
|
|
447
|
-
maxDepth: 3, // Only scan 3 levels deep
|
|
448
|
-
});
|
|
449
|
-
```
|
|
450
|
-
|
|
451
|
-
### Extract and Restore
|
|
383
|
+
const agent = new FsAgent('./folder', new BsMem());
|
|
452
384
|
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
```typescript
|
|
456
|
-
// Extract current state
|
|
385
|
+
// Folder -> tree (+ blobs)
|
|
457
386
|
const tree = await agent.extract();
|
|
458
387
|
|
|
459
|
-
//
|
|
460
|
-
|
|
461
|
-
console.log('Total nodes:', tree.trees.size);
|
|
462
|
-
|
|
463
|
-
// Restore to a different location
|
|
464
|
-
await agent.restore(tree, './backup-location');
|
|
388
|
+
// Tree -> folder, additively
|
|
389
|
+
await agent.restore(tree, './elsewhere');
|
|
465
390
|
|
|
466
|
-
//
|
|
467
|
-
|
|
468
|
-
const treeFromDb = await dbAdapter.loadFsTree('abc123'); // tree hash
|
|
469
|
-
await agent.restore(treeFromDb, './restore-here');
|
|
391
|
+
// Tree -> folder, exactly: prune anything not in the tree
|
|
392
|
+
await agent.restore(tree, './elsewhere', { cleanTarget: true });
|
|
470
393
|
```
|
|
471
394
|
|
|
472
|
-
|
|
395
|
+
A restore writes only what differs. Re-restoring the same tree over a folder
|
|
396
|
+
that already matches writes nothing β which is what keeps one new file from
|
|
397
|
+
rewriting a whole catalogue.
|
|
473
398
|
|
|
474
|
-
|
|
399
|
+
---
|
|
475
400
|
|
|
476
|
-
|
|
477
|
-
import { Route } from '@rljson/rljson';
|
|
478
|
-
|
|
479
|
-
// Get insert history for the tree
|
|
480
|
-
const route = Route.fromFlat(`${treeKey}/`);
|
|
481
|
-
const historyResult = await db.getInsertHistory(route, {});
|
|
401
|
+
## What it guarantees β and what it does not
|
|
482
402
|
|
|
483
|
-
|
|
484
|
-
for (const entry of historyResult.history) {
|
|
485
|
-
const treeRef = entry.treeRef;
|
|
486
|
-
const timestamp = entry.insertedAt;
|
|
487
|
-
|
|
488
|
-
// Load and restore specific version
|
|
489
|
-
const tree = await agent.loadFromDb(db, treeKey, treeRef);
|
|
490
|
-
await agent.restore(tree, `./version-${timestamp}`);
|
|
491
|
-
}
|
|
492
|
-
```
|
|
403
|
+
**It does:**
|
|
493
404
|
|
|
494
|
-
|
|
405
|
+
- converge β every machine ends on the same content, or reports why not;
|
|
406
|
+
- never lose a user's edit to a merge, a catch-up or a reconnect;
|
|
407
|
+
- propagate a deletion made while partitioned or unheard-of by a peer, and
|
|
408
|
+
keep it deleted;
|
|
409
|
+
- keep both sides of a conflict, and say there was one;
|
|
410
|
+
- survive a locked file, an impossible path, a full disk, a vanishing entry, a
|
|
411
|
+
wrong clock and a peer whose history cannot be read β each failing only
|
|
412
|
+
itself;
|
|
413
|
+
- cost one blob to catch up on twenty missed saves of one file, not twenty.
|
|
495
414
|
|
|
496
|
-
|
|
415
|
+
**It does not:**
|
|
497
416
|
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
}
|
|
517
|
-
});
|
|
518
|
-
```
|
|
417
|
+
- **split a large file into blocks.** A file transfers whole, so the transport's
|
|
418
|
+
message limit is the per-file ceiling;
|
|
419
|
+
- **let you approve a mass deletion.** One that looks like a loss is refused
|
|
420
|
+
and reported as a `deletion/refused` signal marked `required`; there is no
|
|
421
|
+
override yet;
|
|
422
|
+
- **collect garbage.** Every superseded version stays on every machine;
|
|
423
|
+
- **promise a latency.** Nothing in the suite asserts an arrival deadline, so
|
|
424
|
+
nothing here should be read as one;
|
|
425
|
+
- **repair a folder reverted under a running agent.** Restoring a backup while
|
|
426
|
+
the agent is stopped is handled; doing it underneath a live one is not
|
|
427
|
+
decidable from the history, and the reasoning is in the test;
|
|
428
|
+
- **follow a whole folder disappearing that it did not watch go.** A deletion
|
|
429
|
+
made while the agent was stopped is recorded at the next start like any
|
|
430
|
+
edit β unless it looks like a lost folder: more than the floors (a hundred
|
|
431
|
+
files and 30 % of the folder, or all but ten) gone without the watcher seeing
|
|
432
|
+
it. That is the shape of a failed mount or a wiped drive, never of a person,
|
|
433
|
+
so nothing is recorded and a `deletion/refused` signal asks somebody to
|
|
434
|
+
decide. **Delete large amounts with the client running.**
|
|
519
435
|
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
`fs-agent` provides robust error handling with clear error messages:
|
|
523
|
-
|
|
524
|
-
```typescript
|
|
525
|
-
try {
|
|
526
|
-
const agent = new FsAgent('./nonexistent', new BsMem(), {
|
|
527
|
-
db,
|
|
528
|
-
treeKey: 'filesTree',
|
|
529
|
-
});
|
|
530
|
-
} catch (error) {
|
|
531
|
-
// Error: Root path "./nonexistent" does not exist. Cannot scan non-existent directory.
|
|
532
|
-
}
|
|
533
|
-
```
|
|
534
|
-
|
|
535
|
-
### Common Error Scenarios
|
|
536
|
-
|
|
537
|
-
1. **Missing Root Path**: Clear error if directory doesn't exist
|
|
538
|
-
2. **Database Failures**: Errors include context about what operation failed
|
|
539
|
-
3. **Invalid Tree Data**: Validation errors explain what's wrong
|
|
540
|
-
4. **Sync Failures**: Non-fatal errors logged, syncing continues
|
|
541
|
-
5. **Loop Detection**: Automatic prevention via pause/resume
|
|
542
|
-
|
|
543
|
-
## Examples
|
|
544
|
-
|
|
545
|
-
### Example 1: Simple Project Sync
|
|
546
|
-
|
|
547
|
-
```typescript
|
|
548
|
-
import { FsAgent } from '@rljson/fs-agent';
|
|
549
|
-
import { Connector, Db } from '@rljson/db';
|
|
550
|
-
import { IoMem, SocketMock } from '@rljson/io';
|
|
551
|
-
import { BsMem } from '@rljson/bs';
|
|
552
|
-
import { Route, createTreesTableCfg } from '@rljson/rljson';
|
|
553
|
-
|
|
554
|
-
async function syncProject() {
|
|
555
|
-
// Setup
|
|
556
|
-
const io = new IoMem();
|
|
557
|
-
await io.init();
|
|
558
|
-
const db = new Db(io);
|
|
559
|
-
|
|
560
|
-
const treeKey = 'projectTree';
|
|
561
|
-
const treeTableCfg = createTreesTableCfg(treeKey);
|
|
562
|
-
await db.core.createTableWithInsertHistory(treeTableCfg);
|
|
563
|
-
|
|
564
|
-
// Create agent
|
|
565
|
-
const agent = new FsAgent('./src', new BsMem(), {
|
|
566
|
-
ignore: ['*.tmp'],
|
|
567
|
-
});
|
|
568
|
-
|
|
569
|
-
// Create Connector and start syncing
|
|
570
|
-
const socket = new SocketMock();
|
|
571
|
-
const route = Route.fromFlat(`/${treeKey}+`);
|
|
572
|
-
const connector = new Connector(db, route, socket);
|
|
573
|
-
const stopSync = await agent.syncToDb(db, connector, treeKey);
|
|
574
|
-
|
|
575
|
-
// Clean up when done
|
|
576
|
-
process.on('SIGINT', () => {
|
|
577
|
-
stopSync();
|
|
578
|
-
agent.dispose();
|
|
579
|
-
process.exit();
|
|
580
|
-
});
|
|
581
|
-
}
|
|
582
|
-
```
|
|
583
|
-
|
|
584
|
-
### Example 2: Backup and Restore
|
|
585
|
-
|
|
586
|
-
```typescript
|
|
587
|
-
async function backupAndRestore() {
|
|
588
|
-
// Create agent
|
|
589
|
-
const agent = new FsAgent('./my-data', new BsMem());
|
|
590
|
-
|
|
591
|
-
// Extract current state
|
|
592
|
-
const backup = await agent.extract();
|
|
593
|
-
console.log('Backed up', backup.trees.size, 'nodes');
|
|
594
|
-
|
|
595
|
-
// ... later, restore from backup
|
|
596
|
-
await agent.restore(backup, './my-data-restored');
|
|
597
|
-
}
|
|
598
|
-
```
|
|
599
|
-
|
|
600
|
-
### Example 2b: Clean Restore (remove stale files)
|
|
601
|
-
|
|
602
|
-
```typescript
|
|
603
|
-
async function cleanRestore() {
|
|
604
|
-
const agent = new FsAgent('./source', new BsMem());
|
|
605
|
-
const snapshot = await agent.extract();
|
|
606
|
-
|
|
607
|
-
// Restore to target and prune anything not in the snapshot
|
|
608
|
-
await agent.restore(snapshot, './target', { cleanTarget: true });
|
|
609
|
-
}
|
|
610
|
-
```
|
|
611
|
-
|
|
612
|
-
### Example 3: Bidirectional Sync
|
|
613
|
-
|
|
614
|
-
```typescript
|
|
615
|
-
async function bidirectionalSync() {
|
|
616
|
-
// Setup database
|
|
617
|
-
const io = new IoMem();
|
|
618
|
-
await io.init();
|
|
619
|
-
const db = new Db(io);
|
|
620
|
-
|
|
621
|
-
const treeTableCfg = createTreesTableCfg('sharedTree');
|
|
622
|
-
await db.core.createTableWithInsertHistory(treeTableCfg);
|
|
623
|
-
|
|
624
|
-
// Agent 1: Watches ./alice and syncs to DB
|
|
625
|
-
const alice = new FsAgent('./alice', new BsMem(), {
|
|
626
|
-
db,
|
|
627
|
-
treeKey: 'sharedTree',
|
|
628
|
-
bidirectional: true, // β Bidirectional
|
|
629
|
-
});
|
|
630
|
-
|
|
631
|
-
// Agent 2: Watches ./bob and syncs to DB
|
|
632
|
-
const bob = new FsAgent('./bob', new BsMem(), {
|
|
633
|
-
db,
|
|
634
|
-
treeKey: 'sharedTree',
|
|
635
|
-
bidirectional: true, // β Bidirectional
|
|
636
|
-
});
|
|
637
|
-
|
|
638
|
-
// Now:
|
|
639
|
-
// - Changes in ./alice β sync to DB β appear in ./bob
|
|
640
|
-
// - Changes in ./bob β sync to DB β appear in ./alice
|
|
641
|
-
// - Loop prevention ensures stability
|
|
642
|
-
}
|
|
643
|
-
```
|
|
644
|
-
|
|
645
|
-
### Example 4: Custom Change Handling
|
|
646
|
-
|
|
647
|
-
```typescript
|
|
648
|
-
async function customHandling() {
|
|
649
|
-
const agent = new FsAgent('./watched', new BsMem(), {
|
|
650
|
-
db,
|
|
651
|
-
treeKey: 'watchedTree',
|
|
652
|
-
});
|
|
653
|
-
|
|
654
|
-
let changeCount = 0;
|
|
655
|
-
|
|
656
|
-
agent.scanner.onChange(async (change) => {
|
|
657
|
-
changeCount++;
|
|
658
|
-
|
|
659
|
-
if (change.type === 'add' && change.path.endsWith('.ts')) {
|
|
660
|
-
console.log(`New TypeScript file: ${change.path}`);
|
|
661
|
-
// Could trigger build, linting, etc.
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
if (changeCount % 10 === 0) {
|
|
665
|
-
console.log(`Processed ${changeCount} changes`);
|
|
666
|
-
}
|
|
667
|
-
});
|
|
668
|
-
}
|
|
669
|
-
```
|
|
670
|
-
|
|
671
|
-
## Best Practices
|
|
672
|
-
|
|
673
|
-
### 1. Use Ignore Patterns
|
|
674
|
-
|
|
675
|
-
Always ignore build artifacts, dependencies, and temporary files:
|
|
676
|
-
|
|
677
|
-
```typescript
|
|
678
|
-
{
|
|
679
|
-
ignore: [
|
|
680
|
-
'node_modules',
|
|
681
|
-
'.git',
|
|
682
|
-
'dist',
|
|
683
|
-
'build',
|
|
684
|
-
'coverage',
|
|
685
|
-
'*.log',
|
|
686
|
-
'.DS_Store',
|
|
687
|
-
'tmp',
|
|
688
|
-
];
|
|
689
|
-
}
|
|
690
|
-
```
|
|
691
|
-
|
|
692
|
-
### 2. Dispose When Done
|
|
693
|
-
|
|
694
|
-
Always clean up resources:
|
|
695
|
-
|
|
696
|
-
```typescript
|
|
697
|
-
const agent = new FsAgent(path, bs, options);
|
|
698
|
-
|
|
699
|
-
try {
|
|
700
|
-
// Use agent...
|
|
701
|
-
} finally {
|
|
702
|
-
agent.dispose();
|
|
703
|
-
}
|
|
704
|
-
```
|
|
705
|
-
|
|
706
|
-
### 3. Use Bidirectional Sync Carefully
|
|
707
|
-
|
|
708
|
-
Bidirectional sync is powerful but consider:
|
|
709
|
-
|
|
710
|
-
- Multiple agents sharing the same `treeKey` will sync to each other
|
|
711
|
-
- Loop prevention is automatic but adds slight latency
|
|
712
|
-
- Best for collaborative scenarios or distributed systems
|
|
713
|
-
|
|
714
|
-
### 4. Monitor Depth
|
|
715
|
-
|
|
716
|
-
Use `maxDepth` for deep directory structures:
|
|
717
|
-
|
|
718
|
-
```typescript
|
|
719
|
-
{
|
|
720
|
-
maxDepth: 5, // Prevents extremely deep recursion
|
|
721
|
-
}
|
|
722
|
-
```
|
|
723
|
-
|
|
724
|
-
### 5. Handle Errors
|
|
725
|
-
|
|
726
|
-
Wrap agent creation in try-catch for better error handling:
|
|
727
|
-
|
|
728
|
-
```typescript
|
|
729
|
-
try {
|
|
730
|
-
const agent = new FsAgent(userProvidedPath, bs, options);
|
|
731
|
-
} catch (error) {
|
|
732
|
-
console.error('Failed to create agent:', error.message);
|
|
733
|
-
}
|
|
734
|
-
```
|
|
735
|
-
|
|
736
|
-
## Timeout & Debounce Configuration
|
|
737
|
-
|
|
738
|
-
Every async operation in FsAgent is guarded by a timeout to prevent silent hangs.
|
|
739
|
-
Rapid filesystem events are debounced to coalesce into a single sync cycle.
|
|
740
|
-
|
|
741
|
-
```typescript
|
|
742
|
-
const agent = new FsAgent('./my-project', bs, {
|
|
743
|
-
timeouts: {
|
|
744
|
-
dbQuery: 10_000, // Single db.get() query (default: 10s)
|
|
745
|
-
fetchTree: 20_000, // Fetching an entire tree from the DB (default: 20s)
|
|
746
|
-
extract: 15_000, // Filesystem extract/scan (default: 15s)
|
|
747
|
-
restore: 15_000, // Filesystem restore (default: 15s)
|
|
748
|
-
syncCallback: 25_000, // Overall syncFromDb callback (default: 25s)
|
|
749
|
-
debounceMs: 300, // Coalesce rapid FS events (default: 300ms)
|
|
750
|
-
processRefRetries: 3, // Retry failed refs before dropping (default: 3)
|
|
751
|
-
processRefRetryDelayMs: 5_000, // Base delay between retries (default: 5s)
|
|
752
|
-
},
|
|
753
|
-
});
|
|
754
|
-
```
|
|
755
|
-
|
|
756
|
-
### processRef Retry Behavior
|
|
757
|
-
|
|
758
|
-
When `syncFromDb` receives a tree ref and fails to process it (e.g. `db.get`
|
|
759
|
-
times out because the IoPeer transport hasn't connected yet), the ref is
|
|
760
|
-
retried up to `processRefRetries` times with increasing delay
|
|
761
|
-
(`attempt * processRefRetryDelayMs`). This prevents a single transient
|
|
762
|
-
timeout from permanently breaking the sync pipeline.
|
|
763
|
-
|
|
764
|
-
## Anti-Entropy β healing a lost message
|
|
765
|
-
|
|
766
|
-
Every change reaches a peer as exactly one message. If that message is lost β
|
|
767
|
-
a push the hub never received, a forward a peer never received, an apply that
|
|
768
|
-
gave up β nothing would ever send it again, and two machines would sit on two
|
|
769
|
-
states for good. The anti-entropy notices and repairs that, with nobody doing
|
|
770
|
-
anything.
|
|
771
|
-
|
|
772
|
-
It is driven by the hub's periodic announcement of its state, so the server
|
|
773
|
-
must send one. Use the **state beacon** (`@rljson/server` 0.0.67+): it goes on
|
|
774
|
-
its own event, which the connector never processes, so it costs nothing in
|
|
775
|
-
the apply path. The bootstrap heartbeat works too, but a periodic heartbeat
|
|
776
|
-
is delivered into every agent's apply path and has been measured
|
|
777
|
-
net-harmful in production.
|
|
778
|
-
|
|
779
|
-
```typescript
|
|
780
|
-
const server = new Server(route, io, bs, {
|
|
781
|
-
syncConfig: { causalOrdering: true, includeClientIdentity: true },
|
|
782
|
-
stateBeaconMs: 30_000,
|
|
783
|
-
});
|
|
784
|
-
|
|
785
|
-
const agent = new FsAgent('./my-project', bs, {
|
|
786
|
-
antiEntropy: {
|
|
787
|
-
enabled: true, // default: true
|
|
788
|
-
graceMs: 10_000, // how long this node may sit still, out of step, before a repair (default: 10s)
|
|
789
|
-
maxBackoffMs: 300_000 // cap for repeated repairs of one divergence (default: 5 min)
|
|
790
|
-
},
|
|
791
|
-
});
|
|
792
|
-
```
|
|
793
|
-
|
|
794
|
-
Each announcement carries the hub's tree ref β a content hash of the whole
|
|
795
|
-
folder, so comparing it with our own is the per-folder checksum comparison β
|
|
796
|
-
plus who produced it and what it descends from. A divergence that outlives
|
|
797
|
-
`graceMs` while nothing is applying is repaired:
|
|
798
|
-
|
|
799
|
-
| Hub state | Repair |
|
|
800
|
-
|---|---|
|
|
801
|
-
| an earlier push of ours, or what our push was made from | **push** β re-announce our state |
|
|
802
|
-
| made from the state we are in | **pull** β apply it, deletions included |
|
|
803
|
-
| neither can be shown | **merge** β apply it; if that makes no progress, additively |
|
|
804
|
-
|
|
805
|
-
Every repair goes through the ordinary apply and push paths, with their
|
|
806
|
-
ancestry and mass-delete rules; the anti-entropy never deletes anything
|
|
807
|
-
itself. Without a beacon or heartbeat it never fires. `agent.antiEntropyStatus`
|
|
808
|
-
reports whether this node and the hub agree, since when they have not, and
|
|
809
|
-
the last repair β a lasting divergence is the one trace a lost message leaves.
|
|
810
|
-
|
|
811
|
-
## Bounce-Back Prevention
|
|
812
|
-
|
|
813
|
-
Bidirectional sync can cause infinite loops when both clients detect each
|
|
814
|
-
other's restores as changes. FsAgent prevents this with three layers:
|
|
815
|
-
|
|
816
|
-
1. **Ref tracking** (`_lastSentRef`): Skips re-broadcast if the stored tree
|
|
817
|
-
produces the same ref as the last one we sent.
|
|
818
|
-
2. **Content-key dedup** (`_lastSentContentKey`): Compares file paths + blobIds
|
|
819
|
-
(ignoring mtimes) to detect identical content with different tree hashes.
|
|
820
|
-
3. **Content comparison before restore**: `syncFromDb` compares the incoming
|
|
821
|
-
tree's content with the current filesystem and skips restore if identical.
|
|
822
|
-
|
|
823
|
-
## Performance
|
|
824
|
-
|
|
825
|
-
- **Efficient Scanning**: Only scans changed directories
|
|
826
|
-
- **Deduplication**: Identical files stored once
|
|
827
|
-
- **Content-Addressed**: Fast lookups via hashes
|
|
828
|
-
- **Optimized Watching**: Uses native filesystem events
|
|
829
|
-
- **Smart Sync**: Only syncs when changes detected
|
|
830
|
-
- **Debounced Events**: Rapid changes coalesced into single operations
|
|
831
|
-
- **Bounded Operations**: All async operations time out to prevent hangs
|
|
436
|
+
---
|
|
832
437
|
|
|
833
438
|
## Troubleshooting
|
|
834
439
|
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
440
|
+
**Two versions of one file wait instead of being settled.** Their conflict needs
|
|
441
|
+
the hub's stamp and the hub does not give one: a `repair/blocked` signal says
|
|
442
|
+
so, and both machines keep their own version. Configure the hub with
|
|
443
|
+
`stamp: { domain, hub }`.
|
|
444
|
+
|
|
445
|
+
**An ignore pattern does nothing.** With no `*`, `?` or `/` it is a *prefix*,
|
|
446
|
+
not a glob: `exe` ignores files starting with `exe`, while `*.exe` is what
|
|
447
|
+
ignores the extension. Check it with `compileIgnore`.
|
|
448
|
+
|
|
449
|
+
**A change arrives late rather than not at all.** A machine that missed an
|
|
450
|
+
announcement catches up the next time the hub says its head β on the state
|
|
451
|
+
beacon, every 30 s in the host client. The failure mode is *delayed*, not
|
|
452
|
+
*silently dropped*.
|
|
453
|
+
|
|
454
|
+
**A whole-folder deletion was refused.** The mass-delete guard, at the machine
|
|
455
|
+
that would have recorded it or at one that would have applied it. A
|
|
456
|
+
`deletion/refused` signal names the count and the threshold. There is no
|
|
457
|
+
override yet.
|
|
458
|
+
|
|
459
|
+
**The first start takes minutes.** A cold scan reads and hashes every file.
|
|
460
|
+
Pass `scanCachePath`.
|
|
461
|
+
|
|
462
|
+
**Files appear in `.fsagent-recovered/`.** A join found files the shared
|
|
463
|
+
history had deliberately deleted. They are kept, not announced and not
|
|
464
|
+
destroyed. Usually it means that folder was restored from a backup.
|
|
465
|
+
|
|
466
|
+
**A big restore times out.** Blob transfer is streamed, but a 15-second
|
|
467
|
+
`restore` budget is not enough for a catalogue. Raise `timeouts.restore` and
|
|
468
|
+
`timeouts.extract`.
|
|
469
|
+
|
|
470
|
+
---
|
|
471
|
+
|
|
472
|
+
## Known constraints
|
|
473
|
+
|
|
474
|
+
**macOS Finder paste and rename.** Sync relies on Node's `fs.watch` (FSEvents
|
|
475
|
+
on macOS), which is reliable for programmatic operations and ordinary editor
|
|
476
|
+
saves β but Finder's paste and in-place rename do not always emit an event. A
|
|
477
|
+
periodic safety rescan catches these, so the gap is the rescan interval rather
|
|
478
|
+
than forever. See [doc/safety-rescan.md](doc/safety-rescan.md).
|
|
479
|
+
|
|
480
|
+
**Windows file locks are covered on one machine only.** The behaviour is right
|
|
481
|
+
β a locked file blocks itself and nothing else, and a half-applied state is not
|
|
482
|
+
advertised β but no mesh test runs on Windows, so this wants a Windows CI
|
|
483
|
+
runner.
|
|
484
|
+
|
|
485
|
+
**Upgrading from 0.0.x changes every ref in the fleet.** 0.2.0 announces chain
|
|
486
|
+
heads only, orders conflicts by the hub's stamp, and keeps no compatibility with
|
|
487
|
+
older wire formats β deliberately: one flag would select two consistency models.
|
|
488
|
+
A machine on 0.2.0 and one on an older release cannot sync. **Upgrade a domain
|
|
489
|
+
together, while it is in sync**, and configure its hubs to stamp; a machine
|
|
490
|
+
whose state file names no head it can read starts as a joiner.
|
|
491
|
+
|
|
492
|
+
**A deliberate mass deletion does not arrive.** Deleting most of a folder is
|
|
493
|
+
refused, and nothing asks the user β see "what it does not do" above. Read
|
|
494
|
+
`agent.signalsNeedingAction` to find out it happened: the guard cannot tell a
|
|
495
|
+
person deleting a project from a machine that lost its disk, and the second is
|
|
496
|
+
why the guard exists. A machine that did lose its folder is refilled: the fleet
|
|
497
|
+
keeps the files and records them again on top of the deletion.
|
|
498
|
+
|
|
499
|
+
**A file still being written cannot be recognised with certainty.** The settle
|
|
500
|
+
rule holds a file back on the first sight of it and for as long as its size keeps
|
|
501
|
+
moving, which covers a copy in progress whatever the machine's clock says. What
|
|
502
|
+
no rule over `stat` can decide is a writer that pauses for a long time: a file
|
|
503
|
+
whose timestamp looks finished and whose size has not moved between two scans is
|
|
504
|
+
indistinguishable from one that was written and closed. If that happens the file
|
|
505
|
+
is hashed and distributed truncated, and a reader of the shared folder sees the
|
|
506
|
+
truncated version until the copy finishes β at which point the size and timestamp
|
|
507
|
+
change, the file is re-read, and the complete version propagates. Nothing is
|
|
508
|
+
corrupted permanently.
|
|
509
|
+
|
|
510
|
+
**Two limits of ordering by the hub.** Neither loses data, and both converge.
|
|
511
|
+
A machine that missed an announcement derives a later stamp for the versions it
|
|
512
|
+
carried, so its verdict on a same-file conflict can differ from a peer's; the
|
|
513
|
+
two merges then merge once more, leaving one redundant conflicted copy. And a
|
|
514
|
+
version that passed through a merge carries the merge's stamp, so in a
|
|
515
|
+
three-way race the name can go to a version first edited earlier.
|
|
516
|
+
|
|
517
|
+
**What to watch in production.** `agent.antiEntropyStatus`: `hubRef` is the head
|
|
518
|
+
the hub said last and `localRef` this machine's head now. They differ for a
|
|
519
|
+
moment after every edit; `diverged` for a long time, with `lastRepair.action`
|
|
520
|
+
`blocked`, is the case to look at.
|
|
521
|
+
|
|
522
|
+
---
|
|
523
|
+
|
|
524
|
+
## Further reading
|
|
525
|
+
|
|
526
|
+
| document | what is in it |
|
|
527
|
+
| --- | --- |
|
|
528
|
+
| [README.architecture.md](README.architecture.md) | the design: why references rather than payloads, the edit chain, the conflict table, the stamp, the guards |
|
|
529
|
+
| [README.api.md](README.api.md) | every export, grouped by module β the shape, where this document gives the advice |
|
|
530
|
+
| [README.tests.md](README.tests.md) | the 723 scenarios this package ships, by what they prove |
|
|
531
|
+
|
|
532
|
+
Related packages: `@rljson/rljson` (trees), `@rljson/db` (database and
|
|
533
|
+
`Connector`), `@rljson/io` (sockets and storage), `@rljson/bs` (blobs),
|
|
534
|
+
`@rljson/server` (hub and client), `@rljson/mongo-agent` (the same idea for
|
|
535
|
+
documents).
|
|
917
536
|
|
|
918
537
|
## License
|
|
919
538
|
|
|
920
|
-
See [LICENSE](LICENSE)
|
|
921
|
-
|
|
922
|
-
## More Information
|
|
923
|
-
|
|
924
|
-
- [Example Code](src/example.ts)
|
|
925
|
-
- [Architecture](README.architecture.md)
|
|
926
|
-
- [Contributors](README.contributors.md)
|
|
539
|
+
See [LICENSE](LICENSE).
|