@dxos/echo-pipeline 0.8.4-main.84f28bd → 0.8.4-main.ae835ea
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-GBFX5J5B.mjs → chunk-FR6GJ4S4.mjs} +239 -162
- package/dist/lib/browser/chunk-FR6GJ4S4.mjs.map +7 -0
- package/dist/lib/browser/chunk-WJJXJTNS.mjs +240 -0
- package/dist/lib/browser/chunk-WJJXJTNS.mjs.map +7 -0
- package/dist/lib/browser/filter/index.mjs +3 -1
- package/dist/lib/browser/index.mjs +1094 -345
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +36 -14
- package/dist/lib/browser/testing/index.mjs.map +3 -3
- package/dist/lib/node-esm/{chunk-FQFKWA3X.mjs → chunk-JQCCVDLT.mjs} +239 -162
- package/dist/lib/node-esm/chunk-JQCCVDLT.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-LEQ77KAT.mjs +240 -0
- package/dist/lib/node-esm/chunk-LEQ77KAT.mjs.map +7 -0
- package/dist/lib/node-esm/filter/index.mjs +3 -1
- package/dist/lib/node-esm/index.mjs +1094 -345
- 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 +36 -14
- 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 +3 -2
- 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 +13 -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-data.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/testing/test-schema.d.ts +1 -1
- package/dist/types/src/testing/test-schema.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 +40 -38
- package/src/automerge/automerge-host.test.ts +18 -8
- package/src/automerge/automerge-host.ts +273 -74
- package/src/automerge/automerge-repo.test.ts +67 -16
- package/src/automerge/collection-synchronizer.test.ts +6 -5
- package/src/automerge/collection-synchronizer.ts +16 -11
- 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 +10 -2
- 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 +105 -27
- package/src/filter/filter-match.test.ts +33 -13
- package/src/filter/filter-match.ts +164 -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 +154 -14
- 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-data.ts +1 -1
- package/src/testing/test-replicator.ts +4 -0
- package/src/testing/test-schema.ts +1 -1
- 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);
|
|
@@ -324,10 +378,6 @@ export class AutomergeHost extends Resource {
|
|
|
324
378
|
// NOTE: If both peers return sharePolicy=false the replication will not happen
|
|
325
379
|
// https://github.com/automerge/automerge-repo/pull/292
|
|
326
380
|
private async _sharePolicy(peerId: PeerId, documentId?: DocumentId): Promise<boolean> {
|
|
327
|
-
if (peerId.startsWith('client-')) {
|
|
328
|
-
return false; // Only send docs to clients if they are requested.
|
|
329
|
-
}
|
|
330
|
-
|
|
331
381
|
if (!documentId) {
|
|
332
382
|
return false;
|
|
333
383
|
}
|
|
@@ -375,14 +425,25 @@ export class AutomergeHost extends Resource {
|
|
|
375
425
|
* Called by AutomergeStorageAdapter after levelDB batch commit.
|
|
376
426
|
*/
|
|
377
427
|
private async _afterSave(path: StorageKey): Promise<void> {
|
|
378
|
-
this.
|
|
428
|
+
if (!this.isOpen) {
|
|
429
|
+
return undefined;
|
|
430
|
+
}
|
|
379
431
|
|
|
432
|
+
this._indexMetadataStore.notifyMarkedDirty();
|
|
380
433
|
const documentId = path[0] as DocumentId;
|
|
381
|
-
const
|
|
382
|
-
if (
|
|
383
|
-
|
|
384
|
-
|
|
434
|
+
const handle = this._repo.handles[documentId];
|
|
435
|
+
if (!handle || !handle.isReady()) {
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
const document = handle.doc();
|
|
439
|
+
if (!document) {
|
|
440
|
+
return;
|
|
385
441
|
}
|
|
442
|
+
|
|
443
|
+
const heads = getHeads(document);
|
|
444
|
+
this._headsUpdates.set(documentId, heads);
|
|
445
|
+
invariant(this._onHeadsChangedTask, 'onHeadsChangedTask is not initialized');
|
|
446
|
+
this._onHeadsChangedTask.schedule();
|
|
386
447
|
this.documentsSaved.emit();
|
|
387
448
|
}
|
|
388
449
|
|
|
@@ -433,11 +494,17 @@ export class AutomergeHost extends Resource {
|
|
|
433
494
|
async flush({ documentIds }: FlushRequest = {}): Promise<void> {
|
|
434
495
|
// Note: Sync protocol for client and services ensures that all handles should have all changes.
|
|
435
496
|
|
|
436
|
-
const loadedDocuments = documentIds
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
497
|
+
const loadedDocuments = (documentIds ?? Object.keys(this._repo.handles)).filter(
|
|
498
|
+
(documentId): documentId is DocumentId => {
|
|
499
|
+
const handle = this._repo.handles[documentId as DocumentId];
|
|
500
|
+
return handle && handle.isReady();
|
|
501
|
+
},
|
|
502
|
+
);
|
|
440
503
|
await this._repo.flush(loadedDocuments);
|
|
504
|
+
|
|
505
|
+
// Ensure that document verions have propagated accross the system.
|
|
506
|
+
// This is important for the case where we are doing flush and then waiting for sync to happen.
|
|
507
|
+
await this._onHeadsChangedTask?.runBlocking();
|
|
441
508
|
}
|
|
442
509
|
|
|
443
510
|
async getHeads(documentIds: DocumentId[]): Promise<(Heads | undefined)[]> {
|
|
@@ -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,182 @@ 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
|
-
if (state
|
|
581
|
-
|
|
582
|
-
|
|
798
|
+
if (!state) {
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
let newState: CollectionState | undefined;
|
|
802
|
+
|
|
803
|
+
for (const [documentId, heads] of docHeads) {
|
|
804
|
+
if (documentId in state.documents) {
|
|
805
|
+
if (!newState) {
|
|
806
|
+
newState = structuredClone(state);
|
|
807
|
+
}
|
|
808
|
+
newState.documents[documentId] = heads;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
if (newState) {
|
|
583
813
|
this._collectionSynchronizer.setLocalCollectionState(collectionId, newState);
|
|
584
814
|
collectionsChanged.add(collectionId as CollectionId);
|
|
585
815
|
}
|
|
586
816
|
}
|
|
817
|
+
|
|
587
818
|
for (const collectionId of collectionsChanged) {
|
|
588
819
|
this.collectionStateUpdated.emit({ collectionId });
|
|
589
820
|
}
|
|
@@ -619,35 +850,3 @@ const decodeCollectionState = (state: unknown): CollectionState => {
|
|
|
619
850
|
const encodeCollectionState = (state: CollectionState): unknown => {
|
|
620
851
|
return state;
|
|
621
852
|
};
|
|
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
|
-
};
|