@dxos/echo-pipeline 0.8.4-main.84f28bd → 0.8.4-main.a4bbb77
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/dist/lib/browser/chunk-BVR7OOZK.mjs +251 -0
- package/dist/lib/browser/chunk-BVR7OOZK.mjs.map +7 -0
- package/dist/lib/browser/{chunk-GBFX5J5B.mjs → chunk-XGG76KKU.mjs} +487 -324
- package/dist/lib/browser/chunk-XGG76KKU.mjs.map +7 -0
- package/dist/lib/browser/filter/index.mjs +3 -1
- package/dist/lib/browser/index.mjs +1379 -562
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +107 -44
- package/dist/lib/browser/testing/index.mjs.map +3 -3
- package/dist/lib/node-esm/{chunk-FQFKWA3X.mjs → chunk-CHMJJ4DG.mjs} +487 -324
- package/dist/lib/node-esm/chunk-CHMJJ4DG.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs +251 -0
- package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs.map +7 -0
- package/dist/lib/node-esm/filter/index.mjs +3 -1
- package/dist/lib/node-esm/index.mjs +1379 -562
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +107 -44
- package/dist/lib/node-esm/testing/index.mjs.map +3 -3
- package/dist/types/src/automerge/automerge-host.d.ts +15 -28
- package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
- package/dist/types/src/automerge/collection-synchronizer.d.ts +1 -1
- package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
- package/dist/types/src/automerge/echo-network-adapter.d.ts +8 -1
- package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
- package/dist/types/src/automerge/echo-replicator.d.ts +21 -2
- package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
- package/dist/types/src/automerge/index.d.ts +1 -1
- package/dist/types/src/automerge/index.d.ts.map +1 -1
- package/dist/types/src/automerge/leveldb-storage-adapter.d.ts +1 -1
- package/dist/types/src/automerge/leveldb-storage-adapter.d.ts.map +1 -1
- package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +1 -0
- package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
- package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
- package/dist/types/src/common/codec.d.ts +1 -1
- package/dist/types/src/common/codec.d.ts.map +1 -1
- package/dist/types/src/db-host/data-service.d.ts +2 -2
- package/dist/types/src/db-host/data-service.d.ts.map +1 -1
- package/dist/types/src/db-host/database-root.d.ts.map +1 -1
- package/dist/types/src/db-host/documents-synchronizer.d.ts +2 -2
- package/dist/types/src/db-host/documents-synchronizer.d.ts.map +1 -1
- package/dist/types/src/db-host/echo-host.d.ts +2 -2
- package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
- package/dist/types/src/db-host/query-service.d.ts +1 -1
- package/dist/types/src/db-host/query-service.d.ts.map +1 -1
- package/dist/types/src/db-host/space-state-manager.d.ts +1 -1
- package/dist/types/src/db-host/space-state-manager.d.ts.map +1 -1
- package/dist/types/src/edge/echo-edge-replicator.d.ts +4 -2
- package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
- package/dist/types/src/filter/filter-match.d.ts +4 -1
- package/dist/types/src/filter/filter-match.d.ts.map +1 -1
- package/dist/types/src/metadata/metadata-store.d.ts +1 -1
- package/dist/types/src/metadata/metadata-store.d.ts.map +1 -1
- package/dist/types/src/pipeline/pipeline.d.ts +1 -1
- package/dist/types/src/pipeline/pipeline.d.ts.map +1 -1
- package/dist/types/src/query/errors.d.ts +24 -8
- package/dist/types/src/query/errors.d.ts.map +1 -1
- package/dist/types/src/query/plan.d.ts +8 -1
- package/dist/types/src/query/plan.d.ts.map +1 -1
- package/dist/types/src/query/query-executor.d.ts +4 -1
- package/dist/types/src/query/query-executor.d.ts.map +1 -1
- package/dist/types/src/query/query-planner.d.ts +2 -0
- package/dist/types/src/query/query-planner.d.ts.map +1 -1
- package/dist/types/src/space/admission-discovery-extension.d.ts.map +1 -1
- package/dist/types/src/space/control-pipeline.d.ts +1 -1
- package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
- package/dist/types/src/space/space-manager.d.ts +1 -1
- package/dist/types/src/space/space-manager.d.ts.map +1 -1
- package/dist/types/src/space/space-protocol.d.ts +1 -1
- package/dist/types/src/space/space-protocol.d.ts.map +1 -1
- package/dist/types/src/space/space.d.ts +1 -1
- package/dist/types/src/space/space.d.ts.map +1 -1
- package/dist/types/src/testing/test-agent-builder.d.ts +2 -2
- package/dist/types/src/testing/test-agent-builder.d.ts.map +1 -1
- package/dist/types/src/testing/test-replicator.d.ts +1 -0
- package/dist/types/src/testing/test-replicator.d.ts.map +1 -1
- package/dist/types/src/util.d.ts +1 -1
- package/dist/types/src/util.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +41 -38
- package/src/automerge/automerge-host.test.ts +18 -8
- package/src/automerge/automerge-host.ts +266 -70
- package/src/automerge/automerge-repo.test.ts +67 -16
- package/src/automerge/collection-synchronizer.test.ts +2 -2
- package/src/automerge/collection-synchronizer.ts +4 -4
- package/src/automerge/echo-data-monitor.ts +1 -1
- package/src/automerge/echo-network-adapter.test.ts +3 -3
- package/src/automerge/echo-network-adapter.ts +38 -6
- package/src/automerge/echo-replicator.ts +23 -2
- package/src/automerge/index.ts +1 -1
- package/src/automerge/leveldb-storage-adapter.ts +7 -7
- package/src/automerge/mesh-echo-replicator-connection.ts +4 -0
- package/src/automerge/mesh-echo-replicator.ts +2 -1
- package/src/automerge/storage-adapter.test.ts +1 -1
- package/src/common/space-id.ts +1 -1
- package/src/db-host/data-service.ts +9 -17
- package/src/db-host/database-root.ts +2 -2
- package/src/db-host/documents-synchronizer.test.ts +1 -1
- package/src/db-host/documents-synchronizer.ts +39 -26
- package/src/db-host/echo-host.ts +14 -15
- package/src/db-host/query-service.ts +8 -1
- package/src/db-host/space-state-manager.ts +2 -2
- package/src/edge/echo-edge-replicator.test.ts +5 -3
- package/src/edge/echo-edge-replicator.ts +75 -18
- package/src/filter/filter-match.test.ts +33 -13
- package/src/filter/filter-match.ts +177 -10
- package/src/metadata/metadata-store.ts +3 -3
- package/src/pipeline/pipeline-stress.test.ts +4 -2
- package/src/pipeline/pipeline.test.ts +3 -2
- package/src/pipeline/pipeline.ts +8 -5
- package/src/query/errors.ts +2 -0
- package/src/query/plan.ts +12 -1
- package/src/query/query-executor.ts +71 -11
- package/src/query/query-planner.test.ts +146 -2
- package/src/query/query-planner.ts +81 -11
- package/src/space/admission-discovery-extension.ts +2 -2
- package/src/space/control-pipeline.test.ts +4 -3
- package/src/space/control-pipeline.ts +9 -6
- package/src/space/space-manager.browser.test.ts +1 -1
- package/src/space/space-manager.ts +5 -4
- package/src/space/space-protocol.browser.test.ts +2 -2
- package/src/space/space-protocol.test.ts +3 -2
- package/src/space/space-protocol.ts +6 -3
- package/src/space/space.test.ts +1 -1
- package/src/space/space.ts +3 -2
- package/src/testing/test-agent-builder.ts +4 -3
- package/src/testing/test-replicator.ts +4 -0
- package/src/util.ts +1 -1
- package/dist/lib/browser/chunk-ANZAS5CC.mjs +0 -126
- package/dist/lib/browser/chunk-ANZAS5CC.mjs.map +0 -7
- package/dist/lib/browser/chunk-GBFX5J5B.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-2SAZ7CCF.mjs +0 -126
- package/dist/lib/node-esm/chunk-2SAZ7CCF.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-FQFKWA3X.mjs.map +0 -7
|
@@ -3,48 +3,49 @@
|
|
|
3
3
|
//
|
|
4
4
|
|
|
5
5
|
import {
|
|
6
|
+
type Doc,
|
|
7
|
+
type Heads,
|
|
6
8
|
getBackend,
|
|
7
9
|
getHeads,
|
|
8
|
-
isAutomerge,
|
|
9
10
|
equals as headsEquals,
|
|
11
|
+
isAutomerge,
|
|
10
12
|
save,
|
|
11
|
-
type Doc,
|
|
12
|
-
type Heads,
|
|
13
13
|
} from '@automerge/automerge';
|
|
14
14
|
import {
|
|
15
|
-
type DocHandleChangePayload,
|
|
16
|
-
Repo,
|
|
17
15
|
type AnyDocumentId,
|
|
18
16
|
type DocHandle,
|
|
17
|
+
type DocHandleChangePayload,
|
|
19
18
|
type DocumentId,
|
|
19
|
+
type HandleState,
|
|
20
20
|
type PeerCandidatePayload,
|
|
21
21
|
type PeerDisconnectedPayload,
|
|
22
22
|
type PeerId,
|
|
23
|
+
Repo,
|
|
23
24
|
type StorageAdapterInterface,
|
|
24
25
|
type StorageKey,
|
|
25
26
|
interpretAsDocumentId,
|
|
26
|
-
type HandleState,
|
|
27
27
|
} from '@automerge/automerge-repo';
|
|
28
28
|
|
|
29
|
-
import { Event, asyncTimeout } from '@dxos/async';
|
|
30
|
-
import { Context, Resource, cancelWithContext
|
|
31
|
-
import {
|
|
29
|
+
import { DeferredTask, Event, asyncTimeout } from '@dxos/async';
|
|
30
|
+
import { Context, type Lifecycle, Resource, cancelWithContext } from '@dxos/context';
|
|
31
|
+
import { type CollectionId, DatabaseDirectory } from '@dxos/echo-protocol';
|
|
32
32
|
import { type IndexMetadataStore } from '@dxos/indexing';
|
|
33
33
|
import { invariant } from '@dxos/invariant';
|
|
34
34
|
import { PublicKey } from '@dxos/keys';
|
|
35
35
|
import { type LevelDB } from '@dxos/kv-store';
|
|
36
36
|
import { log } from '@dxos/log';
|
|
37
37
|
import { objectPointerCodec } from '@dxos/protocols';
|
|
38
|
+
import { type SpaceSyncState } from '@dxos/protocols/proto/dxos/echo/service';
|
|
38
39
|
import { type DocHeadsList, type FlushRequest } from '@dxos/protocols/proto/dxos/echo/service';
|
|
39
40
|
import { trace } from '@dxos/tracing';
|
|
40
|
-
import { bufferToArray } from '@dxos/util';
|
|
41
|
+
import { ComplexSet, bufferToArray, isNonNullable, range } from '@dxos/util';
|
|
41
42
|
|
|
42
|
-
import { CollectionSynchronizer, diffCollectionState
|
|
43
|
+
import { type CollectionState, CollectionSynchronizer, diffCollectionState } from './collection-synchronizer';
|
|
43
44
|
import { type EchoDataMonitor } from './echo-data-monitor';
|
|
44
45
|
import { EchoNetworkAdapter, isEchoPeerMetadata } from './echo-network-adapter';
|
|
45
46
|
import { type EchoReplicator, type RemoteDocumentExistenceCheckParams } from './echo-replicator';
|
|
46
47
|
import { HeadsStore } from './heads-store';
|
|
47
|
-
import {
|
|
48
|
+
import { type BeforeSaveParams, LevelDBStorageAdapter } from './leveldb-storage-adapter';
|
|
48
49
|
|
|
49
50
|
export type PeerIdProvider = () => string | undefined;
|
|
50
51
|
|
|
@@ -52,7 +53,6 @@ export type RootDocumentSpaceKeyProvider = (documentId: string) => PublicKey | u
|
|
|
52
53
|
|
|
53
54
|
export type AutomergeHostParams = {
|
|
54
55
|
db: LevelDB;
|
|
55
|
-
|
|
56
56
|
indexMetadataStore: IndexMetadataStore;
|
|
57
57
|
dataMonitor?: EchoDataMonitor;
|
|
58
58
|
|
|
@@ -78,6 +78,19 @@ export const FIND_PARAMS = {
|
|
|
78
78
|
allowableStates: ['ready', 'requesting'] satisfies HandleState[],
|
|
79
79
|
};
|
|
80
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Maximum amount of documents to sync in a single bundle.
|
|
83
|
+
*/
|
|
84
|
+
const BUNDLE_SIZE = 100;
|
|
85
|
+
/**
|
|
86
|
+
* Maximum amount of concurrent tasks to run when pushing or pulling bundles.
|
|
87
|
+
*/
|
|
88
|
+
const BUNDLE_SYNC_CONCURRENCY = 2;
|
|
89
|
+
/**
|
|
90
|
+
* If the number of documents to sync is greater than this threshold, we will use bundles.
|
|
91
|
+
*/
|
|
92
|
+
const BUNDLE_SYNC_THRESHOLD = 50;
|
|
93
|
+
|
|
81
94
|
/**
|
|
82
95
|
* Abstracts over the AutomergeRepo.
|
|
83
96
|
*/
|
|
@@ -97,6 +110,14 @@ export class AutomergeHost extends Resource {
|
|
|
97
110
|
private _storage!: StorageAdapterInterface & Lifecycle;
|
|
98
111
|
private readonly _headsStore: HeadsStore;
|
|
99
112
|
|
|
113
|
+
private _syncTask: DeferredTask | undefined = undefined;
|
|
114
|
+
/**
|
|
115
|
+
* Cache of collections that would be synced on next sync task run.
|
|
116
|
+
*/
|
|
117
|
+
private readonly _collectionsToSync = new ComplexSet<{ collectionId: string; peerId: PeerId }>(
|
|
118
|
+
({ collectionId, peerId }) => `${collectionId}|${peerId}`,
|
|
119
|
+
);
|
|
120
|
+
|
|
100
121
|
@trace.info()
|
|
101
122
|
private _peerId!: PeerId;
|
|
102
123
|
|
|
@@ -110,6 +131,9 @@ export class AutomergeHost extends Resource {
|
|
|
110
131
|
*/
|
|
111
132
|
public readonly documentsSaved = new Event();
|
|
112
133
|
|
|
134
|
+
private readonly _headsUpdates = new Map<DocumentId, Heads>();
|
|
135
|
+
private _onHeadsChangedTask?: DeferredTask | undefined;
|
|
136
|
+
|
|
113
137
|
constructor({
|
|
114
138
|
db,
|
|
115
139
|
indexMetadataStore,
|
|
@@ -143,6 +167,12 @@ export class AutomergeHost extends Resource {
|
|
|
143
167
|
protected override async _open(): Promise<void> {
|
|
144
168
|
this._peerId = `host-${this._peerIdProvider?.() ?? PublicKey.random().toHex()}` as PeerId;
|
|
145
169
|
|
|
170
|
+
this._onHeadsChangedTask = new DeferredTask(this._ctx, async () => {
|
|
171
|
+
const docHeads = Array.from(this._headsUpdates.entries());
|
|
172
|
+
this._headsUpdates.clear();
|
|
173
|
+
this._onHeadsChanged(docHeads);
|
|
174
|
+
});
|
|
175
|
+
|
|
146
176
|
await this._storage.open?.();
|
|
147
177
|
|
|
148
178
|
// Construct the automerge repo.
|
|
@@ -180,6 +210,22 @@ export class AutomergeHost extends Resource {
|
|
|
180
210
|
}
|
|
181
211
|
});
|
|
182
212
|
|
|
213
|
+
this._syncTask = new DeferredTask(this._ctx, async () => {
|
|
214
|
+
const collectionToSync = Array.from(this._collectionsToSync.values());
|
|
215
|
+
if (collectionToSync.length === 0) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
await Promise.all(
|
|
219
|
+
collectionToSync.map(async ({ collectionId, peerId }) => {
|
|
220
|
+
try {
|
|
221
|
+
await this._handleCollectionSync(collectionId, peerId);
|
|
222
|
+
} catch (err) {
|
|
223
|
+
log.error('failed to sync collection', { collectionId, peerId, err });
|
|
224
|
+
}
|
|
225
|
+
}),
|
|
226
|
+
);
|
|
227
|
+
});
|
|
228
|
+
|
|
183
229
|
await this._echoNetworkAdapter.open();
|
|
184
230
|
await this._collectionSynchronizer.open();
|
|
185
231
|
await this._echoNetworkAdapter.open();
|
|
@@ -190,7 +236,8 @@ export class AutomergeHost extends Resource {
|
|
|
190
236
|
await this._collectionSynchronizer.close();
|
|
191
237
|
await this._storage.close?.();
|
|
192
238
|
await this._echoNetworkAdapter.close();
|
|
193
|
-
|
|
239
|
+
this._syncTask = undefined;
|
|
240
|
+
this._onHeadsChangedTask = undefined;
|
|
194
241
|
}
|
|
195
242
|
|
|
196
243
|
/**
|
|
@@ -209,10 +256,12 @@ export class AutomergeHost extends Resource {
|
|
|
209
256
|
}
|
|
210
257
|
|
|
211
258
|
async addReplicator(replicator: EchoReplicator): Promise<void> {
|
|
259
|
+
invariant(this.isOpen, 'AutomergeHost is not open');
|
|
212
260
|
await this._echoNetworkAdapter.addReplicator(replicator);
|
|
213
261
|
}
|
|
214
262
|
|
|
215
263
|
async removeReplicator(replicator: EchoReplicator): Promise<void> {
|
|
264
|
+
invariant(this.isOpen, 'AutomergeHost is not open');
|
|
216
265
|
await this._echoNetworkAdapter.removeReplicator(replicator);
|
|
217
266
|
}
|
|
218
267
|
|
|
@@ -220,6 +269,7 @@ export class AutomergeHost extends Resource {
|
|
|
220
269
|
* Loads the document handle from the repo and waits for it to be ready.
|
|
221
270
|
*/
|
|
222
271
|
async loadDoc<T>(ctx: Context, documentId: AnyDocumentId, opts?: LoadDocOptions): Promise<DocHandle<T>> {
|
|
272
|
+
invariant(this.isOpen, 'AutomergeHost is not open');
|
|
223
273
|
let handle: DocHandle<T> | undefined;
|
|
224
274
|
if (typeof documentId === 'string') {
|
|
225
275
|
// NOTE: documentId might also be a URL, in which case this lookup will fail.
|
|
@@ -242,6 +292,7 @@ export class AutomergeHost extends Resource {
|
|
|
242
292
|
}
|
|
243
293
|
|
|
244
294
|
async exportDoc(ctx: Context, id: AnyDocumentId): Promise<Uint8Array> {
|
|
295
|
+
invariant(this.isOpen, 'AutomergeHost is not open');
|
|
245
296
|
const documentId = interpretAsDocumentId(id);
|
|
246
297
|
|
|
247
298
|
const chunks = await this._storage.loadRange([documentId]);
|
|
@@ -252,6 +303,7 @@ export class AutomergeHost extends Resource {
|
|
|
252
303
|
* Create new persisted document.
|
|
253
304
|
*/
|
|
254
305
|
createDoc<T>(initialValue?: T | Doc<T> | Uint8Array, opts?: CreateDocOptions): DocHandle<T> {
|
|
306
|
+
invariant(this.isOpen, 'AutomergeHost is not open');
|
|
255
307
|
if (opts?.preserveHistory) {
|
|
256
308
|
if (initialValue instanceof Uint8Array) {
|
|
257
309
|
return this._repo.import(initialValue);
|
|
@@ -273,6 +325,7 @@ export class AutomergeHost extends Resource {
|
|
|
273
325
|
}
|
|
274
326
|
|
|
275
327
|
async waitUntilHeadsReplicated(heads: DocHeadsList): Promise<void> {
|
|
328
|
+
invariant(this.isOpen, 'AutomergeHost is not open');
|
|
276
329
|
const entries = heads.entries;
|
|
277
330
|
if (!entries?.length) {
|
|
278
331
|
return;
|
|
@@ -289,7 +342,7 @@ export class AutomergeHost extends Resource {
|
|
|
289
342
|
});
|
|
290
343
|
if (headsToWait.length > 0) {
|
|
291
344
|
await Promise.all(
|
|
292
|
-
headsToWait.map(async (entry
|
|
345
|
+
headsToWait.map(async (entry) => {
|
|
293
346
|
const handle = await this.loadDoc<DatabaseDirectory>(Context.default(), entry.documentId as DocumentId);
|
|
294
347
|
await waitForHeads(handle, entry.heads!);
|
|
295
348
|
}),
|
|
@@ -303,6 +356,7 @@ export class AutomergeHost extends Resource {
|
|
|
303
356
|
}
|
|
304
357
|
|
|
305
358
|
async reIndexHeads(documentIds: DocumentId[]): Promise<void> {
|
|
359
|
+
invariant(this.isOpen, 'AutomergeHost is not open');
|
|
306
360
|
for (const documentId of documentIds) {
|
|
307
361
|
log('re-indexing heads for document', { documentId });
|
|
308
362
|
const handle = await this._repo.find(documentId, FIND_PARAMS);
|
|
@@ -375,14 +429,25 @@ export class AutomergeHost extends Resource {
|
|
|
375
429
|
* Called by AutomergeStorageAdapter after levelDB batch commit.
|
|
376
430
|
*/
|
|
377
431
|
private async _afterSave(path: StorageKey): Promise<void> {
|
|
378
|
-
this.
|
|
432
|
+
if (!this.isOpen) {
|
|
433
|
+
return undefined;
|
|
434
|
+
}
|
|
379
435
|
|
|
436
|
+
this._indexMetadataStore.notifyMarkedDirty();
|
|
380
437
|
const documentId = path[0] as DocumentId;
|
|
381
|
-
const
|
|
382
|
-
if (
|
|
383
|
-
|
|
384
|
-
this._onHeadsChanged(documentId, heads);
|
|
438
|
+
const handle = this._repo.handles[documentId];
|
|
439
|
+
if (!handle || !handle.isReady()) {
|
|
440
|
+
return;
|
|
385
441
|
}
|
|
442
|
+
const document = handle.doc();
|
|
443
|
+
if (!document) {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const heads = getHeads(document);
|
|
448
|
+
this._headsUpdates.set(documentId, heads);
|
|
449
|
+
invariant(this._onHeadsChangedTask, 'onHeadsChangedTask is not initialized');
|
|
450
|
+
this._onHeadsChangedTask.schedule();
|
|
386
451
|
this.documentsSaved.emit();
|
|
387
452
|
}
|
|
388
453
|
|
|
@@ -433,10 +498,12 @@ export class AutomergeHost extends Resource {
|
|
|
433
498
|
async flush({ documentIds }: FlushRequest = {}): Promise<void> {
|
|
434
499
|
// Note: Sync protocol for client and services ensures that all handles should have all changes.
|
|
435
500
|
|
|
436
|
-
const loadedDocuments = documentIds
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
501
|
+
const loadedDocuments = (documentIds ?? Object.keys(this._repo.handles)).filter(
|
|
502
|
+
(documentId): documentId is DocumentId => {
|
|
503
|
+
const handle = this._repo.handles[documentId as DocumentId];
|
|
504
|
+
return handle && handle.isReady();
|
|
505
|
+
},
|
|
506
|
+
);
|
|
440
507
|
await this._repo.flush(loadedDocuments);
|
|
441
508
|
}
|
|
442
509
|
|
|
@@ -479,8 +546,8 @@ export class AutomergeHost extends Resource {
|
|
|
479
546
|
this._collectionSynchronizer.refreshCollection(collectionId);
|
|
480
547
|
}
|
|
481
548
|
|
|
482
|
-
async getCollectionSyncState(collectionId: string): Promise<
|
|
483
|
-
const result:
|
|
549
|
+
async getCollectionSyncState(collectionId: string): Promise<SpaceSyncState> {
|
|
550
|
+
const result: SpaceSyncState = {
|
|
484
551
|
peers: [],
|
|
485
552
|
};
|
|
486
553
|
|
|
@@ -493,13 +560,16 @@ export class AutomergeHost extends Resource {
|
|
|
493
560
|
|
|
494
561
|
for (const [peerId, state] of remoteState) {
|
|
495
562
|
const diff = diffCollectionState(localState, state);
|
|
496
|
-
result.peers
|
|
563
|
+
result.peers!.push({
|
|
497
564
|
peerId,
|
|
498
565
|
missingOnRemote: diff.missingOnRemote.length,
|
|
499
566
|
missingOnLocal: diff.missingOnLocal.length,
|
|
500
567
|
differentDocuments: diff.different.length,
|
|
501
|
-
localDocumentCount: Object.
|
|
502
|
-
remoteDocumentCount: Object.
|
|
568
|
+
localDocumentCount: Object.entries(localState.documents).filter(([_, heads]) => heads.length > 0).length,
|
|
569
|
+
remoteDocumentCount: Object.entries(state.documents).filter(([_, heads]) => heads.length > 0).length,
|
|
570
|
+
|
|
571
|
+
totalDocumentCount: new Set([...Object.keys(localState.documents), ...Object.keys(state.documents)]).size,
|
|
572
|
+
unsyncedDocumentCount: new Set([...diff.missingOnLocal, ...diff.missingOnRemote, ...diff.different]).size,
|
|
503
573
|
});
|
|
504
574
|
}
|
|
505
575
|
|
|
@@ -515,6 +585,16 @@ export class AutomergeHost extends Resource {
|
|
|
515
585
|
heads.map((heads, index) => [documentIds[index], heads ?? []]),
|
|
516
586
|
);
|
|
517
587
|
this._collectionSynchronizer.setLocalCollectionState(collectionId, { documents });
|
|
588
|
+
|
|
589
|
+
// Proactively push our updated local state to peers that are interested in this collection.
|
|
590
|
+
// This reduces reliance on the next periodic query and prevents replication stalls in fast paths
|
|
591
|
+
// where the remote queries before our local state is ready.
|
|
592
|
+
const interestedPeers = this._echoNetworkAdapter.getPeersInterestedInCollection(collectionId);
|
|
593
|
+
if (interestedPeers.length > 0) {
|
|
594
|
+
for (const peerId of interestedPeers) {
|
|
595
|
+
this._sendCollectionState(collectionId, peerId, { documents });
|
|
596
|
+
}
|
|
597
|
+
}
|
|
518
598
|
}
|
|
519
599
|
|
|
520
600
|
async clearLocalCollectionState(collectionId: string): Promise<void> {
|
|
@@ -546,6 +626,11 @@ export class AutomergeHost extends Resource {
|
|
|
546
626
|
}
|
|
547
627
|
|
|
548
628
|
private _onRemoteCollectionStateUpdated(collectionId: string, peerId: PeerId): void {
|
|
629
|
+
this._collectionsToSync.add({ collectionId, peerId });
|
|
630
|
+
this._syncTask?.schedule();
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
private async _handleCollectionSync(collectionId: string, peerId: PeerId) {
|
|
549
634
|
const localState = this._collectionSynchronizer.getLocalCollectionState(collectionId);
|
|
550
635
|
const remoteState = this._collectionSynchronizer.getRemoteCollectionStates(collectionId).get(peerId);
|
|
551
636
|
|
|
@@ -554,36 +639,179 @@ export class AutomergeHost extends Resource {
|
|
|
554
639
|
}
|
|
555
640
|
|
|
556
641
|
const { different, missingOnLocal, missingOnRemote } = diffCollectionState(localState, remoteState);
|
|
557
|
-
const toReplicate = [...missingOnLocal, ...missingOnRemote, ...different];
|
|
558
642
|
|
|
559
|
-
if (
|
|
643
|
+
if (different.length === 0 && missingOnLocal.length === 0 && missingOnRemote.length === 0) {
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const toReplicateWithoutBatching = [...different];
|
|
648
|
+
const bundleSyncEnabled = this._echoNetworkAdapter.bundleSyncEnabledForPeer(peerId);
|
|
649
|
+
if (bundleSyncEnabled && missingOnRemote.length >= BUNDLE_SYNC_THRESHOLD) {
|
|
650
|
+
log('pushing bundle', { amount: missingOnRemote.length });
|
|
651
|
+
const { syncInteractively } = await this._pushInBundles(peerId, missingOnRemote);
|
|
652
|
+
toReplicateWithoutBatching.push(...syncInteractively);
|
|
653
|
+
} else {
|
|
654
|
+
log.verbose('failed to push bundle, replicating interactively', {
|
|
655
|
+
collectionId,
|
|
656
|
+
peerId,
|
|
657
|
+
amount: missingOnRemote.length,
|
|
658
|
+
});
|
|
659
|
+
toReplicateWithoutBatching.push(...missingOnRemote);
|
|
660
|
+
}
|
|
661
|
+
if (bundleSyncEnabled && missingOnLocal.length >= BUNDLE_SYNC_THRESHOLD) {
|
|
662
|
+
log('pulling bundle', { amount: missingOnLocal.length });
|
|
663
|
+
const { syncInteractively } = await this._pullInBundles(peerId, missingOnLocal);
|
|
664
|
+
toReplicateWithoutBatching.push(...syncInteractively);
|
|
665
|
+
} else {
|
|
666
|
+
log.verbose('failed to pull bundle, replicating interactively', {
|
|
667
|
+
collectionId,
|
|
668
|
+
peerId,
|
|
669
|
+
amount: missingOnLocal.length,
|
|
670
|
+
});
|
|
671
|
+
toReplicateWithoutBatching.push(...missingOnLocal);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
if (toReplicateWithoutBatching.length === 0) {
|
|
560
675
|
return;
|
|
561
676
|
}
|
|
562
677
|
|
|
563
678
|
log('replicating documents after collection sync', {
|
|
564
679
|
collectionId,
|
|
565
680
|
peerId,
|
|
566
|
-
|
|
567
|
-
count:
|
|
681
|
+
toReplicateWithoutBatching,
|
|
682
|
+
count: toReplicateWithoutBatching.length,
|
|
568
683
|
});
|
|
569
684
|
|
|
570
685
|
// Load the documents so they will start syncing.
|
|
571
|
-
for (const documentId of
|
|
686
|
+
for (const documentId of toReplicateWithoutBatching) {
|
|
572
687
|
this._repo.findWithProgress(documentId);
|
|
573
688
|
}
|
|
574
689
|
}
|
|
575
690
|
|
|
576
|
-
|
|
691
|
+
// TODO(mykola): Add retries of batches https://gist.github.com/mykola-vrmchk/fde270259e9209fcbf1331e5abbf12cf
|
|
692
|
+
// TODO(mykola): Use effect to retry batches.
|
|
693
|
+
private async _pushInBundles(
|
|
694
|
+
peerId: PeerId,
|
|
695
|
+
documentIds: DocumentId[],
|
|
696
|
+
): Promise<{ syncInteractively: DocumentId[] }> {
|
|
697
|
+
const documentsToPush = [...documentIds];
|
|
698
|
+
const syncInteractively: DocumentId[] = [];
|
|
699
|
+
|
|
700
|
+
// Push bundles in parallel with BUNDLE_SYNC_CONCURRENCY max concurrent tasks.
|
|
701
|
+
while (documentsToPush.length > 0) {
|
|
702
|
+
await Promise.all(
|
|
703
|
+
range(BUNDLE_SYNC_CONCURRENCY).map(async () => {
|
|
704
|
+
const bundle = documentsToPush.splice(0, BUNDLE_SIZE);
|
|
705
|
+
if (bundle.length === 0) {
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
await this._pushBundle(peerId, bundle).catch((err) => {
|
|
709
|
+
log.warn('failed to push bundle, replicating interactively', { peerId, bundle, err });
|
|
710
|
+
syncInteractively.push(...bundle);
|
|
711
|
+
});
|
|
712
|
+
}),
|
|
713
|
+
);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
return { syncInteractively };
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
private async _pushBundle(peerId: PeerId, documentIds: DocumentId[]): Promise<void> {
|
|
720
|
+
if (this._ctx.disposed) {
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const docs = documentIds.map((documentId) => {
|
|
725
|
+
const handle = this._repo.handles[documentId];
|
|
726
|
+
if (!handle || !handle.isReady()) {
|
|
727
|
+
log.warn('document not ready, skipping', { documentId });
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
const doc = handle.doc();
|
|
731
|
+
if (!doc) {
|
|
732
|
+
log.warn('document not available, skipping', { documentId });
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
return {
|
|
736
|
+
documentId,
|
|
737
|
+
data: save(doc),
|
|
738
|
+
heads: getHeads(doc),
|
|
739
|
+
};
|
|
740
|
+
});
|
|
741
|
+
|
|
742
|
+
await this._echoNetworkAdapter.pushBundle(peerId, docs.filter(isNonNullable));
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
private async _pullInBundles(
|
|
746
|
+
peerId: PeerId,
|
|
747
|
+
documentIds: DocumentId[],
|
|
748
|
+
): Promise<{ syncInteractively: DocumentId[] }> {
|
|
749
|
+
const documentsToPull = [...documentIds];
|
|
750
|
+
const syncInteractively: DocumentId[] = [];
|
|
751
|
+
const docsToImport: Record<DocumentId, Uint8Array> = {};
|
|
752
|
+
|
|
753
|
+
// Pull bundles in parallel with BUNDLE_SYNC_CONCURRENCY max concurrent tasks.
|
|
754
|
+
while (documentsToPull.length > 0) {
|
|
755
|
+
await Promise.all(
|
|
756
|
+
range(BUNDLE_SYNC_CONCURRENCY).map(async () => {
|
|
757
|
+
const bundle = documentsToPull.splice(0, BUNDLE_SIZE);
|
|
758
|
+
if (bundle.length === 0) {
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
const result = await this._pullBundle(peerId, bundle).catch((err) => {
|
|
762
|
+
log.warn('failed to pull bundle, replicating interactively', { peerId, bundle, err });
|
|
763
|
+
syncInteractively.push(...bundle);
|
|
764
|
+
});
|
|
765
|
+
if (result) {
|
|
766
|
+
Object.assign(docsToImport, result.docsToImport);
|
|
767
|
+
}
|
|
768
|
+
}),
|
|
769
|
+
);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
for (const [documentId, data] of Object.entries(docsToImport)) {
|
|
773
|
+
this._repo.import(data, { docId: documentId as DocumentId });
|
|
774
|
+
}
|
|
775
|
+
await this._repo.flush(Object.keys(docsToImport) as DocumentId[]);
|
|
776
|
+
|
|
777
|
+
return { syncInteractively };
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
private async _pullBundle(
|
|
781
|
+
peerId: PeerId,
|
|
782
|
+
documentIds: DocumentId[],
|
|
783
|
+
): Promise<{ docsToImport: Record<DocumentId, Uint8Array> } | undefined> {
|
|
784
|
+
if (this._ctx.disposed) {
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
// NOTE: We are expecting that documents that are being pulled are not present locally, so we are pulling all changes.
|
|
788
|
+
const docHeads = Object.fromEntries(documentIds.map((documentId) => [documentId, []]));
|
|
789
|
+
const bundle = await this._echoNetworkAdapter.pullBundle(peerId, docHeads);
|
|
790
|
+
return { docsToImport: bundle };
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
private _onHeadsChanged(docHeads: [DocumentId, Heads][]): void {
|
|
577
794
|
const collectionsChanged = new Set<CollectionId>();
|
|
795
|
+
|
|
578
796
|
for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
|
|
579
797
|
const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
798
|
+
let newState: CollectionState | undefined;
|
|
799
|
+
|
|
800
|
+
for (const [documentId, heads] of docHeads) {
|
|
801
|
+
if (state?.documents[documentId]) {
|
|
802
|
+
if (!newState) {
|
|
803
|
+
newState = structuredClone(state);
|
|
804
|
+
}
|
|
805
|
+
newState.documents[documentId] = heads;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
if (newState) {
|
|
583
810
|
this._collectionSynchronizer.setLocalCollectionState(collectionId, newState);
|
|
584
811
|
collectionsChanged.add(collectionId as CollectionId);
|
|
585
812
|
}
|
|
586
813
|
}
|
|
814
|
+
|
|
587
815
|
for (const collectionId of collectionsChanged) {
|
|
588
816
|
this.collectionStateUpdated.emit({ collectionId });
|
|
589
817
|
}
|
|
@@ -619,35 +847,3 @@ const decodeCollectionState = (state: unknown): CollectionState => {
|
|
|
619
847
|
const encodeCollectionState = (state: CollectionState): unknown => {
|
|
620
848
|
return state;
|
|
621
849
|
};
|
|
622
|
-
|
|
623
|
-
export type CollectionSyncState = {
|
|
624
|
-
peers: PeerSyncState[];
|
|
625
|
-
};
|
|
626
|
-
|
|
627
|
-
export type PeerSyncState = {
|
|
628
|
-
peerId: PeerId;
|
|
629
|
-
/**
|
|
630
|
-
* Documents that are present locally but not on the remote peer.
|
|
631
|
-
*/
|
|
632
|
-
missingOnRemote: number;
|
|
633
|
-
|
|
634
|
-
/**
|
|
635
|
-
* Documents that are present on the remote peer but not locally.
|
|
636
|
-
*/
|
|
637
|
-
missingOnLocal: number;
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Documents that are present on both peers but have different heads.
|
|
641
|
-
*/
|
|
642
|
-
differentDocuments: number;
|
|
643
|
-
|
|
644
|
-
/**
|
|
645
|
-
* Total number of documents locally.
|
|
646
|
-
*/
|
|
647
|
-
localDocumentCount: number;
|
|
648
|
-
|
|
649
|
-
/**
|
|
650
|
-
* Total number of documents on the remote peer.
|
|
651
|
-
*/
|
|
652
|
-
remoteDocumentCount: number;
|
|
653
|
-
};
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
//
|
|
4
4
|
|
|
5
5
|
import {
|
|
6
|
+
next as A,
|
|
6
7
|
type Heads,
|
|
7
8
|
change,
|
|
8
9
|
clone,
|
|
@@ -10,7 +11,6 @@ import {
|
|
|
10
11
|
from,
|
|
11
12
|
getBackend,
|
|
12
13
|
getHeads,
|
|
13
|
-
next as A,
|
|
14
14
|
save,
|
|
15
15
|
saveSince,
|
|
16
16
|
} from '@automerge/automerge';
|
|
@@ -19,14 +19,14 @@ import {
|
|
|
19
19
|
type DocHandle,
|
|
20
20
|
type DocumentId,
|
|
21
21
|
type HandleState,
|
|
22
|
-
type StorageAdapterInterface,
|
|
23
22
|
type PeerId,
|
|
24
23
|
Repo,
|
|
25
24
|
type SharePolicy,
|
|
25
|
+
type StorageAdapterInterface,
|
|
26
26
|
generateAutomergeUrl,
|
|
27
27
|
parseAutomergeUrl,
|
|
28
28
|
} from '@automerge/automerge-repo';
|
|
29
|
-
import {
|
|
29
|
+
import { describe, expect, onTestFinished, test } from 'vitest';
|
|
30
30
|
|
|
31
31
|
import { asyncTimeout, sleep } from '@dxos/async';
|
|
32
32
|
import { randomBytes } from '@dxos/crypto';
|
|
@@ -36,11 +36,12 @@ import { TestBuilder as TeleportBuilder, TestPeer as TeleportPeer } from '@dxos/
|
|
|
36
36
|
import { openAndClose } from '@dxos/test-utils';
|
|
37
37
|
import { isNonNullable, range } from '@dxos/util';
|
|
38
38
|
|
|
39
|
+
import { TestAdapter, type TestConnectionStateProvider } from '../testing';
|
|
40
|
+
|
|
39
41
|
import { FIND_PARAMS } from './automerge-host';
|
|
40
42
|
import { EchoNetworkAdapter } from './echo-network-adapter';
|
|
41
43
|
import { LevelDBStorageAdapter } from './leveldb-storage-adapter';
|
|
42
44
|
import { MeshEchoReplicator } from './mesh-echo-replicator';
|
|
43
|
-
import { TestAdapter, type TestConnectionStateProvider } from '../testing';
|
|
44
45
|
|
|
45
46
|
const HOST_AND_CLIENT: [string, string] = ['host', 'client'];
|
|
46
47
|
|
|
@@ -420,13 +421,7 @@ describe('AutomergeRepo', () => {
|
|
|
420
421
|
|
|
421
422
|
test('client creates doc and syncs with a Repo', async () => {
|
|
422
423
|
const repo = new Repo({ network: [] });
|
|
423
|
-
const receiveByServer =
|
|
424
|
-
const serverHandle = await repo.find(docId, FIND_PARAMS);
|
|
425
|
-
serverHandle.update((doc) => {
|
|
426
|
-
return A.loadIncremental(doc, blob);
|
|
427
|
-
});
|
|
428
|
-
};
|
|
429
|
-
|
|
424
|
+
const receiveByServer = (blob: Uint8Array, docId: DocumentId) => repo.import<any>(blob, { docId });
|
|
430
425
|
let clientDoc = A.from<{ field?: string }>({});
|
|
431
426
|
const { documentId } = parseAutomergeUrl(generateAutomergeUrl());
|
|
432
427
|
// Sync handshake.
|
|
@@ -434,7 +429,7 @@ describe('AutomergeRepo', () => {
|
|
|
434
429
|
|
|
435
430
|
// Sync protocol.
|
|
436
431
|
const sendDoc = async (doc: A.Doc<any>) => {
|
|
437
|
-
|
|
432
|
+
receiveByServer(saveSince(doc, sentHeads), documentId);
|
|
438
433
|
sentHeads = getHeads(doc);
|
|
439
434
|
};
|
|
440
435
|
|
|
@@ -456,10 +451,9 @@ describe('AutomergeRepo', () => {
|
|
|
456
451
|
|
|
457
452
|
const repo = new Repo({ network: [], storage });
|
|
458
453
|
const receiveByServer = async (blob: Uint8Array, docId: DocumentId) => {
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
});
|
|
454
|
+
repo.import<any>(blob, { docId });
|
|
455
|
+
// TODO(mykola): This should not be required. Document is not persisted without it.
|
|
456
|
+
await repo.flush([docId]);
|
|
463
457
|
};
|
|
464
458
|
|
|
465
459
|
let clientDoc = A.from<{ field?: string }>({ field: 'foo' });
|
|
@@ -677,6 +671,63 @@ describe('AutomergeRepo', () => {
|
|
|
677
671
|
await doc.whenReady();
|
|
678
672
|
expect(doc.doc()).to.deep.eq(document.doc());
|
|
679
673
|
});
|
|
674
|
+
|
|
675
|
+
test('document is passively replicated to connected peers', async () => {
|
|
676
|
+
const [spaceKey] = PublicKey.randomSequence();
|
|
677
|
+
|
|
678
|
+
const teleportBuilder = new TeleportBuilder();
|
|
679
|
+
onTestFinished(() => teleportBuilder.destroy());
|
|
680
|
+
|
|
681
|
+
const peer1 = await createTeleportTestPeer(teleportBuilder, spaceKey);
|
|
682
|
+
const peer2 = await createTeleportTestPeer(teleportBuilder, spaceKey);
|
|
683
|
+
|
|
684
|
+
const handle = peer1.repo.create();
|
|
685
|
+
handle.change((doc: any) => (doc.text = 'hello'));
|
|
686
|
+
await connectPeers(spaceKey, teleportBuilder, peer1, peer2);
|
|
687
|
+
|
|
688
|
+
await expect
|
|
689
|
+
.poll(async () => {
|
|
690
|
+
const doc = peer2.repo.handles[handle.documentId];
|
|
691
|
+
await doc.whenReady();
|
|
692
|
+
return doc.doc()!.text;
|
|
693
|
+
})
|
|
694
|
+
.toEqual('hello');
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
test('imported document is passively replicated to connected peers', async () => {
|
|
698
|
+
let blob: Uint8Array;
|
|
699
|
+
let documentId: DocumentId;
|
|
700
|
+
{
|
|
701
|
+
const repo = new Repo();
|
|
702
|
+
const handle = repo.create();
|
|
703
|
+
handle.change((doc: any) => (doc.text = 'hello'));
|
|
704
|
+
blob = A.save(handle.doc()!);
|
|
705
|
+
documentId = handle.documentId;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
const [spaceKey] = PublicKey.randomSequence();
|
|
709
|
+
|
|
710
|
+
const teleportBuilder = new TeleportBuilder();
|
|
711
|
+
onTestFinished(() => teleportBuilder.destroy());
|
|
712
|
+
|
|
713
|
+
const peer1 = await createTeleportTestPeer(teleportBuilder, spaceKey);
|
|
714
|
+
const peer2 = await createTeleportTestPeer(teleportBuilder, spaceKey);
|
|
715
|
+
await connectPeers(spaceKey, teleportBuilder, peer1, peer2);
|
|
716
|
+
|
|
717
|
+
const handle = peer1.repo.import(blob, { docId: documentId });
|
|
718
|
+
await handle.whenReady();
|
|
719
|
+
|
|
720
|
+
await expect
|
|
721
|
+
.poll(
|
|
722
|
+
async () => {
|
|
723
|
+
const doc = peer2.repo.handles[handle.documentId];
|
|
724
|
+
await doc.whenReady();
|
|
725
|
+
return doc.doc()!.text;
|
|
726
|
+
},
|
|
727
|
+
{ timeout: 1_000 },
|
|
728
|
+
)
|
|
729
|
+
.toEqual('hello');
|
|
730
|
+
});
|
|
680
731
|
});
|
|
681
732
|
|
|
682
733
|
const createLevelAdapter = async () => {
|