@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.
Files changed (140) hide show
  1. package/dist/lib/browser/{chunk-GBFX5J5B.mjs → chunk-FR6GJ4S4.mjs} +239 -162
  2. package/dist/lib/browser/chunk-FR6GJ4S4.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-WJJXJTNS.mjs +240 -0
  4. package/dist/lib/browser/chunk-WJJXJTNS.mjs.map +7 -0
  5. package/dist/lib/browser/filter/index.mjs +3 -1
  6. package/dist/lib/browser/index.mjs +1094 -345
  7. package/dist/lib/browser/index.mjs.map +4 -4
  8. package/dist/lib/browser/meta.json +1 -1
  9. package/dist/lib/browser/testing/index.mjs +36 -14
  10. package/dist/lib/browser/testing/index.mjs.map +3 -3
  11. package/dist/lib/node-esm/{chunk-FQFKWA3X.mjs → chunk-JQCCVDLT.mjs} +239 -162
  12. package/dist/lib/node-esm/chunk-JQCCVDLT.mjs.map +7 -0
  13. package/dist/lib/node-esm/chunk-LEQ77KAT.mjs +240 -0
  14. package/dist/lib/node-esm/chunk-LEQ77KAT.mjs.map +7 -0
  15. package/dist/lib/node-esm/filter/index.mjs +3 -1
  16. package/dist/lib/node-esm/index.mjs +1094 -345
  17. package/dist/lib/node-esm/index.mjs.map +4 -4
  18. package/dist/lib/node-esm/meta.json +1 -1
  19. package/dist/lib/node-esm/testing/index.mjs +36 -14
  20. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  21. package/dist/types/src/automerge/automerge-host.d.ts +15 -28
  22. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  23. package/dist/types/src/automerge/collection-synchronizer.d.ts +3 -2
  24. package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
  25. package/dist/types/src/automerge/echo-network-adapter.d.ts +8 -1
  26. package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
  27. package/dist/types/src/automerge/echo-replicator.d.ts +21 -2
  28. package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
  29. package/dist/types/src/automerge/index.d.ts +1 -1
  30. package/dist/types/src/automerge/index.d.ts.map +1 -1
  31. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts +1 -1
  32. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts.map +1 -1
  33. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +1 -0
  34. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
  35. package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
  36. package/dist/types/src/common/codec.d.ts +1 -1
  37. package/dist/types/src/common/codec.d.ts.map +1 -1
  38. package/dist/types/src/db-host/data-service.d.ts +2 -2
  39. package/dist/types/src/db-host/data-service.d.ts.map +1 -1
  40. package/dist/types/src/db-host/database-root.d.ts.map +1 -1
  41. package/dist/types/src/db-host/documents-synchronizer.d.ts +2 -2
  42. package/dist/types/src/db-host/documents-synchronizer.d.ts.map +1 -1
  43. package/dist/types/src/db-host/echo-host.d.ts +2 -2
  44. package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
  45. package/dist/types/src/db-host/query-service.d.ts +1 -1
  46. package/dist/types/src/db-host/query-service.d.ts.map +1 -1
  47. package/dist/types/src/db-host/space-state-manager.d.ts +1 -1
  48. package/dist/types/src/db-host/space-state-manager.d.ts.map +1 -1
  49. package/dist/types/src/edge/echo-edge-replicator.d.ts +4 -2
  50. package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
  51. package/dist/types/src/filter/filter-match.d.ts +4 -1
  52. package/dist/types/src/filter/filter-match.d.ts.map +1 -1
  53. package/dist/types/src/metadata/metadata-store.d.ts +1 -1
  54. package/dist/types/src/metadata/metadata-store.d.ts.map +1 -1
  55. package/dist/types/src/pipeline/pipeline.d.ts +1 -1
  56. package/dist/types/src/pipeline/pipeline.d.ts.map +1 -1
  57. package/dist/types/src/query/errors.d.ts +24 -8
  58. package/dist/types/src/query/errors.d.ts.map +1 -1
  59. package/dist/types/src/query/plan.d.ts +8 -1
  60. package/dist/types/src/query/plan.d.ts.map +1 -1
  61. package/dist/types/src/query/query-executor.d.ts +13 -1
  62. package/dist/types/src/query/query-executor.d.ts.map +1 -1
  63. package/dist/types/src/query/query-planner.d.ts +2 -0
  64. package/dist/types/src/query/query-planner.d.ts.map +1 -1
  65. package/dist/types/src/space/admission-discovery-extension.d.ts.map +1 -1
  66. package/dist/types/src/space/control-pipeline.d.ts +1 -1
  67. package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
  68. package/dist/types/src/space/space-manager.d.ts +1 -1
  69. package/dist/types/src/space/space-manager.d.ts.map +1 -1
  70. package/dist/types/src/space/space-protocol.d.ts +1 -1
  71. package/dist/types/src/space/space-protocol.d.ts.map +1 -1
  72. package/dist/types/src/space/space.d.ts +1 -1
  73. package/dist/types/src/space/space.d.ts.map +1 -1
  74. package/dist/types/src/testing/test-agent-builder.d.ts +2 -2
  75. package/dist/types/src/testing/test-agent-builder.d.ts.map +1 -1
  76. package/dist/types/src/testing/test-data.d.ts.map +1 -1
  77. package/dist/types/src/testing/test-replicator.d.ts +1 -0
  78. package/dist/types/src/testing/test-replicator.d.ts.map +1 -1
  79. package/dist/types/src/testing/test-schema.d.ts +1 -1
  80. package/dist/types/src/testing/test-schema.d.ts.map +1 -1
  81. package/dist/types/src/util.d.ts +1 -1
  82. package/dist/types/src/util.d.ts.map +1 -1
  83. package/dist/types/tsconfig.tsbuildinfo +1 -1
  84. package/package.json +40 -38
  85. package/src/automerge/automerge-host.test.ts +18 -8
  86. package/src/automerge/automerge-host.ts +273 -74
  87. package/src/automerge/automerge-repo.test.ts +67 -16
  88. package/src/automerge/collection-synchronizer.test.ts +6 -5
  89. package/src/automerge/collection-synchronizer.ts +16 -11
  90. package/src/automerge/echo-data-monitor.ts +1 -1
  91. package/src/automerge/echo-network-adapter.test.ts +3 -3
  92. package/src/automerge/echo-network-adapter.ts +38 -6
  93. package/src/automerge/echo-replicator.ts +23 -2
  94. package/src/automerge/index.ts +1 -1
  95. package/src/automerge/leveldb-storage-adapter.ts +7 -7
  96. package/src/automerge/mesh-echo-replicator-connection.ts +4 -0
  97. package/src/automerge/mesh-echo-replicator.ts +2 -1
  98. package/src/automerge/storage-adapter.test.ts +1 -1
  99. package/src/common/space-id.ts +1 -1
  100. package/src/db-host/data-service.ts +9 -17
  101. package/src/db-host/database-root.ts +2 -2
  102. package/src/db-host/documents-synchronizer.test.ts +1 -1
  103. package/src/db-host/documents-synchronizer.ts +39 -26
  104. package/src/db-host/echo-host.ts +14 -15
  105. package/src/db-host/query-service.ts +10 -2
  106. package/src/db-host/space-state-manager.ts +2 -2
  107. package/src/edge/echo-edge-replicator.test.ts +5 -3
  108. package/src/edge/echo-edge-replicator.ts +105 -27
  109. package/src/filter/filter-match.test.ts +33 -13
  110. package/src/filter/filter-match.ts +164 -10
  111. package/src/metadata/metadata-store.ts +3 -3
  112. package/src/pipeline/pipeline-stress.test.ts +4 -2
  113. package/src/pipeline/pipeline.test.ts +3 -2
  114. package/src/pipeline/pipeline.ts +8 -5
  115. package/src/query/errors.ts +2 -0
  116. package/src/query/plan.ts +12 -1
  117. package/src/query/query-executor.ts +154 -14
  118. package/src/query/query-planner.test.ts +146 -2
  119. package/src/query/query-planner.ts +81 -11
  120. package/src/space/admission-discovery-extension.ts +2 -2
  121. package/src/space/control-pipeline.test.ts +4 -3
  122. package/src/space/control-pipeline.ts +9 -6
  123. package/src/space/space-manager.browser.test.ts +1 -1
  124. package/src/space/space-manager.ts +5 -4
  125. package/src/space/space-protocol.browser.test.ts +2 -2
  126. package/src/space/space-protocol.test.ts +3 -2
  127. package/src/space/space-protocol.ts +6 -3
  128. package/src/space/space.test.ts +1 -1
  129. package/src/space/space.ts +3 -2
  130. package/src/testing/test-agent-builder.ts +4 -3
  131. package/src/testing/test-data.ts +1 -1
  132. package/src/testing/test-replicator.ts +4 -0
  133. package/src/testing/test-schema.ts +1 -1
  134. package/src/util.ts +1 -1
  135. package/dist/lib/browser/chunk-ANZAS5CC.mjs +0 -126
  136. package/dist/lib/browser/chunk-ANZAS5CC.mjs.map +0 -7
  137. package/dist/lib/browser/chunk-GBFX5J5B.mjs.map +0 -7
  138. package/dist/lib/node-esm/chunk-2SAZ7CCF.mjs +0 -126
  139. package/dist/lib/node-esm/chunk-2SAZ7CCF.mjs.map +0 -7
  140. package/dist/lib/node-esm/chunk-FQFKWA3X.mjs.map +0 -7
@@ -3,17 +3,15 @@
3
3
  //
4
4
 
5
5
  import { next as A, type Heads } from '@automerge/automerge';
6
- import { type Repo, type DocHandle, type DocumentId } from '@automerge/automerge-repo';
6
+ import { type DocHandle, type DocumentId, type Repo } from '@automerge/automerge-repo';
7
7
 
8
- import { UpdateScheduler } from '@dxos/async';
9
- import { Resource } from '@dxos/context';
8
+ import { UpdateScheduler, sleep } from '@dxos/async';
9
+ import { LifecycleState, Resource, cancelWithContext } from '@dxos/context';
10
10
  import { type DatabaseDirectory } from '@dxos/echo-protocol';
11
11
  import { invariant } from '@dxos/invariant';
12
12
  import { log } from '@dxos/log';
13
13
  import { type BatchedDocumentUpdates, type DocumentUpdate } from '@dxos/protocols/proto/dxos/echo/service';
14
14
 
15
- import { FIND_PARAMS } from '../automerge';
16
-
17
15
  const MAX_UPDATE_FREQ = 10; // [updates/sec]
18
16
 
19
17
  export type DocumentsSynchronizerParams = {
@@ -27,6 +25,9 @@ interface DocSyncState {
27
25
  clearSubscriptions?: () => void;
28
26
  }
29
27
 
28
+ const WRAP_AROUND_RETRY_LIMIT = 3;
29
+ const WRAP_AROUND_RETRY_INITIAL_DELAY = 100; // [ms]
30
+
30
31
  /**
31
32
  * Manages a connection and replication between worker's Automerge Repo and the client's Repo.
32
33
  */
@@ -47,8 +48,12 @@ export class DocumentsSynchronizer extends Resource {
47
48
  super();
48
49
  }
49
50
 
50
- addDocuments(documentIds: DocumentId[], retryCounter = 0): void {
51
- if (retryCounter > 3) {
51
+ addDocuments(
52
+ documentIds: DocumentId[],
53
+ retryCounter = 0,
54
+ wrapAroundRetryDelay = WRAP_AROUND_RETRY_INITIAL_DELAY,
55
+ ): void {
56
+ if (retryCounter > WRAP_AROUND_RETRY_LIMIT) {
52
57
  log.warn('Failed to load document, retry limit reached', { documentIds });
53
58
  return;
54
59
  }
@@ -64,7 +69,9 @@ export class DocumentsSynchronizer extends Resource {
64
69
  })
65
70
  .catch((error) => {
66
71
  log.warn('Failed to load document, wraparound', { documentId, error });
67
- this.addDocuments([documentId], retryCounter + 1);
72
+ void cancelWithContext(this._ctx, sleep(wrapAroundRetryDelay)).then(() =>
73
+ this.addDocuments([documentId], retryCounter + 1, wrapAroundRetryDelay * 2),
74
+ );
68
75
  });
69
76
  }
70
77
  }
@@ -90,17 +97,13 @@ export class DocumentsSynchronizer extends Resource {
90
97
 
91
98
  async update(updates: DocumentUpdate[]): Promise<void> {
92
99
  for (const { documentId, mutation, isNew } of updates) {
93
- if (isNew) {
94
- const doc = await this._params.repo.find<DatabaseDirectory>(documentId as DocumentId, FIND_PARAMS);
95
- doc.update((doc) => A.loadIncremental(doc, mutation));
96
- this._startSync(doc);
97
- } else {
98
- this._writeMutation(documentId as DocumentId, mutation);
99
- }
100
+ this._writeMutation(documentId as DocumentId, mutation, isNew);
100
101
  }
102
+ // TODO(mykola): This should not be required.
103
+ await this._params.repo.flush(updates.map(({ documentId }) => documentId as DocumentId));
101
104
  }
102
105
 
103
- private _startSync(doc: DocHandle<DatabaseDirectory>): void {
106
+ private _startSync(doc: DocHandle<DatabaseDirectory>) {
104
107
  if (this._syncStates.has(doc.documentId)) {
105
108
  log('Document already being synced', { documentId: doc.documentId });
106
109
  return;
@@ -109,6 +112,7 @@ export class DocumentsSynchronizer extends Resource {
109
112
  const syncState: DocSyncState = { handle: doc };
110
113
  this._subscribeForChanges(syncState);
111
114
  this._syncStates.set(doc.documentId, syncState);
115
+ return syncState;
112
116
  }
113
117
 
114
118
  _subscribeForChanges(syncState: DocSyncState): void {
@@ -157,16 +161,25 @@ export class DocumentsSynchronizer extends Resource {
157
161
  return mutation;
158
162
  }
159
163
 
160
- private _writeMutation(documentId: DocumentId, mutation: Uint8Array): void {
161
- const syncState = this._syncStates.get(documentId);
162
- invariant(syncState, 'Sync state for document not found');
163
- syncState.handle.update((doc) => {
164
- const headsBefore = A.getHeads(doc);
165
- const newDoc = A.loadIncremental(doc, mutation);
166
- if (A.equals(headsBefore, syncState.lastSentHead)) {
167
- syncState.lastSentHead = A.getHeads(newDoc);
164
+ private _writeMutation(documentId: DocumentId, mutation: Uint8Array, isNew?: boolean): void {
165
+ if (this._lifecycleState === LifecycleState.CLOSED) {
166
+ return;
167
+ }
168
+ if (isNew) {
169
+ const newHandle = this._params.repo.import<DatabaseDirectory>(mutation, { docId: documentId });
170
+ const syncState = this._startSync(newHandle);
171
+ syncState!.lastSentHead = A.getHeads(newHandle.doc());
172
+ } else {
173
+ const syncState = this._syncStates.get(documentId);
174
+ invariant(syncState, 'Sync state for document not found');
175
+ const headsBefore = A.getHeads(syncState.handle.doc());
176
+ // This will update corresponding handle in the repo.
177
+ this._params.repo.import(mutation, { docId: documentId });
178
+
179
+ if (A.equals(headsBefore, syncState!.lastSentHead)) {
180
+ // No new mutations were discovered on network, so we do not need to send updates from worker to client.
181
+ syncState!.lastSentHead = A.getHeads(syncState.handle.doc());
168
182
  }
169
- return newDoc;
170
- });
183
+ }
171
184
  }
172
185
  }
@@ -10,9 +10,9 @@ import {
10
10
  type Repo,
11
11
  } from '@automerge/automerge-repo';
12
12
 
13
- import { LifecycleState, Resource, type Context } from '@dxos/context';
13
+ import { type Context, LifecycleState, Resource } from '@dxos/context';
14
14
  import { todo } from '@dxos/debug';
15
- import { createIdFromSpaceKey, SpaceDocVersion, type DatabaseDirectory } from '@dxos/echo-protocol';
15
+ import { type DatabaseDirectory, SpaceDocVersion, createIdFromSpaceKey } from '@dxos/echo-protocol';
16
16
  import { IndexMetadataStore, IndexStore, Indexer } from '@dxos/indexing';
17
17
  import { invariant } from '@dxos/invariant';
18
18
  import { type PublicKey, type SpaceId } from '@dxos/keys';
@@ -20,24 +20,25 @@ import { type LevelDB } from '@dxos/kv-store';
20
20
  import { IndexKind } from '@dxos/protocols/proto/dxos/echo/indexing';
21
21
  import { trace } from '@dxos/tracing';
22
22
 
23
- import { DataServiceImpl } from './data-service';
24
- import { type DatabaseRoot } from './database-root';
25
- import { createSelectedDocumentsIterator } from './documents-iterator';
26
- import { QueryServiceImpl } from './query-service';
27
- import { SpaceStateManager } from './space-state-manager';
28
23
  import {
29
24
  AutomergeHost,
30
- FIND_PARAMS,
31
- EchoDataMonitor,
32
- deriveCollectionIdFromSpaceId,
33
- type LoadDocOptions,
34
25
  type CreateDocOptions,
35
- type EchoReplicator,
26
+ EchoDataMonitor,
36
27
  type EchoDataStats,
28
+ type EchoReplicator,
29
+ FIND_PARAMS,
30
+ type LoadDocOptions,
37
31
  type PeerIdProvider,
38
32
  type RootDocumentSpaceKeyProvider,
33
+ deriveCollectionIdFromSpaceId,
39
34
  } from '../automerge';
40
35
 
36
+ import { DataServiceImpl } from './data-service';
37
+ import { type DatabaseRoot } from './database-root';
38
+ import { createSelectedDocumentsIterator } from './documents-iterator';
39
+ import { QueryServiceImpl } from './query-service';
40
+ import { SpaceStateManager } from './space-state-manager';
41
+
41
42
  export interface EchoHostIndexingConfig {
42
43
  /**
43
44
  * @default true
@@ -197,8 +198,6 @@ export class EchoHost extends Resource {
197
198
  if (e.previousRootId) {
198
199
  void this._automergeHost.clearLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId, e.previousRootId));
199
200
  }
200
- // TODO(yaroslav): remove collection without spaceRootId after release (production<->staging interop)
201
- void this._automergeHost.updateLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId), e.documentIds);
202
201
  void this._automergeHost.updateLocalCollectionState(
203
202
  deriveCollectionIdFromSpaceId(e.spaceId, e.spaceRootId),
204
203
  e.documentIds,
@@ -220,7 +219,7 @@ export class EchoHost extends Resource {
220
219
  * Flush all pending writes to the underlying storage.
221
220
  */
222
221
  async flush(): Promise<void> {
223
- await this._automergeHost.repo.flush();
222
+ await this._automergeHost.flush();
224
223
  }
225
224
 
226
225
  /**
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { getHeads } from '@automerge/automerge';
6
6
  import { type DocHandle, type DocumentId } from '@automerge/automerge-repo';
7
- import { Schema } from 'effect';
7
+ import * as Schema from 'effect/Schema';
8
8
 
9
9
  import { DeferredTask, scheduleMicroTask, synchronized } from '@dxos/async';
10
10
  import { Stream } from '@dxos/codec-protobuf/stream';
@@ -23,10 +23,11 @@ import {
23
23
  } from '@dxos/protocols/proto/dxos/echo/query';
24
24
  import { trace } from '@dxos/tracing';
25
25
 
26
- import type { SpaceStateManager } from './space-state-manager';
27
26
  import { type AutomergeHost } from '../automerge';
28
27
  import { QueryExecutor } from '../query';
29
28
 
29
+ import type { SpaceStateManager } from './space-state-manager';
30
+
30
31
  export type QueryServiceParams = {
31
32
  indexer: Indexer;
32
33
  automergeHost: AutomergeHost;
@@ -55,6 +56,7 @@ type ActiveQuery = {
55
56
 
56
57
  @trace.resource()
57
58
  export class QueryServiceImpl extends Resource implements QueryService {
59
+ // TODO(dmaretskyi): We need to implement query deduping. Idle composer has 80 queries with only 10 being unique.
58
60
  private readonly _queries = new Set<ActiveQuery>();
59
61
 
60
62
  private _updateQueries!: DeferredTask;
@@ -96,6 +98,12 @@ export class QueryServiceImpl extends Resource implements QueryService {
96
98
 
97
99
  execQuery(request: QueryRequest): Stream<QueryResponse> {
98
100
  return new Stream<QueryResponse>(({ next, close, ctx }) => {
101
+ if (this._params.indexer.config?.enabled !== true) {
102
+ log.error('indexer is disabled', { config: this._params.indexer.config });
103
+ close();
104
+ return;
105
+ }
106
+
99
107
  const queryEntry = this._createQuery(ctx, request, next, close, close);
100
108
  scheduleMicroTask(ctx, async () => {
101
109
  await queryEntry.executor.open();
@@ -2,11 +2,11 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { interpretAsDocumentId, type DocHandle, type DocumentId } from '@automerge/automerge-repo';
5
+ import { type DocHandle, type DocumentId, interpretAsDocumentId } from '@automerge/automerge-repo';
6
6
  import isEqual from 'lodash.isequal';
7
7
 
8
8
  import { Event, UpdateScheduler } from '@dxos/async';
9
- import { Resource, Context, LifecycleState } from '@dxos/context';
9
+ import { Context, LifecycleState, Resource } from '@dxos/context';
10
10
  import { type DatabaseDirectory } from '@dxos/echo-protocol';
11
11
  import { invariant } from '@dxos/invariant';
12
12
  import { type SpaceId } from '@dxos/keys';
@@ -7,7 +7,7 @@ import { getRandomPort } from 'get-port-please';
7
7
  import { describe, expect, onTestFinished, test } from 'vitest';
8
8
 
9
9
  import { Event } from '@dxos/async';
10
- import { createEphemeralEdgeIdentity, EdgeClient, MessageSchema } from '@dxos/edge-client';
10
+ import { EdgeClient, type EdgeHttpClient, MessageSchema, createEphemeralEdgeIdentity } from '@dxos/edge-client';
11
11
  import { createTestEdgeWsServer } from '@dxos/edge-client/testing';
12
12
  import { PublicKey, SpaceId } from '@dxos/keys';
13
13
  import { EdgeService } from '@dxos/protocols';
@@ -16,9 +16,10 @@ import { createBuf } from '@dxos/protocols/buf';
16
16
  import type { Peer } from '@dxos/protocols/proto/dxos/edge/messenger';
17
17
  import { openAndClose } from '@dxos/test-utils';
18
18
 
19
- import { EchoEdgeReplicator } from './echo-edge-replicator';
20
19
  import type { EchoReplicatorContext, ReplicatorConnection } from '../automerge';
21
20
 
21
+ import { EchoEdgeReplicator } from './echo-edge-replicator';
22
+
22
23
  describe('EchoEdgeReplicator', () => {
23
24
  test('reconnects', async () => {
24
25
  const { client, server } = await createClientServer();
@@ -79,7 +80,8 @@ describe('EchoEdgeReplicator', () => {
79
80
  });
80
81
 
81
82
  const connectReplicator = async (client: EdgeClient, context: EchoReplicatorContext) => {
82
- const replicator = new EchoEdgeReplicator({ edgeConnection: client });
83
+ // EdgeHttpClient functionality is not tested here.
84
+ const replicator = new EchoEdgeReplicator({ edgeConnection: client, edgeHttpClient: {} as EdgeHttpClient });
83
85
  await replicator.connect(context);
84
86
  onTestFinished(() => replicator.disconnect());
85
87
  return replicator;
@@ -2,34 +2,43 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { cbor } from '@automerge/automerge-repo';
5
+ import * as Automerge from '@automerge/automerge';
6
+ import { type DocumentId, type Heads, cbor } from '@automerge/automerge-repo';
6
7
 
7
- import { Mutex, scheduleTask, scheduleMicroTask } from '@dxos/async';
8
+ import { Mutex, scheduleMicroTask, scheduleTask } from '@dxos/async';
8
9
  import { Context, Resource } from '@dxos/context';
9
10
  import { randomUUID } from '@dxos/crypto';
10
11
  import type { CollectionId } from '@dxos/echo-protocol';
11
- import { type EdgeConnection } from '@dxos/edge-client';
12
+ import { type EdgeConnection, type EdgeHttpClient } from '@dxos/edge-client';
12
13
  import { invariant } from '@dxos/invariant';
13
14
  import type { SpaceId } from '@dxos/keys';
14
15
  import { log } from '@dxos/log';
15
- import { EdgeService, type AutomergeProtocolMessage, type PeerId } from '@dxos/protocols';
16
+ import {
17
+ type AutomergeProtocolMessage,
18
+ DocumentCodec,
19
+ EdgeService,
20
+ type ExportBundleRequest,
21
+ type ImportBundleRequest,
22
+ type PeerId,
23
+ } from '@dxos/protocols';
16
24
  import { buf } from '@dxos/protocols/buf';
17
25
  import {
18
26
  type Message as RouterMessage,
19
27
  MessageSchema as RouterMessageSchema,
20
28
  } from '@dxos/protocols/buf/dxos/edge/messenger_pb';
21
- import { bufferToArray } from '@dxos/util';
29
+ import { bufferToArray, setDeep } from '@dxos/util';
22
30
 
23
- import { InflightRequestLimiter } from './inflight-request-limiter';
24
31
  import {
25
- getSpaceIdFromCollectionId,
26
32
  type EchoReplicator,
27
33
  type EchoReplicatorContext,
28
34
  type ReplicatorConnection,
29
35
  type ShouldAdvertiseParams,
30
36
  type ShouldSyncCollectionParams,
37
+ getSpaceIdFromCollectionId,
31
38
  } from '../automerge';
32
39
 
40
+ import { InflightRequestLimiter } from './inflight-request-limiter';
41
+
33
42
  /**
34
43
  * Delay before restarting the connection after receiving a forbidden error.
35
44
  */
@@ -39,11 +48,13 @@ const MAX_RESTART_DELAY = 5000;
39
48
 
40
49
  export type EchoEdgeReplicatorParams = {
41
50
  edgeConnection: EdgeConnection;
51
+ edgeHttpClient: EdgeHttpClient;
42
52
  disableSharePolicy?: boolean;
43
53
  };
44
54
 
45
55
  export class EchoEdgeReplicator implements EchoReplicator {
46
56
  private readonly _edgeConnection: EdgeConnection;
57
+ private readonly _edgeHttpClient: EdgeHttpClient;
47
58
  private readonly _mutex = new Mutex();
48
59
 
49
60
  private _ctx?: Context = undefined;
@@ -52,8 +63,9 @@ export class EchoEdgeReplicator implements EchoReplicator {
52
63
  private _connections = new Map<SpaceId, EdgeReplicatorConnection>();
53
64
  private _sharePolicyEnabled = true;
54
65
 
55
- constructor({ edgeConnection, disableSharePolicy }: EchoEdgeReplicatorParams) {
66
+ constructor({ edgeConnection, edgeHttpClient, disableSharePolicy }: EchoEdgeReplicatorParams) {
56
67
  this._edgeConnection = edgeConnection;
68
+ this._edgeHttpClient = edgeHttpClient;
57
69
  this._sharePolicyEnabled = !disableSharePolicy;
58
70
  }
59
71
 
@@ -127,14 +139,17 @@ export class EchoEdgeReplicator implements EchoReplicator {
127
139
  let restartScheduled = false;
128
140
 
129
141
  const connection = new EdgeReplicatorConnection({
142
+ edgeHttpClient: this._edgeHttpClient,
130
143
  edgeConnection: this._edgeConnection,
131
144
  spaceId,
132
145
  context: this._context,
133
146
  sharedPolicyEnabled: this._sharePolicyEnabled,
134
147
  onRemoteConnected: async () => {
148
+ log.trace('dxos.echo.edge.replicator.onRemoteConnected', { spaceId });
135
149
  this._context?.onConnectionOpen(connection);
136
150
  },
137
151
  onRemoteDisconnected: async () => {
152
+ log.trace('dxos.echo.edge.replicator.onRemoteDisconnected', { spaceId });
138
153
  this._context?.onConnectionClosed(connection);
139
154
  },
140
155
  onRestartRequested: async () => {
@@ -162,6 +177,7 @@ export class EchoEdgeReplicator implements EchoReplicator {
162
177
  if (ctx?.disposed) {
163
178
  return;
164
179
  }
180
+ log.trace('dxos.echo.edge.replicator.restart', { spaceId, reconnects, restartDelay });
165
181
  await this._openConnection(spaceId, reconnects + 1);
166
182
  },
167
183
  restartDelay,
@@ -176,6 +192,7 @@ export class EchoEdgeReplicator implements EchoReplicator {
176
192
 
177
193
  type EdgeReplicatorConnectionsParams = {
178
194
  edgeConnection: EdgeConnection;
195
+ edgeHttpClient: EdgeHttpClient;
179
196
  spaceId: SpaceId;
180
197
  context: EchoReplicatorContext;
181
198
  sharedPolicyEnabled: boolean;
@@ -188,7 +205,9 @@ const MAX_INFLIGHT_REQUESTS = 5;
188
205
  const MAX_RATE_LIMIT_WAIT_TIME_MS = 3000;
189
206
 
190
207
  class EdgeReplicatorConnection extends Resource implements ReplicatorConnection {
208
+ private readonly _connectionId = randomUUID();
191
209
  private readonly _edgeConnection: EdgeConnection;
210
+ private readonly _edgeHttpClient: EdgeHttpClient;
192
211
  private readonly _remotePeerId: string | null = null;
193
212
  private readonly _targetServiceId: string;
194
213
  private readonly _spaceId: SpaceId;
@@ -197,6 +216,7 @@ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection
197
216
  private readonly _onRemoteConnected: () => Promise<void>;
198
217
  private readonly _onRemoteDisconnected: () => Promise<void>;
199
218
  private readonly _onRestartRequested: () => void;
219
+ private _sequence = 0;
200
220
 
201
221
  private _requestLimiter = new InflightRequestLimiter({
202
222
  maxInflightRequests: MAX_INFLIGHT_REQUESTS,
@@ -210,6 +230,7 @@ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection
210
230
 
211
231
  constructor({
212
232
  edgeConnection,
233
+ edgeHttpClient,
213
234
  spaceId,
214
235
  context,
215
236
  sharedPolicyEnabled,
@@ -219,13 +240,14 @@ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection
219
240
  }: EdgeReplicatorConnectionsParams) {
220
241
  super();
221
242
  this._edgeConnection = edgeConnection;
243
+ this._edgeHttpClient = edgeHttpClient;
222
244
  this._spaceId = spaceId;
223
245
  this._context = context;
224
246
  // Generate a unique peer id for every connection.
225
247
  // This way automerge-repo will have separate sync states for every connection.
226
248
  // This is important because the previous connection might have had some messages that failed to deliver
227
249
  // abd if we don't clear the sync-state, automerge will not attempt to deliver them again.
228
- this._remotePeerId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}-${randomUUID()}`;
250
+ this._remotePeerId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}-${this._connectionId}`;
229
251
  this._targetServiceId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}`;
230
252
  this._sharedPolicyEnabled = sharedPolicyEnabled;
231
253
  this._onRemoteConnected = onRemoteConnected;
@@ -252,13 +274,26 @@ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection
252
274
 
253
275
  await this._requestLimiter.open();
254
276
 
255
- // TODO: handle reconnects
256
277
  this._ctx.onDispose(
257
278
  this._edgeConnection.onMessage((msg: RouterMessage) => {
258
279
  this._onMessage(msg);
259
280
  }),
260
281
  );
261
282
 
283
+ let firstReconnect = true;
284
+ this._ctx.onDispose(
285
+ // NOTE: This will fire immediately if the connection is already open.
286
+ this._edgeConnection.onReconnected(async () => {
287
+ if (firstReconnect) {
288
+ log.verbose('first reconnect skipped');
289
+ firstReconnect = false;
290
+ return;
291
+ }
292
+
293
+ this._onRestartRequested();
294
+ }),
295
+ );
296
+
262
297
  await this._onRemoteConnected();
263
298
  }
264
299
 
@@ -317,8 +352,7 @@ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection
317
352
 
318
353
  const payload = cbor.decode(message.payload!.value) as AutomergeProtocolMessage;
319
354
  log.verbose('received', {
320
- type: payload.type,
321
- documentId: payload.type === 'sync' && payload.documentId,
355
+ ...getMessageInfo(payload),
322
356
  remoteId: this._remotePeerId,
323
357
  });
324
358
 
@@ -327,11 +361,32 @@ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection
327
361
  this._processMessage(payload);
328
362
  }
329
363
 
364
+ get bundleSyncEnabled(): boolean {
365
+ return true;
366
+ }
367
+
368
+ async pushBundle(bundle: { documentId: DocumentId; data: Uint8Array; heads: Heads }[]) {
369
+ const request: ImportBundleRequest = {
370
+ bundle: bundle.map(({ documentId, data, heads }) => ({
371
+ documentId,
372
+ mutation: DocumentCodec.encode(data),
373
+ heads,
374
+ })),
375
+ };
376
+ await this._edgeHttpClient.importBundle(this._spaceId, request);
377
+ }
378
+
379
+ async pullBundle(docHeads: Record<DocumentId, Heads>): Promise<Record<DocumentId, Uint8Array>> {
380
+ const request: ExportBundleRequest = { docHeads };
381
+ const response = await this._edgeHttpClient.exportBundle(this._spaceId, request);
382
+ return Object.fromEntries(response.bundle.map((doc) => [doc.documentId, DocumentCodec.decode(doc.mutation)]));
383
+ }
384
+
330
385
  private _processMessage(message: AutomergeProtocolMessage): void {
331
386
  // There's a race between the credentials being replicated that are needed for access control and the data replication.
332
387
  // AutomergeReplicator might return a Forbidden error if the credentials are not yet replicated.
333
388
  // We restart the connection with some delay to account for that.
334
- if (isForbiddenErrorMessage(message)) {
389
+ if (isErrorMessage(message)) {
335
390
  this._onRestartRequested();
336
391
  return;
337
392
  }
@@ -345,29 +400,52 @@ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection
345
400
  // Fix the peer id.
346
401
  (message as any).targetId = this._targetServiceId as PeerId;
347
402
 
403
+ // Note: This is used on EDGE to detect out-of-order messages per connection.
404
+ setDeep(message, ['metadata', 'dxos_sequence'], this._getSequence());
405
+ setDeep(message, ['metadata', 'dxos_connectionId'], this._connectionId);
406
+
348
407
  log.verbose('sending...', {
349
- type: message.type,
350
- documentId: message.type === 'sync' && message.documentId,
408
+ ...getMessageInfo(message),
351
409
  remoteId: this._remotePeerId,
352
410
  });
353
411
 
354
412
  const encoded = cbor.encode(message);
355
413
 
356
- await this._edgeConnection.send(
357
- buf.create(RouterMessageSchema, {
358
- serviceId: this._targetServiceId,
359
- source: {
360
- identityKey: this._edgeConnection.identityKey,
361
- peerKey: this._edgeConnection.peerKey,
362
- },
363
- payload: { value: bufferToArray(encoded) },
364
- }),
365
- );
414
+ try {
415
+ await this._edgeConnection.send(
416
+ buf.create(RouterMessageSchema, {
417
+ serviceId: this._targetServiceId,
418
+ source: {
419
+ identityKey: this._edgeConnection.identityKey,
420
+ peerKey: this._edgeConnection.peerKey,
421
+ },
422
+ payload: { value: bufferToArray(encoded) },
423
+ }),
424
+ );
425
+ } catch (err) {
426
+ log.error('failed to send message', { err });
427
+ }
428
+ }
429
+
430
+ private _getSequence(): number {
431
+ return this._sequence++;
366
432
  }
367
433
  }
368
434
 
369
435
  /**
370
436
  * This message is sent by EDGE AutomergeReplicator when the authorization is denied.
371
437
  */
372
- const isForbiddenErrorMessage = (message: AutomergeProtocolMessage) =>
373
- message.type === 'error' && message.message === 'Forbidden';
438
+ const isErrorMessage = (message: AutomergeProtocolMessage) => message.type === 'error';
439
+
440
+ const getMessageInfo = (msg: AutomergeProtocolMessage) => {
441
+ const { have, heads, need, changes } = msg.type === 'sync' ? Automerge.decodeSyncMessage(msg.data) : {};
442
+ return {
443
+ type: msg.type,
444
+ documentId: 'documentId' in msg ? msg.documentId : undefined,
445
+ have,
446
+ heads,
447
+ need,
448
+ changes: changes?.length,
449
+ sequence: msg.metadata?.dxos_sequence,
450
+ };
451
+ };
@@ -5,18 +5,30 @@
5
5
  import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { Filter } from '@dxos/echo';
8
+ import { EXPANDO_TYPENAME, Expando, Ref } from '@dxos/echo/internal';
8
9
  import { ObjectStructure } from '@dxos/echo-protocol';
9
- import { Expando, EXPANDO_TYPENAME, Ref } from '@dxos/echo-schema';
10
10
  import { DXN, ObjectId, SpaceId } from '@dxos/keys';
11
11
 
12
- import { filterMatchObject, type MatchedObject } from './filter-match';
12
+ import { type MatchedObject, filterMatchObject } from './filter-match';
13
13
 
14
14
  describe('filterMatch', () => {
15
+ test('everything', () => {
16
+ expect(filterMatchObject(Filter.everything().ast, OBJECT_1)).to.be.true;
17
+ expect(filterMatchObject(Filter.everything().ast, OBJECT_2)).to.be.true;
18
+ });
19
+
20
+ test('nothing', () => {
21
+ expect(filterMatchObject(Filter.nothing().ast, OBJECT_1)).to.be.false;
22
+ expect(filterMatchObject(Filter.nothing().ast, OBJECT_2)).to.be.false;
23
+ });
24
+
15
25
  test('properties', () => {
16
26
  expect(filterMatchObject(Filter.type(Expando, { title: 'test' }).ast, OBJECT_1)).to.be.true;
17
27
  expect(filterMatchObject(Filter.type(Expando, { value: 100 }).ast, OBJECT_1)).to.be.true;
18
28
  expect(filterMatchObject(Filter.type(Expando, { complete: false }).ast, OBJECT_1)).to.be.false;
19
29
  expect(filterMatchObject(Filter.type(Expando, { missing: undefined }).ast, OBJECT_1)).to.be.true;
30
+ expect(filterMatchObject(Filter.type(Expando, { properties: { subject: 'test' } }).ast, OBJECT_1)).to.be.true;
31
+ expect(filterMatchObject(Filter.type(Expando, { array: Filter.contains('two') }).ast, OBJECT_1)).to.be.true;
20
32
  });
21
33
 
22
34
  test('and', () => {
@@ -43,6 +55,17 @@ describe('filterMatch', () => {
43
55
  expect(filterMatchObject(filter2.ast, OBJECT_1)).to.be.false;
44
56
  });
45
57
 
58
+ test('contains', () => {
59
+ expect(filterMatchObject(Filter.type(Expando, { properties: { label: Filter.contains('test') } }).ast, OBJECT_1)).to
60
+ .be.true;
61
+ expect(
62
+ filterMatchObject(
63
+ Filter.type(Expando, { fields: Filter.contains({ label: 'label', value: 'test' }) }).ast,
64
+ OBJECT_1,
65
+ ),
66
+ ).to.be.true;
67
+ });
68
+
46
69
  test('complex', () => {
47
70
  const filter1 = Filter.type(Expando, { title: 'bad' });
48
71
  const filter2 = Filter.type(Expando, { value: 0 });
@@ -55,16 +78,6 @@ describe('filterMatch', () => {
55
78
  expect(filterMatchObject(filter.ast, OBJECT_2)).to.be.false;
56
79
  });
57
80
 
58
- test('everything', () => {
59
- expect(filterMatchObject(Filter.everything().ast, OBJECT_1)).to.be.true;
60
- expect(filterMatchObject(Filter.everything().ast, OBJECT_2)).to.be.true;
61
- });
62
-
63
- test('nothing', () => {
64
- expect(filterMatchObject(Filter.nothing().ast, OBJECT_1)).to.be.false;
65
- expect(filterMatchObject(Filter.nothing().ast, OBJECT_2)).to.be.false;
66
- });
67
-
68
81
  test('refs', () => {
69
82
  const filter = Filter.type(Expando, { parent: Ref.fromDXN(DXN.fromLocalObjectId(OBJECT_1.id)) });
70
83
  expect(filterMatchObject(filter.ast, OBJECT_1)).to.be.false;
@@ -78,7 +91,14 @@ const OBJECT_1: MatchedObject = {
78
91
  spaceId: SpaceId.make('B2NJDFNVZIW77OQSXUBNAD7BUMBD3G5PO'),
79
92
  doc: ObjectStructure.makeObject({
80
93
  type: DXN.fromTypenameAndVersion(EXPANDO_TYPENAME, '0.1.0').toString(),
81
- data: { title: 'test', value: 100, complete: true },
94
+ data: {
95
+ title: 'test',
96
+ value: 100,
97
+ complete: true,
98
+ array: ['one', 'two', 'three'],
99
+ properties: { label: ['test'], subject: 'test' },
100
+ fields: [{ label: 'label', value: 'test' }],
101
+ },
82
102
  }),
83
103
  };
84
104