@dxos/echo-pipeline 0.6.11 → 0.6.12-main.5a87ad5

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 (106) hide show
  1. package/dist/lib/browser/chunk-YTSGJIY7.mjs +2036 -0
  2. package/dist/lib/browser/chunk-YTSGJIY7.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +3401 -17
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +3 -4
  7. package/dist/lib/browser/testing/index.mjs.map +3 -3
  8. package/dist/lib/node/{chunk-7HHYCGUR.cjs → chunk-6SSC2M4R.cjs} +65 -37
  9. package/dist/lib/node/chunk-6SSC2M4R.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +3378 -35
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +11 -12
  14. package/dist/lib/node/testing/index.cjs.map +3 -3
  15. package/dist/lib/{browser/chunk-UKXIJW43.mjs → node-esm/chunk-ASOERPR6.mjs} +52 -26
  16. package/dist/lib/node-esm/chunk-ASOERPR6.mjs.map +7 -0
  17. package/dist/lib/{browser/chunk-MPWFDDQK.mjs → node-esm/index.mjs} +1623 -318
  18. package/dist/lib/node-esm/index.mjs.map +7 -0
  19. package/dist/lib/node-esm/meta.json +1 -0
  20. package/dist/lib/node-esm/testing/index.mjs +551 -0
  21. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  22. package/dist/types/src/automerge/automerge-host.d.ts +24 -1
  23. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  24. package/dist/types/src/automerge/collection-synchronizer.d.ts +2 -0
  25. package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
  26. package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
  27. package/dist/types/src/automerge/space-collection.d.ts +3 -2
  28. package/dist/types/src/automerge/space-collection.d.ts.map +1 -1
  29. package/dist/types/src/db-host/automerge-metrics.d.ts +11 -0
  30. package/dist/types/src/db-host/automerge-metrics.d.ts.map +1 -0
  31. package/dist/types/src/db-host/data-service.d.ts +3 -2
  32. package/dist/types/src/db-host/data-service.d.ts.map +1 -1
  33. package/dist/types/src/db-host/database-root.d.ts +20 -0
  34. package/dist/types/src/db-host/database-root.d.ts.map +1 -0
  35. package/dist/types/src/db-host/documents-iterator.d.ts +7 -0
  36. package/dist/types/src/db-host/documents-iterator.d.ts.map +1 -0
  37. package/dist/types/src/db-host/echo-host.d.ts +73 -0
  38. package/dist/types/src/db-host/echo-host.d.ts.map +1 -0
  39. package/dist/types/src/db-host/index.d.ts +5 -0
  40. package/dist/types/src/db-host/index.d.ts.map +1 -1
  41. package/dist/types/src/db-host/migration.d.ts +8 -0
  42. package/dist/types/src/db-host/migration.d.ts.map +1 -0
  43. package/dist/types/src/db-host/query-service.d.ts +25 -0
  44. package/dist/types/src/db-host/query-service.d.ts.map +1 -0
  45. package/dist/types/src/db-host/query-state.d.ts +41 -0
  46. package/dist/types/src/db-host/query-state.d.ts.map +1 -0
  47. package/dist/types/src/db-host/space-state-manager.d.ts +23 -0
  48. package/dist/types/src/db-host/space-state-manager.d.ts.map +1 -0
  49. package/dist/types/src/edge/echo-edge-replicator.d.ts +23 -0
  50. package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -0
  51. package/dist/types/src/edge/index.d.ts +2 -0
  52. package/dist/types/src/edge/index.d.ts.map +1 -0
  53. package/dist/types/src/index.d.ts +1 -0
  54. package/dist/types/src/index.d.ts.map +1 -1
  55. package/dist/types/src/testing/test-agent-builder.d.ts.map +1 -1
  56. package/package.json +40 -50
  57. package/src/automerge/automerge-host.test.ts +8 -9
  58. package/src/automerge/automerge-host.ts +42 -6
  59. package/src/automerge/automerge-repo.test.ts +18 -16
  60. package/src/automerge/collection-synchronizer.test.ts +10 -5
  61. package/src/automerge/collection-synchronizer.ts +17 -6
  62. package/src/automerge/echo-data-monitor.test.ts +1 -3
  63. package/src/automerge/echo-network-adapter.test.ts +4 -3
  64. package/src/automerge/mesh-echo-replicator.ts +2 -1
  65. package/src/automerge/space-collection.ts +3 -2
  66. package/src/automerge/storage-adapter.test.ts +2 -3
  67. package/src/db-host/automerge-metrics.ts +38 -0
  68. package/src/db-host/data-service.ts +29 -14
  69. package/src/db-host/database-root.ts +86 -0
  70. package/src/db-host/documents-iterator.ts +73 -0
  71. package/src/db-host/documents-synchronizer.test.ts +2 -2
  72. package/src/db-host/echo-host.ts +257 -0
  73. package/src/db-host/index.ts +6 -1
  74. package/src/db-host/migration.ts +57 -0
  75. package/src/db-host/query-service.ts +208 -0
  76. package/src/db-host/query-state.ts +200 -0
  77. package/src/db-host/space-state-manager.ts +90 -0
  78. package/src/edge/echo-edge-replicator.ts +286 -0
  79. package/src/edge/index.ts +5 -0
  80. package/src/index.ts +1 -0
  81. package/src/pipeline/pipeline-stress.test.ts +44 -47
  82. package/src/pipeline/pipeline.test.ts +3 -4
  83. package/src/space/control-pipeline.test.ts +2 -3
  84. package/src/space/control-pipeline.ts +10 -1
  85. package/src/space/replication.browser.test.ts +2 -8
  86. package/src/space/space-manager.browser.test.ts +6 -5
  87. package/src/space/space-protocol.browser.test.ts +29 -34
  88. package/src/space/space-protocol.test.ts +29 -27
  89. package/src/space/space.test.ts +28 -11
  90. package/src/testing/test-agent-builder.ts +2 -2
  91. package/dist/lib/browser/chunk-MPWFDDQK.mjs.map +0 -7
  92. package/dist/lib/browser/chunk-UKXIJW43.mjs.map +0 -7
  93. package/dist/lib/browser/chunk-XPCF2V5U.mjs +0 -31
  94. package/dist/lib/browser/chunk-XPCF2V5U.mjs.map +0 -7
  95. package/dist/lib/browser/light.mjs +0 -32
  96. package/dist/lib/browser/light.mjs.map +0 -7
  97. package/dist/lib/node/chunk-5DH4KR2S.cjs +0 -2148
  98. package/dist/lib/node/chunk-5DH4KR2S.cjs.map +0 -7
  99. package/dist/lib/node/chunk-7HHYCGUR.cjs.map +0 -7
  100. package/dist/lib/node/chunk-DZVH7HDD.cjs +0 -43
  101. package/dist/lib/node/chunk-DZVH7HDD.cjs.map +0 -7
  102. package/dist/lib/node/light.cjs +0 -52
  103. package/dist/lib/node/light.cjs.map +0 -7
  104. package/dist/types/src/light.d.ts +0 -4
  105. package/dist/types/src/light.d.ts.map +0 -1
  106. package/src/light.ts +0 -7
@@ -0,0 +1,200 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type DocumentId } from '@dxos/automerge/automerge-repo';
6
+ import { Context, LifecycleState, Resource } from '@dxos/context';
7
+ import { createIdFromSpaceKey } from '@dxos/echo-protocol';
8
+ import { type Indexer, type IndexQuery } from '@dxos/indexing';
9
+ import { invariant } from '@dxos/invariant';
10
+ import { PublicKey } from '@dxos/keys';
11
+ import { objectPointerCodec } from '@dxos/protocols';
12
+ import { type Filter as FilterProto } from '@dxos/protocols/proto/dxos/echo/filter';
13
+ import { type QueryRequest, type QueryResult } from '@dxos/protocols/proto/dxos/echo/query';
14
+ import { trace } from '@dxos/tracing';
15
+ import { nonNullable } from '@dxos/util';
16
+
17
+ import { type AutomergeHost, getSpaceKeyFromDoc } from '../automerge';
18
+
19
+ type QueryStateParams = {
20
+ indexer: Indexer;
21
+ automergeHost: AutomergeHost;
22
+ request: QueryRequest;
23
+ };
24
+
25
+ type QueryRunResult = {
26
+ changed: boolean;
27
+ };
28
+
29
+ export type QueryMetrics = {
30
+ objectsReturned: number;
31
+ objectsReturnedFromIndex: number;
32
+ documentsLoaded: number;
33
+ executionTime: number;
34
+ indexQueryTime: number;
35
+ documentLoadTime: number;
36
+ };
37
+
38
+ /**
39
+ * Manages querying logic on service side.
40
+ */
41
+ @trace.resource()
42
+ export class QueryState extends Resource {
43
+ private _results: QueryResult[] = [];
44
+
45
+ /**
46
+ * Metrics are only captured for the first run of the query since that is the most representative.
47
+ * We plan to change the query logic so that reactive updates do not require a full re-run of the query.
48
+ */
49
+ private _firstRun = true;
50
+
51
+ @trace.info({ depth: null })
52
+ public readonly filter: FilterProto;
53
+
54
+ @trace.info()
55
+ public metrics: QueryMetrics = {
56
+ objectsReturned: 0,
57
+ objectsReturnedFromIndex: 0,
58
+ documentsLoaded: 0,
59
+ executionTime: 0,
60
+ indexQueryTime: 0,
61
+ documentLoadTime: 0,
62
+ };
63
+
64
+ @trace.info()
65
+ get active() {
66
+ return this._lifecycleState === LifecycleState.OPEN;
67
+ }
68
+
69
+ constructor(private readonly _params: QueryStateParams) {
70
+ super();
71
+ this.filter = _params.request.filter;
72
+ }
73
+
74
+ getResults() {
75
+ return this._results;
76
+ }
77
+
78
+ // https://github.com/open-telemetry/semantic-conventions/blob/main/docs/attributes-registry/db.md#generic-database-attributes
79
+ @trace.span({ showInBrowserTimeline: true, op: 'db.query', attributes: { 'db.system': 'echo' } })
80
+ async execQuery(): Promise<QueryRunResult> {
81
+ const filter = this._params.request.filter;
82
+
83
+ const beginQuery = performance.now();
84
+
85
+ // For object id filters, we return no results as those are handled by the SpaceQuerySource.
86
+ const hits =
87
+ filter.objectIds && filter.objectIds?.length > 0
88
+ ? []
89
+ : await this._params.indexer.execQuery(filterToIndexQuery(filter));
90
+ if (this._firstRun) {
91
+ this.metrics.indexQueryTime = performance.now() - beginQuery;
92
+ }
93
+
94
+ const beginFilter = performance.now();
95
+
96
+ const results: QueryResult[] = (
97
+ await Promise.all(
98
+ hits.map(async (result) => {
99
+ if (this._firstRun) {
100
+ this.metrics.objectsReturnedFromIndex++;
101
+ }
102
+
103
+ const { objectId, documentId, spaceKey: spaceKeyInIndex } = objectPointerCodec.decode(result.id);
104
+
105
+ let spaceKey: string | null;
106
+ if (spaceKeyInIndex !== undefined) {
107
+ spaceKey = spaceKeyInIndex;
108
+ } else {
109
+ // Indexes created by older versions of the indexer do not have the spaceKey in the index.
110
+ // If the spaceKey is not in the index, we need to load the document to get it.
111
+
112
+ if (this._firstRun) {
113
+ this.metrics.documentsLoaded++;
114
+ }
115
+
116
+ const handle = await this._params.automergeHost.loadDoc(Context.default(), documentId as DocumentId);
117
+
118
+ // `whenReady` creates a timeout so we guard it with an if to skip it if the handle is already ready.
119
+ if (this._ctx.disposed) {
120
+ return;
121
+ }
122
+ spaceKey = getSpaceKeyFromDoc(handle.docSync());
123
+ }
124
+
125
+ if (!spaceKey) {
126
+ return;
127
+ }
128
+ // TODO(mykola): Remove business logic from here.
129
+ if (
130
+ this._params.request.filter.options?.spaces?.length &&
131
+ !this._params.request.filter.options.spaces.some((key) => key.equals(spaceKey!))
132
+ ) {
133
+ return;
134
+ }
135
+
136
+ if (this._firstRun) {
137
+ this.metrics.objectsReturned++;
138
+ }
139
+
140
+ return {
141
+ id: objectId,
142
+ documentId,
143
+ spaceId: await createIdFromSpaceKey(PublicKey.from(spaceKey)),
144
+ spaceKey: PublicKey.from(spaceKey),
145
+ rank: result.rank,
146
+ } satisfies QueryResult;
147
+ }),
148
+ )
149
+ ).filter(nonNullable);
150
+
151
+ if (this._firstRun) {
152
+ this.metrics.documentLoadTime = performance.now() - beginFilter;
153
+ }
154
+
155
+ if (this._ctx.disposed) {
156
+ return { changed: false };
157
+ }
158
+
159
+ const areResultsUnchanged =
160
+ !this._firstRun &&
161
+ this._results.length === results.length &&
162
+ this._results.every((oldResult) => results.some((result) => result.id === oldResult.id)) &&
163
+ results.every((result) => this._results.some((oldResult) => oldResult.id === result.id));
164
+
165
+ if (this._firstRun) {
166
+ this.metrics.executionTime = performance.now() - beginQuery;
167
+ }
168
+
169
+ this._firstRun = false;
170
+ if (areResultsUnchanged) {
171
+ return { changed: false };
172
+ }
173
+
174
+ this._results = results;
175
+ return { changed: true };
176
+ }
177
+ }
178
+
179
+ // TODO(burdon): Process Filter DSL.
180
+ const filterToIndexQuery = (filter: FilterProto): IndexQuery => {
181
+ invariant(!(filter.type && (filter.or ?? []).length > 0), 'Cannot mix type and or filters.');
182
+ invariant(
183
+ (filter.or ?? []).every((subFilter) => !(subFilter.type && (subFilter.or ?? []).length > 0)),
184
+ 'Cannot mix type and or filters.',
185
+ );
186
+ if (
187
+ filter.type ||
188
+ ((filter.or ?? []).length > 0 && (filter.or ?? []).every((subFilter) => !subFilter.not && subFilter.type))
189
+ ) {
190
+ return {
191
+ typenames: filter.type?.objectId
192
+ ? [filter.type.objectId]
193
+ : (filter.or ?? []).map((f) => f.type?.objectId).filter(nonNullable),
194
+ inverted: filter.not,
195
+ };
196
+ } else {
197
+ // Query all objects.
198
+ return { typenames: [] };
199
+ }
200
+ };
@@ -0,0 +1,90 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import isEqual from 'lodash.isequal';
6
+
7
+ import { Event, UpdateScheduler } from '@dxos/async';
8
+ import { interpretAsDocumentId, type DocHandle, type DocumentId } from '@dxos/automerge/automerge-repo';
9
+ import { Resource, Context } from '@dxos/context';
10
+ import type { SpaceDoc } from '@dxos/echo-protocol';
11
+ import type { SpaceId } from '@dxos/keys';
12
+
13
+ import { DatabaseRoot } from './database-root';
14
+
15
+ export class SpaceStateManager extends Resource {
16
+ private readonly _roots = new Map<DocumentId, DatabaseRoot>();
17
+ private readonly _rootBySpace = new Map<SpaceId, DocumentId>();
18
+ private readonly _perRootContext = new Map<DocumentId, Context>();
19
+ private readonly _lastSpaceDocumentList = new Map<SpaceId, DocumentId[]>();
20
+
21
+ public readonly spaceDocumentListUpdated = new Event<SpaceDocumentListUpdatedEvent>();
22
+
23
+ protected override async _close(ctx: Context): Promise<void> {
24
+ for (const [_, rootCtx] of this._perRootContext) {
25
+ await rootCtx.dispose();
26
+ }
27
+ this._roots.clear();
28
+ }
29
+
30
+ get roots(): ReadonlyMap<DocumentId, DatabaseRoot> {
31
+ return this._roots;
32
+ }
33
+
34
+ getRootByDocumentId(documentId: DocumentId): DatabaseRoot | undefined {
35
+ return this._roots.get(documentId);
36
+ }
37
+
38
+ async assignRootToSpace(spaceId: SpaceId, handle: DocHandle<SpaceDoc>): Promise<DatabaseRoot> {
39
+ let root: DatabaseRoot;
40
+ if (this._roots.has(handle.documentId)) {
41
+ root = this._roots.get(handle.documentId)!;
42
+ } else {
43
+ root = new DatabaseRoot(handle);
44
+ this._roots.set(handle.documentId, root);
45
+ }
46
+
47
+ if (this._rootBySpace.get(spaceId) === root.handle.documentId) {
48
+ return root;
49
+ }
50
+
51
+ const prevRootId = this._rootBySpace.get(spaceId);
52
+ if (prevRootId) {
53
+ void this._perRootContext.get(prevRootId)?.dispose();
54
+ this._perRootContext.delete(prevRootId);
55
+ }
56
+
57
+ this._rootBySpace.set(spaceId, root.handle.documentId);
58
+ const ctx = new Context();
59
+
60
+ this._perRootContext.set(root.handle.documentId, ctx);
61
+
62
+ await root.handle.whenReady();
63
+
64
+ const documentListCheckScheduler = new UpdateScheduler(
65
+ ctx,
66
+ async () => {
67
+ const documentIds = [root.documentId, ...root.getAllLinkedDocuments().map((url) => interpretAsDocumentId(url))];
68
+ if (!isEqual(documentIds, this._lastSpaceDocumentList.get(spaceId))) {
69
+ this._lastSpaceDocumentList.set(spaceId, documentIds);
70
+ this.spaceDocumentListUpdated.emit(new SpaceDocumentListUpdatedEvent(spaceId, documentIds));
71
+ }
72
+ },
73
+ { maxFrequency: 50 },
74
+ );
75
+ const triggerCheckOnChange = () => documentListCheckScheduler.trigger();
76
+ root.handle.addListener('change', triggerCheckOnChange);
77
+ ctx.onDispose(() => root.handle.removeListener('change', triggerCheckOnChange));
78
+
79
+ documentListCheckScheduler.trigger();
80
+
81
+ return root;
82
+ }
83
+ }
84
+
85
+ export class SpaceDocumentListUpdatedEvent {
86
+ constructor(
87
+ public readonly spaceId: SpaceId,
88
+ public readonly documentIds: DocumentId[],
89
+ ) {}
90
+ }
@@ -0,0 +1,286 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { Mutex, Trigger } from '@dxos/async';
6
+ import * as A from '@dxos/automerge/automerge';
7
+ import { type Message as AutomergeMessage, cbor } from '@dxos/automerge/automerge-repo';
8
+ import { Context, Resource } from '@dxos/context';
9
+ import { randomUUID } from '@dxos/crypto';
10
+ import type { CollectionId } from '@dxos/echo-protocol';
11
+ import { type EdgeConnection } from '@dxos/edge-client';
12
+ import { invariant } from '@dxos/invariant';
13
+ import type { SpaceId } from '@dxos/keys';
14
+ import { log } from '@dxos/log';
15
+ import { EdgeService, type PeerId } from '@dxos/protocols';
16
+ import { buf } from '@dxos/protocols/buf';
17
+ import {
18
+ type Message as RouterMessage,
19
+ MessageSchema as RouterMessageSchema,
20
+ } from '@dxos/protocols/buf/dxos/edge/messenger_pb';
21
+ import { bufferToArray } from '@dxos/util';
22
+
23
+ import {
24
+ getSpaceIdFromCollectionId,
25
+ type EchoReplicator,
26
+ type EchoReplicatorContext,
27
+ type ReplicatorConnection,
28
+ type ShouldAdvertiseParams,
29
+ type ShouldSyncCollectionParams,
30
+ } from '../automerge';
31
+
32
+ export type EchoEdgeReplicatorParams = {
33
+ edgeConnection: EdgeConnection;
34
+ disableSharePolicy?: boolean;
35
+ };
36
+
37
+ export class EchoEdgeReplicator implements EchoReplicator {
38
+ private readonly _edgeConnection: EdgeConnection;
39
+ private readonly _mutex = new Mutex();
40
+
41
+ private _ctx?: Context = undefined;
42
+ private _context: EchoReplicatorContext | null = null;
43
+ private _connectedSpaces = new Set<SpaceId>();
44
+ private _connections = new Map<SpaceId, EdgeReplicatorConnection>();
45
+ private _sharePolicyEnabled = true;
46
+
47
+ constructor({ edgeConnection, disableSharePolicy }: EchoEdgeReplicatorParams) {
48
+ this._edgeConnection = edgeConnection;
49
+ this._sharePolicyEnabled = !disableSharePolicy;
50
+ }
51
+
52
+ async connect(context: EchoReplicatorContext): Promise<void> {
53
+ log.info('connect', { peerId: context.peerId });
54
+ this._context = context;
55
+
56
+ this._ctx = Context.default();
57
+ this._edgeConnection.reconnect.on(this._ctx, async () => {
58
+ using _guard = await this._mutex.acquire();
59
+
60
+ const spaces = [...this._connectedSpaces];
61
+ for (const connection of this._connections.values()) {
62
+ await connection.close();
63
+ }
64
+ this._connections.clear();
65
+
66
+ if (this._context !== null) {
67
+ for (const spaceId of spaces) {
68
+ await this._openConnection(spaceId);
69
+ }
70
+ }
71
+ });
72
+
73
+ for (const spaceId of this._connectedSpaces) {
74
+ await this._openConnection(spaceId);
75
+ }
76
+ }
77
+
78
+ async disconnect(): Promise<void> {
79
+ using _guard = await this._mutex.acquire();
80
+
81
+ for (const connection of this._connections.values()) {
82
+ await connection.close();
83
+ }
84
+ this._connections.clear();
85
+ }
86
+
87
+ async connectToSpace(spaceId: SpaceId) {
88
+ using _guard = await this._mutex.acquire();
89
+
90
+ this._connectedSpaces.add(spaceId);
91
+
92
+ // Check if AM-repo requested that we connect to remote peers.
93
+ if (this._context !== null) {
94
+ await this._openConnection(spaceId);
95
+ }
96
+ }
97
+
98
+ async disconnectFromSpace(spaceId: SpaceId) {
99
+ using _guard = await this._mutex.acquire();
100
+
101
+ this._connectedSpaces.delete(spaceId);
102
+
103
+ const connection = this._connections.get(spaceId);
104
+ if (connection) {
105
+ await connection.close();
106
+ this._connections.delete(spaceId);
107
+ }
108
+ }
109
+
110
+ private async _openConnection(spaceId: SpaceId) {
111
+ invariant(this._context);
112
+ const connection = new EdgeReplicatorConnection({
113
+ edgeConnection: this._edgeConnection,
114
+ ownPeerId: this._context.peerId,
115
+ spaceId,
116
+ context: this._context,
117
+ sharedPolicyEnabled: this._sharePolicyEnabled,
118
+ onRemoteConnected: async () => {
119
+ this._context?.onConnectionOpen(connection);
120
+ },
121
+ onRemoteDisconnected: async () => {
122
+ this._context?.onConnectionClosed(connection);
123
+ },
124
+ });
125
+ this._connections.set(spaceId, connection);
126
+
127
+ await connection.open();
128
+ }
129
+ }
130
+
131
+ type EdgeReplicatorConnectionsParams = {
132
+ edgeConnection: EdgeConnection;
133
+ ownPeerId: string;
134
+ spaceId: SpaceId;
135
+ context: EchoReplicatorContext;
136
+ sharedPolicyEnabled: boolean;
137
+ onRemoteConnected: () => Promise<void>;
138
+ onRemoteDisconnected: () => Promise<void>;
139
+ };
140
+
141
+ class EdgeReplicatorConnection extends Resource implements ReplicatorConnection {
142
+ private readonly _edgeConnection: EdgeConnection;
143
+ private _remotePeerId: string | null = null;
144
+ private readonly _ownPeerId: string;
145
+ private readonly _targetServiceId: string;
146
+ private readonly _spaceId: SpaceId;
147
+ private readonly _context: EchoReplicatorContext;
148
+ private readonly _sharedPolicyEnabled: boolean;
149
+ private readonly _onRemoteConnected: () => Promise<void>;
150
+ private readonly _onRemoteDisconnected: () => Promise<void>;
151
+
152
+ private _streamStarted = new Trigger();
153
+ private _readableStreamController!: ReadableStreamDefaultController<AutomergeMessage>;
154
+
155
+ public readable: ReadableStream<AutomergeMessage>;
156
+ public writable: WritableStream<AutomergeMessage>;
157
+
158
+ constructor({
159
+ edgeConnection,
160
+ ownPeerId,
161
+ spaceId,
162
+ context,
163
+ sharedPolicyEnabled,
164
+ onRemoteConnected,
165
+ onRemoteDisconnected,
166
+ }: EdgeReplicatorConnectionsParams) {
167
+ super();
168
+ this._edgeConnection = edgeConnection;
169
+ this._ownPeerId = ownPeerId;
170
+ this._spaceId = spaceId;
171
+ this._context = context;
172
+
173
+ // Generate a unique peer id for every connection.
174
+ // This way automerge-repo will have separate sync states for every connection.
175
+ // This is important because the previous connection might have had some messages that failed to deliver
176
+ // abd if we don't clear the sync-state, automerge will not attempt to deliver them again.
177
+ this._remotePeerId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}-${randomUUID()}`;
178
+ this._targetServiceId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}`;
179
+ this._sharedPolicyEnabled = sharedPolicyEnabled;
180
+ this._onRemoteConnected = onRemoteConnected;
181
+ this._onRemoteDisconnected = onRemoteDisconnected;
182
+
183
+ this.readable = new ReadableStream<AutomergeMessage>({
184
+ start: (controller) => {
185
+ this._readableStreamController = controller;
186
+ this._ctx.onDispose(() => controller.close());
187
+ this._streamStarted.wake();
188
+ },
189
+ });
190
+
191
+ this.writable = new WritableStream<AutomergeMessage>({
192
+ write: async (message: AutomergeMessage, controller) => {
193
+ await this._sendMessage(message);
194
+ },
195
+ });
196
+ }
197
+
198
+ protected override async _open(ctx: Context): Promise<void> {
199
+ // TODO: handle reconnects
200
+ this._ctx.onDispose(
201
+ this._edgeConnection.addListener((msg: RouterMessage) => {
202
+ this._onMessage(msg);
203
+ }),
204
+ );
205
+
206
+ await this._onRemoteConnected();
207
+ }
208
+
209
+ protected override async _close(): Promise<void> {
210
+ await this._onRemoteDisconnected();
211
+ }
212
+
213
+ get peerId(): string {
214
+ invariant(this._remotePeerId, 'Not connected');
215
+ return this._remotePeerId;
216
+ }
217
+
218
+ async shouldAdvertise(params: ShouldAdvertiseParams): Promise<boolean> {
219
+ if (!this._sharedPolicyEnabled) {
220
+ return true;
221
+ }
222
+ const spaceId = await this._context.getContainingSpaceIdForDocument(params.documentId);
223
+ if (!spaceId) {
224
+ // There's no spaceId if the document is not present locally. This means the sharePolicy check is being
225
+ // performed on message reception, so spaceId check was already performed in _onMessage.
226
+ return true;
227
+ }
228
+ return spaceId === this._spaceId;
229
+ }
230
+
231
+ shouldSyncCollection(params: ShouldSyncCollectionParams): boolean {
232
+ if (!this._sharedPolicyEnabled) {
233
+ return true;
234
+ }
235
+ const spaceId = getSpaceIdFromCollectionId(params.collectionId as CollectionId);
236
+ return spaceId === this._spaceId;
237
+ }
238
+
239
+ private _onMessage(message: RouterMessage) {
240
+ if (message.serviceId !== this._targetServiceId) {
241
+ return;
242
+ }
243
+
244
+ const payload = cbor.decode(message.payload!.value) as AutomergeMessage;
245
+ log('recv', () => {
246
+ const decodedData =
247
+ payload.type === 'sync' && payload.data
248
+ ? A.decodeSyncMessage(payload.data)
249
+ : payload.type === 'collection-state'
250
+ ? (payload as any).state
251
+ : payload;
252
+ return { from: message.serviceId, type: payload.type, decodedData };
253
+ });
254
+ // Fix the peer id.
255
+ payload.senderId = this._remotePeerId! as PeerId;
256
+ this._processMessage(payload);
257
+ }
258
+
259
+ private _processMessage(message: AutomergeMessage) {
260
+ this._readableStreamController.enqueue(message);
261
+ }
262
+
263
+ private async _sendMessage(message: AutomergeMessage) {
264
+ // Fix the peer id.
265
+ message.targetId = this._targetServiceId as PeerId;
266
+
267
+ log('send', {
268
+ type: message.type,
269
+ senderId: message.senderId,
270
+ targetId: message.targetId,
271
+ documentId: message.documentId,
272
+ });
273
+ const encoded = cbor.encode(message);
274
+
275
+ await this._edgeConnection.send(
276
+ buf.create(RouterMessageSchema, {
277
+ serviceId: this._targetServiceId,
278
+ source: {
279
+ identityKey: this._edgeConnection.identityKey,
280
+ peerKey: this._edgeConnection.peerKey,
281
+ },
282
+ payload: { value: bufferToArray(encoded) },
283
+ }),
284
+ );
285
+ }
286
+ }
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export * from './echo-edge-replicator';
package/src/index.ts CHANGED
@@ -8,3 +8,4 @@ export * from './metadata';
8
8
  export * from './pipeline';
9
9
  export * from './space';
10
10
  export * from './automerge';
11
+ export * from './edge';