@dxos/echo-pipeline 0.6.12-main.5cc132e → 0.6.12-main.78ddbdf

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 (100) hide show
  1. package/dist/lib/{node-esm/chunk-ZWS5AMHO.mjs → browser/chunk-YTSGJIY7.mjs} +59 -23
  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/node-esm/index.mjs +3401 -17
  18. package/dist/lib/node-esm/index.mjs.map +4 -4
  19. package/dist/lib/node-esm/meta.json +1 -1
  20. package/dist/lib/node-esm/testing/index.mjs +4 -4
  21. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  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 +36 -43
  57. package/src/automerge/automerge-host.ts +42 -6
  58. package/src/automerge/collection-synchronizer.test.ts +3 -1
  59. package/src/automerge/collection-synchronizer.ts +17 -6
  60. package/src/automerge/mesh-echo-replicator.ts +2 -1
  61. package/src/automerge/space-collection.ts +3 -2
  62. package/src/db-host/automerge-metrics.ts +38 -0
  63. package/src/db-host/data-service.ts +29 -14
  64. package/src/db-host/database-root.ts +86 -0
  65. package/src/db-host/documents-iterator.ts +73 -0
  66. package/src/db-host/echo-host.ts +257 -0
  67. package/src/db-host/index.ts +6 -1
  68. package/src/db-host/migration.ts +57 -0
  69. package/src/db-host/query-service.ts +208 -0
  70. package/src/db-host/query-state.ts +200 -0
  71. package/src/db-host/space-state-manager.ts +90 -0
  72. package/src/edge/echo-edge-replicator.ts +286 -0
  73. package/src/edge/index.ts +5 -0
  74. package/src/index.ts +1 -0
  75. package/src/space/control-pipeline.ts +10 -1
  76. package/src/testing/test-agent-builder.ts +2 -2
  77. package/dist/lib/browser/chunk-MPWFDDQK.mjs +0 -2152
  78. package/dist/lib/browser/chunk-MPWFDDQK.mjs.map +0 -7
  79. package/dist/lib/browser/chunk-UKXIJW43.mjs.map +0 -7
  80. package/dist/lib/browser/chunk-XPCF2V5U.mjs +0 -31
  81. package/dist/lib/browser/chunk-XPCF2V5U.mjs.map +0 -7
  82. package/dist/lib/browser/light.mjs +0 -32
  83. package/dist/lib/browser/light.mjs.map +0 -7
  84. package/dist/lib/node/chunk-5DH4KR2S.cjs +0 -2148
  85. package/dist/lib/node/chunk-5DH4KR2S.cjs.map +0 -7
  86. package/dist/lib/node/chunk-7HHYCGUR.cjs.map +0 -7
  87. package/dist/lib/node/chunk-DZVH7HDD.cjs +0 -43
  88. package/dist/lib/node/chunk-DZVH7HDD.cjs.map +0 -7
  89. package/dist/lib/node/light.cjs +0 -52
  90. package/dist/lib/node/light.cjs.map +0 -7
  91. package/dist/lib/node-esm/chunk-BZ3FKMCP.mjs +0 -21
  92. package/dist/lib/node-esm/chunk-BZ3FKMCP.mjs.map +0 -7
  93. package/dist/lib/node-esm/chunk-HH4RB7HI.mjs +0 -2150
  94. package/dist/lib/node-esm/chunk-HH4RB7HI.mjs.map +0 -7
  95. package/dist/lib/node-esm/chunk-ZWS5AMHO.mjs.map +0 -7
  96. package/dist/lib/node-esm/light.mjs +0 -31
  97. package/dist/lib/node-esm/light.mjs.map +0 -7
  98. package/dist/types/src/light.d.ts +0 -4
  99. package/dist/types/src/light.d.ts.map +0 -1
  100. package/src/light.ts +0 -7
@@ -1,16 +1,4 @@
1
- import {
2
- AutomergeHost,
3
- DataServiceImpl,
4
- DocumentsSynchronizer,
5
- EchoDataMonitor,
6
- LevelDBStorageAdapter,
7
- MeshEchoReplicator,
8
- deriveCollectionIdFromSpaceId,
9
- diffCollectionState,
10
- encodingOptions,
11
- getSpaceIdFromCollectionId,
12
- getSpaceKeyFromDoc
13
- } from "./chunk-HH4RB7HI.mjs";
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
14
2
  import {
15
3
  AuthExtension,
16
4
  AuthStatus,
@@ -26,16 +14,3404 @@ import {
26
14
  SpaceProtocolSession,
27
15
  TimeframeClock,
28
16
  codec,
17
+ createIdFromSpaceKey,
29
18
  createMappedFeedWriter,
30
19
  hasInvitationExpired,
31
20
  mapFeedIndexesToTimeframe,
32
21
  mapTimeframeToFeedIndexes,
33
22
  startAfter,
34
23
  valueEncoding
35
- } from "./chunk-ZWS5AMHO.mjs";
36
- import {
37
- createIdFromSpaceKey
38
- } from "./chunk-BZ3FKMCP.mjs";
24
+ } from "./chunk-ASOERPR6.mjs";
25
+
26
+ // packages/core/echo/echo-pipeline/src/db-host/data-service.ts
27
+ import { UpdateScheduler as UpdateScheduler2 } from "@dxos/async";
28
+ import { Stream } from "@dxos/codec-protobuf/stream";
29
+ import { invariant as invariant7 } from "@dxos/invariant";
30
+ import { SpaceId as SpaceId2 } from "@dxos/keys";
31
+ import { log as log7 } from "@dxos/log";
32
+
33
+ // packages/core/echo/echo-pipeline/src/db-host/documents-synchronizer.ts
34
+ import { UpdateScheduler } from "@dxos/async";
35
+ import { next as A } from "@dxos/automerge/automerge";
36
+ import { Resource } from "@dxos/context";
37
+ import { invariant } from "@dxos/invariant";
38
+ import { log } from "@dxos/log";
39
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/documents-synchronizer.ts";
40
+ var MAX_UPDATE_FREQ = 10;
41
+ var DocumentsSynchronizer = class extends Resource {
42
+ constructor(_params) {
43
+ super();
44
+ this._params = _params;
45
+ this._syncStates = /* @__PURE__ */ new Map();
46
+ this._pendingUpdates = /* @__PURE__ */ new Set();
47
+ this._sendUpdatesJob = void 0;
48
+ }
49
+ addDocuments(documentIds, retryCounter = 0) {
50
+ if (retryCounter > 3) {
51
+ log.warn("Failed to load document, retry limit reached", {
52
+ documentIds
53
+ }, {
54
+ F: __dxlog_file,
55
+ L: 49,
56
+ S: this,
57
+ C: (f, a) => f(...a)
58
+ });
59
+ return;
60
+ }
61
+ for (const documentId of documentIds) {
62
+ const doc = this._params.repo.find(documentId);
63
+ doc.whenReady().then(() => {
64
+ this._startSync(doc);
65
+ this._pendingUpdates.add(doc.documentId);
66
+ this._sendUpdatesJob.trigger();
67
+ }).catch((error) => {
68
+ log.warn("Failed to load document, wraparound", {
69
+ documentId,
70
+ error
71
+ }, {
72
+ F: __dxlog_file,
73
+ L: 63,
74
+ S: this,
75
+ C: (f, a) => f(...a)
76
+ });
77
+ this.addDocuments([
78
+ documentId
79
+ ], retryCounter + 1);
80
+ });
81
+ }
82
+ }
83
+ removeDocuments(documentIds) {
84
+ for (const documentId of documentIds) {
85
+ this._syncStates.get(documentId)?.clearSubscriptions?.();
86
+ this._syncStates.delete(documentId);
87
+ this._pendingUpdates.delete(documentId);
88
+ }
89
+ }
90
+ async _open() {
91
+ this._sendUpdatesJob = new UpdateScheduler(this._ctx, this._checkAndSendUpdates.bind(this), {
92
+ maxFrequency: MAX_UPDATE_FREQ
93
+ });
94
+ }
95
+ async _close() {
96
+ await this._sendUpdatesJob.join();
97
+ this._syncStates.clear();
98
+ }
99
+ update(updates) {
100
+ for (const { documentId, mutation, isNew } of updates) {
101
+ if (isNew) {
102
+ const doc = this._params.repo.find(documentId);
103
+ doc.update((doc2) => A.loadIncremental(doc2, mutation));
104
+ this._startSync(doc);
105
+ } else {
106
+ this._writeMutation(documentId, mutation);
107
+ }
108
+ }
109
+ }
110
+ _startSync(doc) {
111
+ if (this._syncStates.has(doc.documentId)) {
112
+ log.info("Document already being synced", {
113
+ documentId: doc.documentId
114
+ }, {
115
+ F: __dxlog_file,
116
+ L: 102,
117
+ S: this,
118
+ C: (f, a) => f(...a)
119
+ });
120
+ return;
121
+ }
122
+ const syncState = {
123
+ handle: doc
124
+ };
125
+ this._subscribeForChanges(syncState);
126
+ this._syncStates.set(doc.documentId, syncState);
127
+ }
128
+ _subscribeForChanges(syncState) {
129
+ const handler = () => {
130
+ this._pendingUpdates.add(syncState.handle.documentId);
131
+ this._sendUpdatesJob.trigger();
132
+ };
133
+ syncState.handle.on("heads-changed", handler);
134
+ syncState.clearSubscriptions = () => syncState.handle.off("heads-changed", handler);
135
+ }
136
+ async _checkAndSendUpdates() {
137
+ const updates = [];
138
+ const docsWithPendingUpdates = Array.from(this._pendingUpdates);
139
+ this._pendingUpdates.clear();
140
+ for (const documentId of docsWithPendingUpdates) {
141
+ const update = this._getPendingChanges(documentId);
142
+ if (update) {
143
+ updates.push({
144
+ documentId,
145
+ mutation: update
146
+ });
147
+ }
148
+ }
149
+ if (updates.length > 0) {
150
+ this._params.sendUpdates({
151
+ updates
152
+ });
153
+ }
154
+ }
155
+ _getPendingChanges(documentId) {
156
+ const syncState = this._syncStates.get(documentId);
157
+ invariant(syncState, "Sync state for document not found", {
158
+ F: __dxlog_file,
159
+ L: 143,
160
+ S: this,
161
+ A: [
162
+ "syncState",
163
+ "'Sync state for document not found'"
164
+ ]
165
+ });
166
+ const doc = syncState.handle.docSync();
167
+ if (!doc) {
168
+ return;
169
+ }
170
+ const mutation = syncState.lastSentHead ? A.saveSince(doc, syncState.lastSentHead) : A.save(doc);
171
+ if (mutation.length === 0) {
172
+ return;
173
+ }
174
+ syncState.lastSentHead = A.getHeads(doc);
175
+ return mutation;
176
+ }
177
+ _writeMutation(documentId, mutation) {
178
+ const syncState = this._syncStates.get(documentId);
179
+ invariant(syncState, "Sync state for document not found", {
180
+ F: __dxlog_file,
181
+ L: 158,
182
+ S: this,
183
+ A: [
184
+ "syncState",
185
+ "'Sync state for document not found'"
186
+ ]
187
+ });
188
+ syncState.handle.update((doc) => {
189
+ const headsBefore = A.getHeads(doc);
190
+ const newDoc = A.loadIncremental(doc, mutation);
191
+ if (A.equals(headsBefore, syncState.lastSentHead)) {
192
+ syncState.lastSentHead = A.getHeads(newDoc);
193
+ }
194
+ return newDoc;
195
+ });
196
+ }
197
+ };
198
+
199
+ // packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts
200
+ import { Event as Event2, asyncTimeout } from "@dxos/async";
201
+ import { getBackend, getHeads, isAutomerge, equals as headsEquals, save } from "@dxos/automerge/automerge";
202
+ import { Repo } from "@dxos/automerge/automerge-repo";
203
+ import { Context, Resource as Resource4, cancelWithContext } from "@dxos/context";
204
+ import { invariant as invariant3 } from "@dxos/invariant";
205
+ import { PublicKey } from "@dxos/keys";
206
+ import { log as log4 } from "@dxos/log";
207
+ import { objectPointerCodec } from "@dxos/protocols";
208
+ import { trace } from "@dxos/tracing";
209
+
210
+ // packages/core/echo/echo-pipeline/src/automerge/collection-synchronizer.ts
211
+ import { asyncReturn, Event, scheduleTask, scheduleTaskInterval } from "@dxos/async";
212
+ import { next as am } from "@dxos/automerge/automerge";
213
+ import { Resource as Resource2 } from "@dxos/context";
214
+ import { log as log2 } from "@dxos/log";
215
+ import { defaultMap } from "@dxos/util";
216
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/collection-synchronizer.ts";
217
+ var MIN_QUERY_INTERVAL = 5e3;
218
+ var POLL_INTERVAL = 3e4;
219
+ var CollectionSynchronizer = class extends Resource2 {
220
+ constructor(params) {
221
+ super();
222
+ /**
223
+ * CollectionId -> State.
224
+ */
225
+ this._perCollectionStates = /* @__PURE__ */ new Map();
226
+ this._connectedPeers = /* @__PURE__ */ new Set();
227
+ this.remoteStateUpdated = new Event();
228
+ this._sendCollectionState = params.sendCollectionState;
229
+ this._queryCollectionState = params.queryCollectionState;
230
+ this._shouldSyncCollection = params.shouldSyncCollection;
231
+ }
232
+ async _open(ctx) {
233
+ scheduleTaskInterval(this._ctx, async () => {
234
+ for (const collectionId of this._perCollectionStates.keys()) {
235
+ this.refreshCollection(collectionId);
236
+ await asyncReturn();
237
+ }
238
+ }, POLL_INTERVAL);
239
+ }
240
+ getRegisteredCollectionIds() {
241
+ return [
242
+ ...this._perCollectionStates.keys()
243
+ ];
244
+ }
245
+ getLocalCollectionState(collectionId) {
246
+ return this._getPerCollectionState(collectionId).localState;
247
+ }
248
+ setLocalCollectionState(collectionId, state) {
249
+ log2("setLocalCollectionState", {
250
+ collectionId,
251
+ state
252
+ }, {
253
+ F: __dxlog_file2,
254
+ L: 68,
255
+ S: this,
256
+ C: (f, a) => f(...a)
257
+ });
258
+ this._getPerCollectionState(collectionId).localState = state;
259
+ queueMicrotask(async () => {
260
+ if (!this._ctx.disposed) {
261
+ this._refreshInterestedPeers(collectionId);
262
+ this.refreshCollection(collectionId);
263
+ }
264
+ });
265
+ }
266
+ getRemoteCollectionStates(collectionId) {
267
+ return this._getPerCollectionState(collectionId).remoteStates;
268
+ }
269
+ refreshCollection(collectionId) {
270
+ let scheduleAnotherRefresh = false;
271
+ const state = this._getPerCollectionState(collectionId);
272
+ for (const peerId of this._connectedPeers) {
273
+ if (state.interestedPeers.has(peerId)) {
274
+ const lastQueried = state.lastQueried.get(peerId) ?? 0;
275
+ if (Date.now() - lastQueried > MIN_QUERY_INTERVAL) {
276
+ state.lastQueried.set(peerId, Date.now());
277
+ this._queryCollectionState(collectionId, peerId);
278
+ } else {
279
+ scheduleAnotherRefresh = true;
280
+ }
281
+ }
282
+ }
283
+ if (scheduleAnotherRefresh) {
284
+ scheduleTask(this._ctx, () => this.refreshCollection(collectionId), MIN_QUERY_INTERVAL);
285
+ }
286
+ }
287
+ /**
288
+ * Callback when a connection to a peer is established.
289
+ */
290
+ onConnectionOpen(peerId) {
291
+ this._connectedPeers.add(peerId);
292
+ queueMicrotask(async () => {
293
+ if (this._ctx.disposed) {
294
+ return;
295
+ }
296
+ for (const [collectionId, state] of this._perCollectionStates.entries()) {
297
+ if (this._shouldSyncCollection(collectionId, peerId)) {
298
+ state.interestedPeers.add(peerId);
299
+ state.lastQueried.set(peerId, Date.now());
300
+ this._queryCollectionState(collectionId, peerId);
301
+ }
302
+ }
303
+ });
304
+ }
305
+ /**
306
+ * Callback when a connection to a peer is closed.
307
+ */
308
+ onConnectionClosed(peerId) {
309
+ this._connectedPeers.delete(peerId);
310
+ for (const perCollectionState of this._perCollectionStates.values()) {
311
+ perCollectionState.remoteStates.delete(peerId);
312
+ }
313
+ }
314
+ /**
315
+ * Callback when a peer queries the state of a collection.
316
+ */
317
+ onCollectionStateQueried(collectionId, peerId) {
318
+ const perCollectionState = this._getPerCollectionState(collectionId);
319
+ if (perCollectionState.localState) {
320
+ this._sendCollectionState(collectionId, peerId, perCollectionState.localState);
321
+ }
322
+ }
323
+ /**
324
+ * Callback when a peer sends the state of a collection.
325
+ */
326
+ onRemoteStateReceived(collectionId, peerId, state) {
327
+ log2("onRemoteStateReceived", {
328
+ collectionId,
329
+ peerId,
330
+ state
331
+ }, {
332
+ F: __dxlog_file2,
333
+ L: 148,
334
+ S: this,
335
+ C: (f, a) => f(...a)
336
+ });
337
+ validateCollectionState(state);
338
+ const perCollectionState = this._getPerCollectionState(collectionId);
339
+ perCollectionState.remoteStates.set(peerId, state);
340
+ this.remoteStateUpdated.emit({
341
+ peerId,
342
+ collectionId
343
+ });
344
+ }
345
+ _getPerCollectionState(collectionId) {
346
+ return defaultMap(this._perCollectionStates, collectionId, () => ({
347
+ localState: void 0,
348
+ remoteStates: /* @__PURE__ */ new Map(),
349
+ interestedPeers: /* @__PURE__ */ new Set(),
350
+ lastQueried: /* @__PURE__ */ new Map()
351
+ }));
352
+ }
353
+ _refreshInterestedPeers(collectionId) {
354
+ for (const peerId of this._connectedPeers) {
355
+ if (this._shouldSyncCollection(collectionId, peerId)) {
356
+ this._getPerCollectionState(collectionId).interestedPeers.add(peerId);
357
+ } else {
358
+ this._getPerCollectionState(collectionId).interestedPeers.delete(peerId);
359
+ }
360
+ }
361
+ }
362
+ };
363
+ var diffCollectionState = (local, remote) => {
364
+ const allDocuments = /* @__PURE__ */ new Set([
365
+ ...Object.keys(local.documents),
366
+ ...Object.keys(remote.documents)
367
+ ]);
368
+ const missingOnRemote = [];
369
+ const missingOnLocal = [];
370
+ const different = [];
371
+ for (const documentId of allDocuments) {
372
+ if (!local.documents[documentId]) {
373
+ missingOnLocal.push(documentId);
374
+ } else if (!remote.documents[documentId]) {
375
+ missingOnRemote.push(documentId);
376
+ } else if (!am.equals(local.documents[documentId], remote.documents[documentId])) {
377
+ different.push(documentId);
378
+ }
379
+ }
380
+ return {
381
+ missingOnRemote,
382
+ missingOnLocal,
383
+ different
384
+ };
385
+ };
386
+ var validateCollectionState = (state) => {
387
+ Object.entries(state.documents).forEach(([documentId, heads]) => {
388
+ if (!isValidDocumentId(documentId)) {
389
+ throw new Error(`Invalid documentId: ${documentId}`);
390
+ }
391
+ if (Array.isArray(heads) && heads.some((head) => typeof head !== "string")) {
392
+ throw new Error(`Invalid heads: ${heads}`);
393
+ }
394
+ });
395
+ };
396
+ var isValidDocumentId = (documentId) => {
397
+ return typeof documentId === "string" && !documentId.includes(":");
398
+ };
399
+
400
+ // packages/core/echo/echo-pipeline/src/automerge/echo-network-adapter.ts
401
+ import { synchronized, Trigger } from "@dxos/async";
402
+ import { NetworkAdapter } from "@dxos/automerge/automerge-repo";
403
+ import { LifecycleState } from "@dxos/context";
404
+ import { invariant as invariant2 } from "@dxos/invariant";
405
+ import { log as log3 } from "@dxos/log";
406
+ import { nonNullable } from "@dxos/util";
407
+
408
+ // packages/core/echo/echo-pipeline/src/automerge/network-protocol.ts
409
+ import { MESSAGE_TYPE_COLLECTION_QUERY, MESSAGE_TYPE_COLLECTION_STATE } from "@dxos/protocols";
410
+ var isCollectionQueryMessage = (message) => message.type === MESSAGE_TYPE_COLLECTION_QUERY;
411
+ var isCollectionStateMessage = (message) => message.type === MESSAGE_TYPE_COLLECTION_STATE;
412
+
413
+ // packages/core/echo/echo-pipeline/src/automerge/echo-network-adapter.ts
414
+ function _ts_decorate(decorators, target, key, desc) {
415
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
416
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
417
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
418
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
419
+ }
420
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/echo-network-adapter.ts";
421
+ var EchoNetworkAdapter = class extends NetworkAdapter {
422
+ constructor(_params) {
423
+ super();
424
+ this._params = _params;
425
+ this._replicators = /* @__PURE__ */ new Set();
426
+ this._connections = /* @__PURE__ */ new Map();
427
+ this._lifecycleState = LifecycleState.CLOSED;
428
+ this._connected = new Trigger();
429
+ }
430
+ connect(peerId, peerMetadata) {
431
+ this.peerId = peerId;
432
+ this.peerMetadata = peerMetadata;
433
+ this._connected.wake();
434
+ }
435
+ send(message) {
436
+ this._send(message);
437
+ }
438
+ disconnect() {
439
+ }
440
+ async open() {
441
+ if (this._lifecycleState === LifecycleState.OPEN) {
442
+ return;
443
+ }
444
+ this._lifecycleState = LifecycleState.OPEN;
445
+ log3("emit ready", void 0, {
446
+ F: __dxlog_file3,
447
+ L: 81,
448
+ S: this,
449
+ C: (f, a) => f(...a)
450
+ });
451
+ this.emit("ready", {
452
+ network: this
453
+ });
454
+ }
455
+ async close() {
456
+ if (this._lifecycleState === LifecycleState.CLOSED) {
457
+ return this;
458
+ }
459
+ for (const replicator of this._replicators) {
460
+ await replicator.disconnect();
461
+ }
462
+ this._replicators.clear();
463
+ this._lifecycleState = LifecycleState.CLOSED;
464
+ }
465
+ async whenConnected() {
466
+ await this._connected.wait({
467
+ timeout: 1e4
468
+ });
469
+ }
470
+ async addReplicator(replicator) {
471
+ invariant2(this._lifecycleState === LifecycleState.OPEN, void 0, {
472
+ F: __dxlog_file3,
473
+ L: 107,
474
+ S: this,
475
+ A: [
476
+ "this._lifecycleState === LifecycleState.OPEN",
477
+ ""
478
+ ]
479
+ });
480
+ invariant2(this.peerId, void 0, {
481
+ F: __dxlog_file3,
482
+ L: 108,
483
+ S: this,
484
+ A: [
485
+ "this.peerId",
486
+ ""
487
+ ]
488
+ });
489
+ invariant2(!this._replicators.has(replicator), void 0, {
490
+ F: __dxlog_file3,
491
+ L: 109,
492
+ S: this,
493
+ A: [
494
+ "!this._replicators.has(replicator)",
495
+ ""
496
+ ]
497
+ });
498
+ this._replicators.add(replicator);
499
+ await replicator.connect({
500
+ peerId: this.peerId,
501
+ onConnectionOpen: this._onConnectionOpen.bind(this),
502
+ onConnectionClosed: this._onConnectionClosed.bind(this),
503
+ onConnectionAuthScopeChanged: this._onConnectionAuthScopeChanged.bind(this),
504
+ isDocumentInRemoteCollection: this._params.isDocumentInRemoteCollection,
505
+ getContainingSpaceForDocument: this._params.getContainingSpaceForDocument,
506
+ getContainingSpaceIdForDocument: async (documentId) => {
507
+ const key = await this._params.getContainingSpaceForDocument(documentId);
508
+ return key ? createIdFromSpaceKey(key) : null;
509
+ }
510
+ });
511
+ }
512
+ async removeReplicator(replicator) {
513
+ invariant2(this._lifecycleState === LifecycleState.OPEN, void 0, {
514
+ F: __dxlog_file3,
515
+ L: 128,
516
+ S: this,
517
+ A: [
518
+ "this._lifecycleState === LifecycleState.OPEN",
519
+ ""
520
+ ]
521
+ });
522
+ invariant2(this._replicators.has(replicator), void 0, {
523
+ F: __dxlog_file3,
524
+ L: 129,
525
+ S: this,
526
+ A: [
527
+ "this._replicators.has(replicator)",
528
+ ""
529
+ ]
530
+ });
531
+ await replicator.disconnect();
532
+ this._replicators.delete(replicator);
533
+ }
534
+ async shouldAdvertise(peerId, params) {
535
+ const connection = this._connections.get(peerId);
536
+ if (!connection) {
537
+ return false;
538
+ }
539
+ return connection.connection.shouldAdvertise(params);
540
+ }
541
+ shouldSyncCollection(peerId, params) {
542
+ const connection = this._connections.get(peerId);
543
+ if (!connection) {
544
+ return false;
545
+ }
546
+ return connection.connection.shouldSyncCollection(params);
547
+ }
548
+ queryCollectionState(collectionId, targetId) {
549
+ const message = {
550
+ type: "collection-query",
551
+ senderId: this.peerId,
552
+ targetId,
553
+ collectionId
554
+ };
555
+ this._send(message);
556
+ }
557
+ sendCollectionState(collectionId, targetId, state) {
558
+ const message = {
559
+ type: "collection-state",
560
+ senderId: this.peerId,
561
+ targetId,
562
+ collectionId,
563
+ state
564
+ };
565
+ this._send(message);
566
+ }
567
+ _send(message) {
568
+ const connectionEntry = this._connections.get(message.targetId);
569
+ if (!connectionEntry) {
570
+ throw new Error("Connection not found.");
571
+ }
572
+ const writeStart = Date.now();
573
+ connectionEntry.writer.write(message).then(() => {
574
+ const durationMs = Date.now() - writeStart;
575
+ this._params.monitor?.recordMessageSent(message, durationMs);
576
+ }).catch((err) => {
577
+ if (connectionEntry.isOpen) {
578
+ log3.catch(err, void 0, {
579
+ F: __dxlog_file3,
580
+ L: 189,
581
+ S: this,
582
+ C: (f, a) => f(...a)
583
+ });
584
+ }
585
+ this._params.monitor?.recordMessageSendingFailed(message);
586
+ });
587
+ }
588
+ // TODO(dmaretskyi): Remove.
589
+ getPeersInterestedInCollection(collectionId) {
590
+ return Array.from(this._connections.values()).map((connection) => {
591
+ return connection.connection.shouldSyncCollection({
592
+ collectionId
593
+ }) ? connection.connection.peerId : null;
594
+ }).filter(nonNullable);
595
+ }
596
+ _onConnectionOpen(connection) {
597
+ log3("Connection opened", {
598
+ peerId: connection.peerId
599
+ }, {
600
+ F: __dxlog_file3,
601
+ L: 207,
602
+ S: this,
603
+ C: (f, a) => f(...a)
604
+ });
605
+ invariant2(!this._connections.has(connection.peerId), void 0, {
606
+ F: __dxlog_file3,
607
+ L: 208,
608
+ S: this,
609
+ A: [
610
+ "!this._connections.has(connection.peerId as PeerId)",
611
+ ""
612
+ ]
613
+ });
614
+ const reader = connection.readable.getReader();
615
+ const writer = connection.writable.getWriter();
616
+ const connectionEntry = {
617
+ connection,
618
+ reader,
619
+ writer,
620
+ isOpen: true
621
+ };
622
+ this._connections.set(connection.peerId, connectionEntry);
623
+ queueMicrotask(async () => {
624
+ try {
625
+ while (true) {
626
+ const { done, value } = await reader.read();
627
+ if (done) {
628
+ break;
629
+ }
630
+ this._onMessage(value);
631
+ }
632
+ } catch (err) {
633
+ if (connectionEntry.isOpen) {
634
+ log3.catch(err, void 0, {
635
+ F: __dxlog_file3,
636
+ L: 227,
637
+ S: this,
638
+ C: (f, a) => f(...a)
639
+ });
640
+ }
641
+ }
642
+ });
643
+ log3("emit peer-candidate", {
644
+ peerId: connection.peerId
645
+ }, {
646
+ F: __dxlog_file3,
647
+ L: 232,
648
+ S: this,
649
+ C: (f, a) => f(...a)
650
+ });
651
+ this._emitPeerCandidate(connection);
652
+ this._params.monitor?.recordPeerConnected(connection.peerId);
653
+ }
654
+ _onMessage(message) {
655
+ if (isCollectionQueryMessage(message)) {
656
+ this._params.onCollectionStateQueried(message.collectionId, message.senderId);
657
+ } else if (isCollectionStateMessage(message)) {
658
+ this._params.onCollectionStateReceived(message.collectionId, message.senderId, message.state);
659
+ } else {
660
+ this.emit("message", message);
661
+ }
662
+ this._params.monitor?.recordMessageReceived(message);
663
+ }
664
+ /**
665
+ * Trigger doc-synchronizer shared documents set recalculation. Happens on peer-candidate.
666
+ * TODO(y): replace with a proper API call when sharePolicy update becomes supported by automerge-repo
667
+ */
668
+ _onConnectionAuthScopeChanged(connection) {
669
+ log3("Connection auth scope changed", {
670
+ peerId: connection.peerId
671
+ }, {
672
+ F: __dxlog_file3,
673
+ L: 253,
674
+ S: this,
675
+ C: (f, a) => f(...a)
676
+ });
677
+ const entry = this._connections.get(connection.peerId);
678
+ invariant2(entry, void 0, {
679
+ F: __dxlog_file3,
680
+ L: 255,
681
+ S: this,
682
+ A: [
683
+ "entry",
684
+ ""
685
+ ]
686
+ });
687
+ this.emit("peer-disconnected", {
688
+ peerId: connection.peerId
689
+ });
690
+ this._emitPeerCandidate(connection);
691
+ }
692
+ _onConnectionClosed(connection) {
693
+ log3("Connection closed", {
694
+ peerId: connection.peerId
695
+ }, {
696
+ F: __dxlog_file3,
697
+ L: 261,
698
+ S: this,
699
+ C: (f, a) => f(...a)
700
+ });
701
+ const entry = this._connections.get(connection.peerId);
702
+ invariant2(entry, void 0, {
703
+ F: __dxlog_file3,
704
+ L: 263,
705
+ S: this,
706
+ A: [
707
+ "entry",
708
+ ""
709
+ ]
710
+ });
711
+ entry.isOpen = false;
712
+ this.emit("peer-disconnected", {
713
+ peerId: connection.peerId
714
+ });
715
+ this._params.monitor?.recordPeerDisconnected(connection.peerId);
716
+ void entry.reader.cancel().catch((err) => log3.catch(err, void 0, {
717
+ F: __dxlog_file3,
718
+ L: 269,
719
+ S: this,
720
+ C: (f, a) => f(...a)
721
+ }));
722
+ void entry.writer.abort().catch((err) => log3.catch(err, void 0, {
723
+ F: __dxlog_file3,
724
+ L: 270,
725
+ S: this,
726
+ C: (f, a) => f(...a)
727
+ }));
728
+ this._connections.delete(connection.peerId);
729
+ }
730
+ _emitPeerCandidate(connection) {
731
+ this.emit("peer-candidate", {
732
+ peerId: connection.peerId,
733
+ peerMetadata: createEchoPeerMetadata()
734
+ });
735
+ }
736
+ };
737
+ _ts_decorate([
738
+ synchronized
739
+ ], EchoNetworkAdapter.prototype, "open", null);
740
+ _ts_decorate([
741
+ synchronized
742
+ ], EchoNetworkAdapter.prototype, "close", null);
743
+ _ts_decorate([
744
+ synchronized
745
+ ], EchoNetworkAdapter.prototype, "addReplicator", null);
746
+ _ts_decorate([
747
+ synchronized
748
+ ], EchoNetworkAdapter.prototype, "removeReplicator", null);
749
+ var createEchoPeerMetadata = () => ({
750
+ // TODO(dmaretskyi): Refactor this.
751
+ dxos_peerSource: "EchoNetworkAdapter"
752
+ });
753
+ var isEchoPeerMetadata = (metadata) => metadata?.dxos_peerSource === "EchoNetworkAdapter";
754
+
755
+ // packages/core/echo/echo-pipeline/src/automerge/heads-store.ts
756
+ import { headsEncoding } from "@dxos/indexing";
757
+ var HeadsStore = class {
758
+ constructor({ db }) {
759
+ this._db = db;
760
+ }
761
+ setHeads(documentId, heads, batch) {
762
+ batch.put(documentId, heads, {
763
+ sublevel: this._db,
764
+ keyEncoding: "utf8",
765
+ valueEncoding: headsEncoding
766
+ });
767
+ }
768
+ // TODO(dmaretskyi): Make batched.
769
+ async getHeads(documentIds) {
770
+ return this._db.getMany(documentIds, {
771
+ keyEncoding: "utf8",
772
+ valueEncoding: headsEncoding
773
+ });
774
+ }
775
+ };
776
+
777
+ // packages/core/echo/echo-pipeline/src/automerge/leveldb-storage-adapter.ts
778
+ import { LifecycleState as LifecycleState2, Resource as Resource3 } from "@dxos/context";
779
+ var LevelDBStorageAdapter = class extends Resource3 {
780
+ constructor(_params) {
781
+ super();
782
+ this._params = _params;
783
+ }
784
+ async load(keyArray) {
785
+ try {
786
+ if (this._lifecycleState !== LifecycleState2.OPEN) {
787
+ return void 0;
788
+ }
789
+ const startMs = Date.now();
790
+ const chunk = await this._params.db.get(keyArray, {
791
+ ...encodingOptions
792
+ });
793
+ this._params.monitor?.recordBytesLoaded(chunk.byteLength);
794
+ this._params.monitor?.recordLoadDuration(Date.now() - startMs);
795
+ return chunk;
796
+ } catch (err) {
797
+ if (isLevelDbNotFoundError(err)) {
798
+ return void 0;
799
+ }
800
+ throw err;
801
+ }
802
+ }
803
+ async save(keyArray, binary) {
804
+ if (this._lifecycleState !== LifecycleState2.OPEN) {
805
+ return void 0;
806
+ }
807
+ const startMs = Date.now();
808
+ const batch = this._params.db.batch();
809
+ await this._params.callbacks?.beforeSave?.({
810
+ path: keyArray,
811
+ batch
812
+ });
813
+ batch.put(keyArray, Buffer.from(binary), {
814
+ ...encodingOptions
815
+ });
816
+ await batch.write();
817
+ this._params.monitor?.recordBytesStored(binary.byteLength);
818
+ await this._params.callbacks?.afterSave?.(keyArray);
819
+ this._params.monitor?.recordStoreDuration(Date.now() - startMs);
820
+ }
821
+ async remove(keyArray) {
822
+ if (this._lifecycleState !== LifecycleState2.OPEN) {
823
+ return void 0;
824
+ }
825
+ await this._params.db.del(keyArray, {
826
+ ...encodingOptions
827
+ });
828
+ }
829
+ async loadRange(keyPrefix) {
830
+ if (this._lifecycleState !== LifecycleState2.OPEN) {
831
+ return [];
832
+ }
833
+ const startMs = Date.now();
834
+ const result = [];
835
+ for await (const [key, value] of this._params.db.iterator({
836
+ gte: keyPrefix,
837
+ lte: [
838
+ ...keyPrefix,
839
+ "\uFFFF"
840
+ ],
841
+ ...encodingOptions
842
+ })) {
843
+ result.push({
844
+ key,
845
+ data: value
846
+ });
847
+ this._params.monitor?.recordBytesLoaded(value.byteLength);
848
+ }
849
+ this._params.monitor?.recordLoadDuration(Date.now() - startMs);
850
+ return result;
851
+ }
852
+ async removeRange(keyPrefix) {
853
+ if (this._lifecycleState !== LifecycleState2.OPEN) {
854
+ return void 0;
855
+ }
856
+ const batch = this._params.db.batch();
857
+ for await (const [key] of this._params.db.iterator({
858
+ gte: keyPrefix,
859
+ lte: [
860
+ ...keyPrefix,
861
+ "\uFFFF"
862
+ ],
863
+ ...encodingOptions
864
+ })) {
865
+ batch.del(key, {
866
+ ...encodingOptions
867
+ });
868
+ }
869
+ await batch.write();
870
+ }
871
+ };
872
+ var keyEncoder = {
873
+ encode: (key) => Buffer.from(key.map((k) => k.replaceAll("%", "%25").replaceAll("-", "%2D")).join("-")),
874
+ decode: (key) => Buffer.from(key).toString().split("-").map((k) => k.replaceAll("%2D", "-").replaceAll("%25", "%")),
875
+ format: "buffer"
876
+ };
877
+ var encodingOptions = {
878
+ keyEncoding: keyEncoder,
879
+ valueEncoding: "buffer"
880
+ };
881
+ var isLevelDbNotFoundError = (err) => err.code === "LEVEL_NOT_FOUND";
882
+
883
+ // packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts
884
+ function _ts_decorate2(decorators, target, key, desc) {
885
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
886
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
887
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
888
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
889
+ }
890
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts";
891
+ var AutomergeHost = class extends Resource4 {
892
+ constructor({ db, indexMetadataStore, dataMonitor }) {
893
+ super();
894
+ this._collectionSynchronizer = new CollectionSynchronizer({
895
+ queryCollectionState: this._queryCollectionState.bind(this),
896
+ sendCollectionState: this._sendCollectionState.bind(this),
897
+ shouldSyncCollection: this._shouldSyncCollection.bind(this)
898
+ });
899
+ this.collectionStateUpdated = new Event2();
900
+ this._db = db;
901
+ this._storage = new LevelDBStorageAdapter({
902
+ db: db.sublevel("automerge"),
903
+ callbacks: {
904
+ beforeSave: async (params) => this._beforeSave(params),
905
+ afterSave: async (key) => this._afterSave(key)
906
+ },
907
+ monitor: dataMonitor
908
+ });
909
+ this._echoNetworkAdapter = new EchoNetworkAdapter({
910
+ getContainingSpaceForDocument: this._getContainingSpaceForDocument.bind(this),
911
+ isDocumentInRemoteCollection: this._isDocumentInRemoteCollection.bind(this),
912
+ onCollectionStateQueried: this._onCollectionStateQueried.bind(this),
913
+ onCollectionStateReceived: this._onCollectionStateReceived.bind(this),
914
+ monitor: dataMonitor
915
+ });
916
+ this._headsStore = new HeadsStore({
917
+ db: db.sublevel("heads")
918
+ });
919
+ this._indexMetadataStore = indexMetadataStore;
920
+ }
921
+ async _open() {
922
+ this._peerId = `host-${PublicKey.random().toHex()}`;
923
+ await this._storage.open?.();
924
+ this._repo = new Repo({
925
+ peerId: this._peerId,
926
+ sharePolicy: this._sharePolicy.bind(this),
927
+ storage: this._storage,
928
+ network: [
929
+ // Upstream swarm.
930
+ this._echoNetworkAdapter
931
+ ]
932
+ });
933
+ Event2.wrap(this._echoNetworkAdapter, "peer-candidate").on(this._ctx, (e) => this._onPeerConnected(e.peerId));
934
+ Event2.wrap(this._echoNetworkAdapter, "peer-disconnected").on(this._ctx, (e) => this._onPeerDisconnected(e.peerId));
935
+ this._collectionSynchronizer.remoteStateUpdated.on(this._ctx, ({ collectionId, peerId }) => {
936
+ this._onRemoteCollectionStateUpdated(collectionId, peerId);
937
+ this.collectionStateUpdated.emit({
938
+ collectionId
939
+ });
940
+ });
941
+ await this._echoNetworkAdapter.open();
942
+ await this._collectionSynchronizer.open();
943
+ await this._echoNetworkAdapter.open();
944
+ await this._echoNetworkAdapter.whenConnected();
945
+ }
946
+ async _close() {
947
+ await this._collectionSynchronizer.close();
948
+ await this._storage.close?.();
949
+ await this._echoNetworkAdapter.close();
950
+ await this._ctx.dispose();
951
+ }
952
+ /**
953
+ * @deprecated To be abstracted away.
954
+ */
955
+ get repo() {
956
+ return this._repo;
957
+ }
958
+ get peerId() {
959
+ return this._peerId;
960
+ }
961
+ get loadedDocsCount() {
962
+ return Object.keys(this._repo.handles).length;
963
+ }
964
+ async addReplicator(replicator) {
965
+ await this._echoNetworkAdapter.addReplicator(replicator);
966
+ }
967
+ async removeReplicator(replicator) {
968
+ await this._echoNetworkAdapter.removeReplicator(replicator);
969
+ }
970
+ /**
971
+ * Loads the document handle from the repo and waits for it to be ready.
972
+ */
973
+ async loadDoc(ctx, documentId, opts) {
974
+ let handle;
975
+ if (typeof documentId === "string") {
976
+ handle = this._repo.handles[documentId];
977
+ }
978
+ if (!handle) {
979
+ handle = this._repo.find(documentId);
980
+ }
981
+ if (!handle.isReady()) {
982
+ if (!opts?.timeout) {
983
+ await cancelWithContext(ctx, handle.whenReady());
984
+ } else {
985
+ await cancelWithContext(ctx, asyncTimeout(handle.whenReady(), opts.timeout));
986
+ }
987
+ }
988
+ return handle;
989
+ }
990
+ /**
991
+ * Create new persisted document.
992
+ */
993
+ createDoc(initialValue, opts) {
994
+ if (opts?.preserveHistory) {
995
+ if (!isAutomerge(initialValue)) {
996
+ throw new TypeError("Initial value must be an Automerge document");
997
+ }
998
+ return this._repo.import(save(initialValue));
999
+ } else {
1000
+ return this._repo.create(initialValue);
1001
+ }
1002
+ }
1003
+ async waitUntilHeadsReplicated(heads) {
1004
+ const entries = heads.entries;
1005
+ if (!entries?.length) {
1006
+ return;
1007
+ }
1008
+ const documentIds = entries.map((entry) => entry.documentId);
1009
+ const documentHeads = await this.getHeads(documentIds);
1010
+ const headsToWait = entries.filter((entry, index) => {
1011
+ const targetHeads = entry.heads;
1012
+ if (!targetHeads || targetHeads.length === 0) {
1013
+ return false;
1014
+ }
1015
+ const currentHeads = documentHeads[index];
1016
+ return !(currentHeads !== null && headsEquals(currentHeads, targetHeads));
1017
+ });
1018
+ if (headsToWait.length > 0) {
1019
+ await Promise.all(headsToWait.map(async (entry, index) => {
1020
+ const handle = await this.loadDoc(Context.default(void 0, {
1021
+ F: __dxlog_file4,
1022
+ L: 230
1023
+ }), entry.documentId);
1024
+ await waitForHeads(handle, entry.heads);
1025
+ }));
1026
+ }
1027
+ await this._repo.flush(documentIds.filter((documentId) => !!this._repo.handles[documentId]));
1028
+ }
1029
+ async reIndexHeads(documentIds) {
1030
+ for (const documentId of documentIds) {
1031
+ log4.info("re-indexing heads for document", {
1032
+ documentId
1033
+ }, {
1034
+ F: __dxlog_file4,
1035
+ L: 242,
1036
+ S: this,
1037
+ C: (f, a) => f(...a)
1038
+ });
1039
+ const handle = this._repo.find(documentId);
1040
+ await handle.whenReady([
1041
+ "ready",
1042
+ "requesting"
1043
+ ]);
1044
+ if (handle.inState([
1045
+ "requesting"
1046
+ ])) {
1047
+ log4.warn("document is not available locally, skipping", {
1048
+ documentId
1049
+ }, {
1050
+ F: __dxlog_file4,
1051
+ L: 246,
1052
+ S: this,
1053
+ C: (f, a) => f(...a)
1054
+ });
1055
+ continue;
1056
+ }
1057
+ const doc = handle.docSync();
1058
+ invariant3(doc, void 0, {
1059
+ F: __dxlog_file4,
1060
+ L: 251,
1061
+ S: this,
1062
+ A: [
1063
+ "doc",
1064
+ ""
1065
+ ]
1066
+ });
1067
+ const heads = getHeads(doc);
1068
+ const batch = this._db.batch();
1069
+ this._headsStore.setHeads(documentId, heads, batch);
1070
+ await batch.write();
1071
+ }
1072
+ log4.info("done re-indexing heads", void 0, {
1073
+ F: __dxlog_file4,
1074
+ L: 258,
1075
+ S: this,
1076
+ C: (f, a) => f(...a)
1077
+ });
1078
+ }
1079
+ // TODO(dmaretskyi): Share based on HALO permissions and space affinity.
1080
+ // Hosts, running in the worker, don't share documents unless requested by other peers.
1081
+ // NOTE: If both peers return sharePolicy=false the replication will not happen
1082
+ // https://github.com/automerge/automerge-repo/pull/292
1083
+ async _sharePolicy(peerId, documentId) {
1084
+ if (peerId.startsWith("client-")) {
1085
+ return false;
1086
+ }
1087
+ if (!documentId) {
1088
+ return false;
1089
+ }
1090
+ const peerMetadata = this.repo.peerMetadataByPeerId[peerId];
1091
+ if (isEchoPeerMetadata(peerMetadata)) {
1092
+ return this._echoNetworkAdapter.shouldAdvertise(peerId, {
1093
+ documentId
1094
+ });
1095
+ }
1096
+ return false;
1097
+ }
1098
+ async _beforeSave({ path, batch }) {
1099
+ const handle = this._repo.handles[path[0]];
1100
+ if (!handle) {
1101
+ return;
1102
+ }
1103
+ const doc = handle.docSync();
1104
+ if (!doc) {
1105
+ return;
1106
+ }
1107
+ const heads = getHeads(doc);
1108
+ this._headsStore.setHeads(handle.documentId, heads, batch);
1109
+ const spaceKey = getSpaceKeyFromDoc(doc) ?? void 0;
1110
+ const objectIds = Object.keys(doc.objects ?? {});
1111
+ const encodedIds = objectIds.map((objectId) => objectPointerCodec.encode({
1112
+ documentId: handle.documentId,
1113
+ objectId,
1114
+ spaceKey
1115
+ }));
1116
+ const idToLastHash = new Map(encodedIds.map((id) => [
1117
+ id,
1118
+ heads
1119
+ ]));
1120
+ this._indexMetadataStore.markDirty(idToLastHash, batch);
1121
+ }
1122
+ _shouldSyncCollection(collectionId, peerId) {
1123
+ const peerMetadata = this._repo.peerMetadataByPeerId[peerId];
1124
+ if (isEchoPeerMetadata(peerMetadata)) {
1125
+ return this._echoNetworkAdapter.shouldSyncCollection(peerId, {
1126
+ collectionId
1127
+ });
1128
+ }
1129
+ return false;
1130
+ }
1131
+ /**
1132
+ * Called by AutomergeStorageAdapter after levelDB batch commit.
1133
+ */
1134
+ async _afterSave(path) {
1135
+ this._indexMetadataStore.notifyMarkedDirty();
1136
+ const documentId = path[0];
1137
+ const document = this._repo.handles[documentId]?.docSync();
1138
+ if (document) {
1139
+ const heads = getHeads(document);
1140
+ this._onHeadsChanged(documentId, heads);
1141
+ }
1142
+ }
1143
+ _automergePeers() {
1144
+ return this._repo.peers;
1145
+ }
1146
+ async _isDocumentInRemoteCollection(params) {
1147
+ for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
1148
+ const remoteCollections = this._collectionSynchronizer.getRemoteCollectionStates(collectionId);
1149
+ const remotePeerDocs = remoteCollections.get(params.peerId)?.documents;
1150
+ if (remotePeerDocs && params.documentId in remotePeerDocs) {
1151
+ return true;
1152
+ }
1153
+ }
1154
+ return false;
1155
+ }
1156
+ async _getContainingSpaceForDocument(documentId) {
1157
+ const doc = this._repo.handles[documentId]?.docSync();
1158
+ if (!doc) {
1159
+ return null;
1160
+ }
1161
+ const spaceKeyHex = getSpaceKeyFromDoc(doc);
1162
+ if (!spaceKeyHex) {
1163
+ return null;
1164
+ }
1165
+ return PublicKey.from(spaceKeyHex);
1166
+ }
1167
+ /**
1168
+ * Flush documents to disk.
1169
+ */
1170
+ async flush({ documentIds } = {}) {
1171
+ await this._repo.flush(documentIds);
1172
+ }
1173
+ async getHeads(documentIds) {
1174
+ const result = [];
1175
+ const storeRequestIds = [];
1176
+ const storeResultIndices = [];
1177
+ for (const documentId of documentIds) {
1178
+ const doc = this._repo.handles[documentId]?.docSync();
1179
+ if (doc) {
1180
+ result.push(getHeads(doc));
1181
+ } else {
1182
+ storeRequestIds.push(documentId);
1183
+ storeResultIndices.push(result.length);
1184
+ result.push(void 0);
1185
+ }
1186
+ }
1187
+ if (storeRequestIds.length > 0) {
1188
+ const storedHeads = await this._headsStore.getHeads(storeRequestIds);
1189
+ for (let i = 0; i < storedHeads.length; i++) {
1190
+ result[storeResultIndices[i]] = storedHeads[i];
1191
+ }
1192
+ }
1193
+ return result;
1194
+ }
1195
+ //
1196
+ // Collection sync.
1197
+ //
1198
+ getLocalCollectionState(collectionId) {
1199
+ return this._collectionSynchronizer.getLocalCollectionState(collectionId);
1200
+ }
1201
+ getRemoteCollectionStates(collectionId) {
1202
+ return this._collectionSynchronizer.getRemoteCollectionStates(collectionId);
1203
+ }
1204
+ refreshCollection(collectionId) {
1205
+ this._collectionSynchronizer.refreshCollection(collectionId);
1206
+ }
1207
+ async getCollectionSyncState(collectionId) {
1208
+ const result = {
1209
+ peers: []
1210
+ };
1211
+ const localState = this.getLocalCollectionState(collectionId);
1212
+ const remoteState = this.getRemoteCollectionStates(collectionId);
1213
+ if (!localState) {
1214
+ return result;
1215
+ }
1216
+ for (const [peerId, state] of remoteState) {
1217
+ const diff = diffCollectionState(localState, state);
1218
+ result.peers.push({
1219
+ peerId,
1220
+ missingOnRemote: diff.missingOnRemote.length,
1221
+ missingOnLocal: diff.missingOnLocal.length,
1222
+ differentDocuments: diff.different.length,
1223
+ localDocumentCount: Object.keys(localState.documents).length,
1224
+ remoteDocumentCount: Object.keys(state.documents).length
1225
+ });
1226
+ }
1227
+ return result;
1228
+ }
1229
+ /**
1230
+ * Update the local collection state based on the locally stored document heads.
1231
+ */
1232
+ async updateLocalCollectionState(collectionId, documentIds) {
1233
+ const heads = await this.getHeads(documentIds);
1234
+ const documents = Object.fromEntries(heads.map((heads2, index) => [
1235
+ documentIds[index],
1236
+ heads2 ?? []
1237
+ ]));
1238
+ this._collectionSynchronizer.setLocalCollectionState(collectionId, {
1239
+ documents
1240
+ });
1241
+ }
1242
+ _onCollectionStateQueried(collectionId, peerId) {
1243
+ this._collectionSynchronizer.onCollectionStateQueried(collectionId, peerId);
1244
+ }
1245
+ _onCollectionStateReceived(collectionId, peerId, state) {
1246
+ this._collectionSynchronizer.onRemoteStateReceived(collectionId, peerId, decodeCollectionState(state));
1247
+ }
1248
+ _queryCollectionState(collectionId, peerId) {
1249
+ this._echoNetworkAdapter.queryCollectionState(collectionId, peerId);
1250
+ }
1251
+ _sendCollectionState(collectionId, peerId, state) {
1252
+ this._echoNetworkAdapter.sendCollectionState(collectionId, peerId, encodeCollectionState(state));
1253
+ }
1254
+ _onPeerConnected(peerId) {
1255
+ this._collectionSynchronizer.onConnectionOpen(peerId);
1256
+ }
1257
+ _onPeerDisconnected(peerId) {
1258
+ this._collectionSynchronizer.onConnectionClosed(peerId);
1259
+ }
1260
+ _onRemoteCollectionStateUpdated(collectionId, peerId) {
1261
+ const localState = this._collectionSynchronizer.getLocalCollectionState(collectionId);
1262
+ const remoteState = this._collectionSynchronizer.getRemoteCollectionStates(collectionId).get(peerId);
1263
+ if (!localState || !remoteState) {
1264
+ return;
1265
+ }
1266
+ const { different, missingOnLocal, missingOnRemote } = diffCollectionState(localState, remoteState);
1267
+ const toReplicate = [
1268
+ ...missingOnLocal,
1269
+ ...missingOnRemote,
1270
+ ...different
1271
+ ];
1272
+ if (toReplicate.length === 0) {
1273
+ return;
1274
+ }
1275
+ log4.info("replication documents after collection sync", {
1276
+ count: toReplicate.length
1277
+ }, {
1278
+ F: __dxlog_file4,
1279
+ L: 483,
1280
+ S: this,
1281
+ C: (f, a) => f(...a)
1282
+ });
1283
+ for (const documentId of toReplicate) {
1284
+ this._repo.find(documentId);
1285
+ }
1286
+ }
1287
+ _onHeadsChanged(documentId, heads) {
1288
+ const collectionsChanged = /* @__PURE__ */ new Set();
1289
+ for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
1290
+ const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);
1291
+ if (state?.documents[documentId]) {
1292
+ const newState = structuredClone(state);
1293
+ newState.documents[documentId] = heads;
1294
+ this._collectionSynchronizer.setLocalCollectionState(collectionId, newState);
1295
+ collectionsChanged.add(collectionId);
1296
+ }
1297
+ }
1298
+ for (const collectionId of collectionsChanged) {
1299
+ this.collectionStateUpdated.emit({
1300
+ collectionId
1301
+ });
1302
+ }
1303
+ }
1304
+ };
1305
+ _ts_decorate2([
1306
+ trace.info()
1307
+ ], AutomergeHost.prototype, "_peerId", void 0);
1308
+ _ts_decorate2([
1309
+ trace.info({
1310
+ depth: null
1311
+ })
1312
+ ], AutomergeHost.prototype, "_automergePeers", null);
1313
+ _ts_decorate2([
1314
+ trace.span({
1315
+ showInBrowserTimeline: true
1316
+ })
1317
+ ], AutomergeHost.prototype, "flush", null);
1318
+ AutomergeHost = _ts_decorate2([
1319
+ trace.resource()
1320
+ ], AutomergeHost);
1321
+ var getSpaceKeyFromDoc = (doc) => {
1322
+ const rawSpaceKey = doc.access?.spaceKey ?? doc.experimental_spaceKey;
1323
+ if (rawSpaceKey == null) {
1324
+ return null;
1325
+ }
1326
+ return String(rawSpaceKey);
1327
+ };
1328
+ var waitForHeads = async (handle, heads) => {
1329
+ const unavailableHeads = new Set(heads);
1330
+ await handle.whenReady();
1331
+ await Event2.wrap(handle, "change").waitForCondition(() => {
1332
+ for (const changeHash of unavailableHeads.values()) {
1333
+ if (changeIsPresentInDoc(handle.docSync(), changeHash)) {
1334
+ unavailableHeads.delete(changeHash);
1335
+ }
1336
+ }
1337
+ return unavailableHeads.size === 0;
1338
+ });
1339
+ };
1340
+ var changeIsPresentInDoc = (doc, changeHash) => {
1341
+ return !!getBackend(doc).getChangeByHash(changeHash);
1342
+ };
1343
+ var decodeCollectionState = (state) => {
1344
+ invariant3(typeof state === "object" && state !== null, "Invalid state", {
1345
+ F: __dxlog_file4,
1346
+ L: 541,
1347
+ S: void 0,
1348
+ A: [
1349
+ "typeof state === 'object' && state !== null",
1350
+ "'Invalid state'"
1351
+ ]
1352
+ });
1353
+ return state;
1354
+ };
1355
+ var encodeCollectionState = (state) => {
1356
+ return state;
1357
+ };
1358
+
1359
+ // packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts
1360
+ import { invariant as invariant6 } from "@dxos/invariant";
1361
+ import { PublicKey as PublicKey2 } from "@dxos/keys";
1362
+ import { log as log6 } from "@dxos/log";
1363
+ import { ComplexSet, defaultMap as defaultMap2 } from "@dxos/util";
1364
+
1365
+ // packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator-connection.ts
1366
+ import * as A2 from "@dxos/automerge/automerge";
1367
+ import { cbor } from "@dxos/automerge/automerge-repo";
1368
+ import { Resource as Resource5 } from "@dxos/context";
1369
+ import { invariant as invariant4 } from "@dxos/invariant";
1370
+ import { log as log5 } from "@dxos/log";
1371
+ import { AutomergeReplicator } from "@dxos/teleport-extension-automerge-replicator";
1372
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator-connection.ts";
1373
+ var DEFAULT_FACTORY = (params) => new AutomergeReplicator(...params);
1374
+ var MeshReplicatorConnection = class extends Resource5 {
1375
+ constructor(_params) {
1376
+ super();
1377
+ this._params = _params;
1378
+ this.remoteDeviceKey = null;
1379
+ this._remotePeerId = null;
1380
+ this._isEnabled = false;
1381
+ let readableStreamController;
1382
+ this.readable = new ReadableStream({
1383
+ start: (controller) => {
1384
+ readableStreamController = controller;
1385
+ this._ctx.onDispose(() => controller.close());
1386
+ }
1387
+ });
1388
+ this.writable = new WritableStream({
1389
+ write: async (message, controller) => {
1390
+ invariant4(this._isEnabled, "Writing to a disabled connection", {
1391
+ F: __dxlog_file5,
1392
+ L: 49,
1393
+ S: this,
1394
+ A: [
1395
+ "this._isEnabled",
1396
+ "'Writing to a disabled connection'"
1397
+ ]
1398
+ });
1399
+ try {
1400
+ logSendSync(message);
1401
+ await this.replicatorExtension.sendSyncMessage({
1402
+ payload: cbor.encode(message)
1403
+ });
1404
+ } catch (err) {
1405
+ controller.error(err);
1406
+ this._disconnectIfEnabled();
1407
+ }
1408
+ }
1409
+ });
1410
+ const createAutomergeReplicator = this._params.replicatorFactory ?? DEFAULT_FACTORY;
1411
+ this.replicatorExtension = createAutomergeReplicator([
1412
+ {
1413
+ peerId: this._params.ownPeerId
1414
+ },
1415
+ {
1416
+ onStartReplication: async (info, remotePeerId) => {
1417
+ this.remoteDeviceKey = remotePeerId;
1418
+ this._remotePeerId = info.id;
1419
+ log5("onStartReplication", {
1420
+ id: info.id,
1421
+ thisPeerId: this.peerId,
1422
+ remotePeerId: remotePeerId.toHex()
1423
+ }, {
1424
+ F: __dxlog_file5,
1425
+ L: 84,
1426
+ S: this,
1427
+ C: (f, a) => f(...a)
1428
+ });
1429
+ this._params.onRemoteConnected();
1430
+ },
1431
+ onSyncMessage: async ({ payload }) => {
1432
+ if (!this._isEnabled) {
1433
+ return;
1434
+ }
1435
+ const message = cbor.decode(payload);
1436
+ readableStreamController.enqueue(message);
1437
+ },
1438
+ onClose: async () => {
1439
+ this._disconnectIfEnabled();
1440
+ }
1441
+ }
1442
+ ]);
1443
+ }
1444
+ _disconnectIfEnabled() {
1445
+ if (this._isEnabled) {
1446
+ this._params.onRemoteDisconnected();
1447
+ }
1448
+ }
1449
+ get peerId() {
1450
+ invariant4(this._remotePeerId != null, "Remote peer has not connected yet.", {
1451
+ F: __dxlog_file5,
1452
+ L: 110,
1453
+ S: this,
1454
+ A: [
1455
+ "this._remotePeerId != null",
1456
+ "'Remote peer has not connected yet.'"
1457
+ ]
1458
+ });
1459
+ return this._remotePeerId;
1460
+ }
1461
+ async shouldAdvertise(params) {
1462
+ return this._params.shouldAdvertise(params);
1463
+ }
1464
+ shouldSyncCollection(params) {
1465
+ return this._params.shouldSyncCollection(params);
1466
+ }
1467
+ /**
1468
+ * Start exchanging messages with the remote peer.
1469
+ * Call after the remote peer has connected.
1470
+ */
1471
+ enable() {
1472
+ invariant4(this._remotePeerId != null, "Remote peer has not connected yet.", {
1473
+ F: __dxlog_file5,
1474
+ L: 127,
1475
+ S: this,
1476
+ A: [
1477
+ "this._remotePeerId != null",
1478
+ "'Remote peer has not connected yet.'"
1479
+ ]
1480
+ });
1481
+ this._isEnabled = true;
1482
+ }
1483
+ /**
1484
+ * Stop exchanging messages with the remote peer.
1485
+ */
1486
+ disable() {
1487
+ this._isEnabled = false;
1488
+ }
1489
+ };
1490
+ var logSendSync = (message) => {
1491
+ log5("sendSyncMessage", () => {
1492
+ const decodedSyncMessage = message.type === "sync" && message.data ? A2.decodeSyncMessage(message.data) : void 0;
1493
+ return {
1494
+ sync: decodedSyncMessage && {
1495
+ headsLength: decodedSyncMessage.heads.length,
1496
+ requesting: decodedSyncMessage.need.length > 0,
1497
+ sendingChanges: decodedSyncMessage.changes.length > 0
1498
+ },
1499
+ type: message.type,
1500
+ from: message.senderId,
1501
+ to: message.targetId
1502
+ };
1503
+ }, {
1504
+ F: __dxlog_file5,
1505
+ L: 140,
1506
+ S: void 0,
1507
+ C: (f, a) => f(...a)
1508
+ });
1509
+ };
1510
+
1511
+ // packages/core/echo/echo-pipeline/src/automerge/space-collection.ts
1512
+ import { invariant as invariant5 } from "@dxos/invariant";
1513
+ import { SpaceId } from "@dxos/keys";
1514
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/space-collection.ts";
1515
+ var deriveCollectionIdFromSpaceId = (spaceId) => `space:${spaceId}`;
1516
+ var getSpaceIdFromCollectionId = (collectionId) => {
1517
+ const spaceId = collectionId.replace(/^space:/, "");
1518
+ invariant5(SpaceId.isValid(spaceId), void 0, {
1519
+ F: __dxlog_file6,
1520
+ L: 13,
1521
+ S: void 0,
1522
+ A: [
1523
+ "SpaceId.isValid(spaceId)",
1524
+ ""
1525
+ ]
1526
+ });
1527
+ return spaceId;
1528
+ };
1529
+
1530
+ // packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts
1531
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts";
1532
+ var MeshEchoReplicator = class {
1533
+ constructor() {
1534
+ this._connections = /* @__PURE__ */ new Set();
1535
+ /**
1536
+ * Using automerge peerId as a key.
1537
+ */
1538
+ this._connectionsPerPeer = /* @__PURE__ */ new Map();
1539
+ /**
1540
+ * spaceId -> deviceKey[]
1541
+ */
1542
+ this._authorizedDevices = /* @__PURE__ */ new Map();
1543
+ this._context = null;
1544
+ }
1545
+ async connect(context) {
1546
+ this._context = context;
1547
+ }
1548
+ async disconnect() {
1549
+ for (const connection of this._connectionsPerPeer.values()) {
1550
+ this._context?.onConnectionClosed(connection);
1551
+ }
1552
+ for (const connection of this._connections) {
1553
+ await connection.close();
1554
+ }
1555
+ this._connections.clear();
1556
+ this._connectionsPerPeer.clear();
1557
+ this._context = null;
1558
+ }
1559
+ createExtension(extensionFactory) {
1560
+ invariant6(this._context, void 0, {
1561
+ F: __dxlog_file7,
1562
+ L: 57,
1563
+ S: this,
1564
+ A: [
1565
+ "this._context",
1566
+ ""
1567
+ ]
1568
+ });
1569
+ const connection = new MeshReplicatorConnection({
1570
+ ownPeerId: this._context.peerId,
1571
+ replicatorFactory: extensionFactory,
1572
+ onRemoteConnected: async () => {
1573
+ log6("onRemoteConnected", {
1574
+ peerId: connection.peerId
1575
+ }, {
1576
+ F: __dxlog_file7,
1577
+ L: 63,
1578
+ S: this,
1579
+ C: (f, a) => f(...a)
1580
+ });
1581
+ invariant6(this._context, void 0, {
1582
+ F: __dxlog_file7,
1583
+ L: 64,
1584
+ S: this,
1585
+ A: [
1586
+ "this._context",
1587
+ ""
1588
+ ]
1589
+ });
1590
+ if (this._connectionsPerPeer.has(connection.peerId)) {
1591
+ this._context.onConnectionAuthScopeChanged(connection);
1592
+ } else {
1593
+ this._connectionsPerPeer.set(connection.peerId, connection);
1594
+ this._context.onConnectionOpen(connection);
1595
+ connection.enable();
1596
+ }
1597
+ },
1598
+ onRemoteDisconnected: async () => {
1599
+ log6("onRemoteDisconnected", {
1600
+ peerId: connection.peerId
1601
+ }, {
1602
+ F: __dxlog_file7,
1603
+ L: 75,
1604
+ S: this,
1605
+ C: (f, a) => f(...a)
1606
+ });
1607
+ this._context?.onConnectionClosed(connection);
1608
+ this._connectionsPerPeer.delete(connection.peerId);
1609
+ connection.disable();
1610
+ this._connections.delete(connection);
1611
+ },
1612
+ shouldAdvertise: async (params) => {
1613
+ log6("shouldAdvertise", {
1614
+ peerId: connection.peerId,
1615
+ documentId: params.documentId
1616
+ }, {
1617
+ F: __dxlog_file7,
1618
+ L: 82,
1619
+ S: this,
1620
+ C: (f, a) => f(...a)
1621
+ });
1622
+ invariant6(this._context, void 0, {
1623
+ F: __dxlog_file7,
1624
+ L: 83,
1625
+ S: this,
1626
+ A: [
1627
+ "this._context",
1628
+ ""
1629
+ ]
1630
+ });
1631
+ try {
1632
+ const spaceKey = await this._context.getContainingSpaceForDocument(params.documentId);
1633
+ if (!spaceKey) {
1634
+ const remoteDocumentExists = await this._context.isDocumentInRemoteCollection({
1635
+ documentId: params.documentId,
1636
+ peerId: connection.peerId
1637
+ });
1638
+ log6("document not found locally for share policy check, accepting the remote document", {
1639
+ peerId: connection.peerId,
1640
+ documentId: params.documentId,
1641
+ remoteDocumentExists
1642
+ }, {
1643
+ F: __dxlog_file7,
1644
+ L: 91,
1645
+ S: this,
1646
+ C: (f, a) => f(...a)
1647
+ });
1648
+ return remoteDocumentExists;
1649
+ }
1650
+ const spaceId = await createIdFromSpaceKey(spaceKey);
1651
+ const authorizedDevices = this._authorizedDevices.get(spaceId);
1652
+ if (!connection.remoteDeviceKey) {
1653
+ log6("device key not found for share policy check", {
1654
+ peerId: connection.peerId,
1655
+ documentId: params.documentId
1656
+ }, {
1657
+ F: __dxlog_file7,
1658
+ L: 107,
1659
+ S: this,
1660
+ C: (f, a) => f(...a)
1661
+ });
1662
+ return false;
1663
+ }
1664
+ const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false;
1665
+ log6("share policy check", {
1666
+ localPeer: this._context.peerId,
1667
+ remotePeer: connection.peerId,
1668
+ documentId: params.documentId,
1669
+ deviceKey: connection.remoteDeviceKey,
1670
+ spaceKey,
1671
+ isAuthorized
1672
+ }, {
1673
+ F: __dxlog_file7,
1674
+ L: 115,
1675
+ S: this,
1676
+ C: (f, a) => f(...a)
1677
+ });
1678
+ return isAuthorized;
1679
+ } catch (err) {
1680
+ log6.catch(err, void 0, {
1681
+ F: __dxlog_file7,
1682
+ L: 125,
1683
+ S: this,
1684
+ C: (f, a) => f(...a)
1685
+ });
1686
+ return false;
1687
+ }
1688
+ },
1689
+ shouldSyncCollection: ({ collectionId }) => {
1690
+ const spaceId = getSpaceIdFromCollectionId(collectionId);
1691
+ const authorizedDevices = this._authorizedDevices.get(spaceId);
1692
+ if (!connection.remoteDeviceKey) {
1693
+ log6("device key not found for collection sync check", {
1694
+ peerId: connection.peerId,
1695
+ collectionId
1696
+ }, {
1697
+ F: __dxlog_file7,
1698
+ L: 135,
1699
+ S: this,
1700
+ C: (f, a) => f(...a)
1701
+ });
1702
+ return false;
1703
+ }
1704
+ const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false;
1705
+ return isAuthorized;
1706
+ }
1707
+ });
1708
+ this._connections.add(connection);
1709
+ return connection.replicatorExtension;
1710
+ }
1711
+ async authorizeDevice(spaceKey, deviceKey) {
1712
+ log6("authorizeDevice", {
1713
+ spaceKey,
1714
+ deviceKey
1715
+ }, {
1716
+ F: __dxlog_file7,
1717
+ L: 152,
1718
+ S: this,
1719
+ C: (f, a) => f(...a)
1720
+ });
1721
+ const spaceId = await createIdFromSpaceKey(spaceKey);
1722
+ defaultMap2(this._authorizedDevices, spaceId, () => new ComplexSet(PublicKey2.hash)).add(deviceKey);
1723
+ for (const connection of this._connections) {
1724
+ if (connection.remoteDeviceKey && connection.remoteDeviceKey.equals(deviceKey)) {
1725
+ if (this._connectionsPerPeer.has(connection.peerId)) {
1726
+ this._context?.onConnectionAuthScopeChanged(connection);
1727
+ }
1728
+ }
1729
+ }
1730
+ }
1731
+ };
1732
+
1733
+ // packages/core/echo/echo-pipeline/src/automerge/echo-data-monitor.ts
1734
+ import { trace as trace2 } from "@dxos/tracing";
1735
+ import { CircularBuffer, mapValues, SlidingWindowSummary } from "@dxos/util";
1736
+ function _ts_decorate3(decorators, target, key, desc) {
1737
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1738
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1739
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1740
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1741
+ }
1742
+ var PER_SECOND_RATE_AVG_WINDOW_SIZE = 5;
1743
+ var DEFAULT_AVG_WINDOW_SIZE = 25;
1744
+ var EchoDataMonitor = class {
1745
+ constructor(_params = {
1746
+ timeSeriesLength: 30
1747
+ }) {
1748
+ this._params = _params;
1749
+ this._lastTick = 0;
1750
+ this._activeCounters = createLocalCounters();
1751
+ this._localTimeSeries = createLocalTimeSeries();
1752
+ this._storageAverages = createStorageAverages();
1753
+ this._replicationAverages = createNetworkAverages();
1754
+ this._sizeByMessageType = {};
1755
+ this._lastReceivedMessages = new CircularBuffer(100);
1756
+ this._lastSentMessages = new CircularBuffer(100);
1757
+ this._connectionsCount = 0;
1758
+ }
1759
+ tick(timeMs) {
1760
+ this._advanceTimeWindow(timeMs - this._lastTick);
1761
+ this._lastTick = timeMs;
1762
+ }
1763
+ computeStats() {
1764
+ return {
1765
+ meta: {
1766
+ rateAverageOverSeconds: PER_SECOND_RATE_AVG_WINDOW_SIZE
1767
+ },
1768
+ storage: {
1769
+ reads: {
1770
+ payloadSize: this._storageAverages.loadedChunkSize.average(),
1771
+ opDuration: this._storageAverages.loadDuration.average(),
1772
+ countPerSecond: this._storageAverages.loadsPerSecond.average()
1773
+ },
1774
+ writes: {
1775
+ payloadSize: this._storageAverages.storedChunkSize.average(),
1776
+ opDuration: this._storageAverages.storeDuration.average(),
1777
+ countPerSecond: this._storageAverages.storesPerSecond.average()
1778
+ }
1779
+ },
1780
+ replicator: {
1781
+ connections: this._connectionsCount,
1782
+ receivedMessages: {
1783
+ payloadSize: this._replicationAverages.receivedMessageSize.average(),
1784
+ countPerSecond: this._replicationAverages.receivedPerSecond.average()
1785
+ },
1786
+ sentMessages: {
1787
+ payloadSize: this._replicationAverages.sentMessageSize.average(),
1788
+ opDuration: this._replicationAverages.sendDuration.average(),
1789
+ countPerSecond: this._replicationAverages.sentPerSecond.average(),
1790
+ failedPerSecond: this._replicationAverages.sendsFailedPerSecond.average()
1791
+ },
1792
+ countByMessageType: this._computeMessageHistogram("type"),
1793
+ avgSizeByMessageType: mapValues(this._sizeByMessageType, (summary) => summary.average())
1794
+ }
1795
+ };
1796
+ }
1797
+ get connectionsCount() {
1798
+ return this._connectionsCount;
1799
+ }
1800
+ /**
1801
+ * @internal
1802
+ */
1803
+ get lastPerSecondStats() {
1804
+ return this._lastCompleteCounters;
1805
+ }
1806
+ /**
1807
+ * @internal
1808
+ */
1809
+ get timeSeries() {
1810
+ return {
1811
+ ...this._localTimeSeries.storage,
1812
+ ...this._localTimeSeries.replication
1813
+ };
1814
+ }
1815
+ /**
1816
+ * @internal
1817
+ */
1818
+ get messagesByPeerId() {
1819
+ return this._computeMessageHistogram("peerId");
1820
+ }
1821
+ _advanceTimeWindow(millisPassed) {
1822
+ const oldMetrics = Object.freeze(this._activeCounters);
1823
+ this._activeCounters = createLocalCounters();
1824
+ this._lastCompleteCounters = oldMetrics;
1825
+ for (const peerId of Object.keys(oldMetrics.byPeerId)) {
1826
+ this._activeCounters.byPeerId[peerId] = createMessageCounter();
1827
+ }
1828
+ this._addToTimeSeries(oldMetrics.replication, this._localTimeSeries.replication);
1829
+ this._addToTimeSeries(oldMetrics.storage, this._localTimeSeries.storage);
1830
+ if (Math.abs(millisPassed - 1e3) < 100) {
1831
+ this._reportPerSecondRate(oldMetrics);
1832
+ }
1833
+ }
1834
+ _addToTimeSeries(values, timeSeries) {
1835
+ for (const [key, value] of Object.entries(values)) {
1836
+ const values2 = timeSeries[key];
1837
+ values2.push(value);
1838
+ if (values2.length > this._params.timeSeriesLength) {
1839
+ values2.shift();
1840
+ }
1841
+ }
1842
+ }
1843
+ _reportPerSecondRate(metrics) {
1844
+ const toReport = [
1845
+ [
1846
+ "storage.load",
1847
+ metrics.storage.loadedChunks,
1848
+ this._storageAverages.loadsPerSecond
1849
+ ],
1850
+ [
1851
+ "storage.store",
1852
+ metrics.storage.storedChunks,
1853
+ this._storageAverages.storesPerSecond
1854
+ ],
1855
+ [
1856
+ "network.receive",
1857
+ metrics.replication.received,
1858
+ this._replicationAverages.receivedPerSecond
1859
+ ],
1860
+ [
1861
+ "network.send",
1862
+ metrics.replication.sent,
1863
+ this._replicationAverages.sentPerSecond
1864
+ ]
1865
+ ];
1866
+ for (const [metricName, metric, summary] of toReport) {
1867
+ summary.record(metric);
1868
+ if (metric > 0) {
1869
+ trace2.metrics.distribution(`dxos.echo.${metricName}-rate`, metric);
1870
+ trace2.metrics.increment(`dxos.echo.${metricName}`, 1, {
1871
+ tags: {
1872
+ status: "busy"
1873
+ }
1874
+ });
1875
+ } else {
1876
+ trace2.metrics.increment(`dxos.echo.${metricName}`, 1, {
1877
+ tags: {
1878
+ status: "idle"
1879
+ }
1880
+ });
1881
+ }
1882
+ }
1883
+ this._replicationAverages.sendsFailedPerSecond.record(metrics.replication.failed);
1884
+ }
1885
+ recordPeerConnected(peerId) {
1886
+ this._activeCounters.byPeerId[peerId] = createMessageCounter();
1887
+ this._connectionsCount++;
1888
+ }
1889
+ recordPeerDisconnected(peerId) {
1890
+ this._connectionsCount--;
1891
+ delete this._activeCounters.byPeerId[peerId];
1892
+ }
1893
+ recordBytesStored(count) {
1894
+ this._activeCounters.storage.storedChunks++;
1895
+ this._activeCounters.storage.storedBytes += count;
1896
+ this._storageAverages.storedChunkSize.record(count);
1897
+ trace2.metrics.distribution("dxos.echo.storage.bytes-stored", count, {
1898
+ unit: "bytes"
1899
+ });
1900
+ }
1901
+ recordLoadDuration(durationMs) {
1902
+ this._storageAverages.loadDuration.record(durationMs);
1903
+ }
1904
+ recordStoreDuration(durationMs) {
1905
+ this._storageAverages.storeDuration.record(durationMs);
1906
+ }
1907
+ recordBytesLoaded(count) {
1908
+ this._activeCounters.storage.loadedChunks++;
1909
+ this._activeCounters.storage.loadedBytes += count;
1910
+ this._storageAverages.loadedChunkSize.record(count);
1911
+ trace2.metrics.distribution("dxos.echo.storage.bytes-loaded", count, {
1912
+ unit: "bytes"
1913
+ });
1914
+ }
1915
+ recordMessageSent(message, duration) {
1916
+ let metricsGroupName;
1917
+ const bytes = getByteCount(message);
1918
+ const tags = {
1919
+ type: message.type
1920
+ };
1921
+ if (isAutomergeProtocolMessage(message)) {
1922
+ this._activeCounters.replication.sent++;
1923
+ this._replicationAverages.sendDuration.record(duration);
1924
+ this._replicationAverages.sentMessageSize.record(bytes);
1925
+ metricsGroupName = "replication";
1926
+ } else {
1927
+ metricsGroupName = "collection-sync";
1928
+ }
1929
+ trace2.metrics.distribution(`dxos.echo.${metricsGroupName}.bytes-sent`, bytes, {
1930
+ unit: "bytes",
1931
+ tags
1932
+ });
1933
+ trace2.metrics.distribution(`dxos.echo.${metricsGroupName}.send-duration`, duration, {
1934
+ unit: "millisecond",
1935
+ tags
1936
+ });
1937
+ trace2.metrics.increment(`dxos.echo.${metricsGroupName}.send-status`, 1, {
1938
+ tags: {
1939
+ ...tags,
1940
+ success: true
1941
+ }
1942
+ });
1943
+ const { messageSize, messageCounts } = this._getStatsForType(message);
1944
+ messageSize.record(bytes);
1945
+ messageCounts.sent++;
1946
+ this._lastSentMessages.push({
1947
+ type: message.type,
1948
+ peerId: message.targetId
1949
+ });
1950
+ }
1951
+ recordMessageReceived(message) {
1952
+ const bytes = getByteCount(message);
1953
+ const tags = {
1954
+ type: message.type
1955
+ };
1956
+ if (isAutomergeProtocolMessage(message)) {
1957
+ this._activeCounters.replication.received++;
1958
+ this._replicationAverages.receivedMessageSize.record(bytes);
1959
+ trace2.metrics.distribution("dxos.echo.replication.bytes-received", bytes, {
1960
+ unit: "bytes",
1961
+ tags
1962
+ });
1963
+ } else {
1964
+ trace2.metrics.distribution("dxos.echo.collection-sync.bytes-received", bytes, {
1965
+ unit: "bytes",
1966
+ tags
1967
+ });
1968
+ }
1969
+ const { messageSize, messageCounts } = this._getStatsForType(message);
1970
+ messageSize.record(bytes);
1971
+ messageCounts.received++;
1972
+ this._lastReceivedMessages.push({
1973
+ type: message.type,
1974
+ peerId: message.senderId
1975
+ });
1976
+ }
1977
+ recordMessageSendingFailed(message) {
1978
+ const tags = {
1979
+ type: message.type,
1980
+ success: false
1981
+ };
1982
+ if (isAutomergeProtocolMessage(message)) {
1983
+ this._activeCounters.replication.failed++;
1984
+ trace2.metrics.increment("dxos.echo.replication.send-status", 1, {
1985
+ unit: "bytes",
1986
+ tags
1987
+ });
1988
+ } else {
1989
+ trace2.metrics.increment("dxos.echo.collection-sync.send-status", 1, {
1990
+ unit: "bytes",
1991
+ tags
1992
+ });
1993
+ }
1994
+ const { messageCounts } = this._getStatsForType(message);
1995
+ messageCounts.failed++;
1996
+ }
1997
+ _getStatsForType(message) {
1998
+ const messageSize = this._sizeByMessageType[message.type] ??= createSlidingWindow();
1999
+ const messageCounts = this._activeCounters.byType[message.type] ??= createMessageCounter();
2000
+ return {
2001
+ messageCounts,
2002
+ messageSize
2003
+ };
2004
+ }
2005
+ _computeMessageHistogram(groupKey) {
2006
+ const result = {};
2007
+ for (const receivedMessage of this._lastReceivedMessages) {
2008
+ const counters = result[receivedMessage[groupKey]] ??= {
2009
+ received: 0,
2010
+ sent: 0
2011
+ };
2012
+ counters.received++;
2013
+ }
2014
+ for (const receivedMessage of this._lastSentMessages) {
2015
+ const counters = result[receivedMessage[groupKey]] ??= {
2016
+ received: 0,
2017
+ sent: 0
2018
+ };
2019
+ counters.sent++;
2020
+ }
2021
+ return result;
2022
+ }
2023
+ };
2024
+ EchoDataMonitor = _ts_decorate3([
2025
+ trace2.resource()
2026
+ ], EchoDataMonitor);
2027
+ var isAutomergeProtocolMessage = (message) => {
2028
+ return !(isCollectionQueryMessage(message) || isCollectionStateMessage(message));
2029
+ };
2030
+ var createSlidingWindow = (overrides) => new SlidingWindowSummary({
2031
+ dataPoints: DEFAULT_AVG_WINDOW_SIZE,
2032
+ precision: 2,
2033
+ ...overrides
2034
+ });
2035
+ var createLocalCounters = () => ({
2036
+ storage: {
2037
+ loadedBytes: 0,
2038
+ storedBytes: 0,
2039
+ storedChunks: 0,
2040
+ loadedChunks: 0
2041
+ },
2042
+ replication: createMessageCounter(),
2043
+ byPeerId: {},
2044
+ byType: {}
2045
+ });
2046
+ var createLocalTimeSeries = () => ({
2047
+ storage: {
2048
+ loadedBytes: [],
2049
+ storedBytes: [],
2050
+ storedChunks: [],
2051
+ loadedChunks: []
2052
+ },
2053
+ replication: {
2054
+ sent: [],
2055
+ failed: [],
2056
+ received: []
2057
+ }
2058
+ });
2059
+ var createMessageCounter = () => ({
2060
+ sent: 0,
2061
+ received: 0,
2062
+ failed: 0
2063
+ });
2064
+ var createNetworkAverages = () => ({
2065
+ receivedMessageSize: createSlidingWindow(),
2066
+ sentMessageSize: createSlidingWindow(),
2067
+ sendDuration: createSlidingWindow(),
2068
+ receivedPerSecond: createSlidingWindow({
2069
+ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2070
+ }),
2071
+ sentPerSecond: createSlidingWindow({
2072
+ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2073
+ }),
2074
+ sendsFailedPerSecond: createSlidingWindow({
2075
+ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2076
+ })
2077
+ });
2078
+ var createStorageAverages = () => ({
2079
+ storedChunkSize: createSlidingWindow(),
2080
+ loadedChunkSize: createSlidingWindow(),
2081
+ loadDuration: createSlidingWindow(),
2082
+ storeDuration: createSlidingWindow(),
2083
+ loadsPerSecond: createSlidingWindow({
2084
+ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2085
+ }),
2086
+ storesPerSecond: createSlidingWindow({
2087
+ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2088
+ })
2089
+ });
2090
+ var getByteCount = (message) => {
2091
+ return message.type.length + message.senderId.length + message.targetId.length + (message.data?.byteLength ?? 0) + (message.documentId?.length ?? 0);
2092
+ };
2093
+
2094
+ // packages/core/echo/echo-pipeline/src/db-host/data-service.ts
2095
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/data-service.ts";
2096
+ var DataServiceImpl = class {
2097
+ constructor(params) {
2098
+ /**
2099
+ * Map of subscriptions.
2100
+ * subscriptionId -> DocumentsSynchronizer
2101
+ */
2102
+ this._subscriptions = /* @__PURE__ */ new Map();
2103
+ this._automergeHost = params.automergeHost;
2104
+ this._updateIndexes = params.updateIndexes;
2105
+ }
2106
+ subscribe(request) {
2107
+ return new Stream(({ next, ready }) => {
2108
+ const synchronizer = new DocumentsSynchronizer({
2109
+ repo: this._automergeHost.repo,
2110
+ sendUpdates: (updates) => next(updates)
2111
+ });
2112
+ synchronizer.open().then(() => {
2113
+ this._subscriptions.set(request.subscriptionId, synchronizer);
2114
+ ready();
2115
+ }).catch((err) => log7.catch(err, void 0, {
2116
+ F: __dxlog_file8,
2117
+ L: 66,
2118
+ S: this,
2119
+ C: (f, a) => f(...a)
2120
+ }));
2121
+ return () => synchronizer.close();
2122
+ });
2123
+ }
2124
+ async updateSubscription(request) {
2125
+ const synchronizer = this._subscriptions.get(request.subscriptionId);
2126
+ invariant7(synchronizer, "Subscription not found", {
2127
+ F: __dxlog_file8,
2128
+ L: 73,
2129
+ S: this,
2130
+ A: [
2131
+ "synchronizer",
2132
+ "'Subscription not found'"
2133
+ ]
2134
+ });
2135
+ if (request.addIds?.length) {
2136
+ await synchronizer.addDocuments(request.addIds);
2137
+ }
2138
+ if (request.removeIds?.length) {
2139
+ await synchronizer.removeDocuments(request.removeIds);
2140
+ }
2141
+ }
2142
+ async update(request) {
2143
+ if (!request.updates) {
2144
+ return;
2145
+ }
2146
+ const synchronizer = this._subscriptions.get(request.subscriptionId);
2147
+ invariant7(synchronizer, "Subscription not found", {
2148
+ F: __dxlog_file8,
2149
+ L: 88,
2150
+ S: this,
2151
+ A: [
2152
+ "synchronizer",
2153
+ "'Subscription not found'"
2154
+ ]
2155
+ });
2156
+ synchronizer.update(request.updates);
2157
+ }
2158
+ async flush(request) {
2159
+ await this._automergeHost.flush(request);
2160
+ }
2161
+ async getDocumentHeads(request) {
2162
+ const documentIds = request.documentIds;
2163
+ if (!documentIds) {
2164
+ return {
2165
+ heads: {
2166
+ entries: []
2167
+ }
2168
+ };
2169
+ }
2170
+ const heads = await this._automergeHost.getHeads(documentIds);
2171
+ return {
2172
+ heads: {
2173
+ entries: heads.map((heads2, idx) => ({
2174
+ documentId: documentIds[idx],
2175
+ heads: heads2
2176
+ }))
2177
+ }
2178
+ };
2179
+ }
2180
+ async waitUntilHeadsReplicated(request, options) {
2181
+ await this._automergeHost.waitUntilHeadsReplicated(request.heads);
2182
+ }
2183
+ async reIndexHeads(request, options) {
2184
+ await this._automergeHost.reIndexHeads(request.documentIds ?? []);
2185
+ }
2186
+ async updateIndexes() {
2187
+ await this._updateIndexes();
2188
+ }
2189
+ subscribeSpaceSyncState(request) {
2190
+ return new Stream(({ ctx, next, ready }) => {
2191
+ invariant7(SpaceId2.isValid(request.spaceId), void 0, {
2192
+ F: __dxlog_file8,
2193
+ L: 127,
2194
+ S: this,
2195
+ A: [
2196
+ "SpaceId.isValid(request.spaceId)",
2197
+ ""
2198
+ ]
2199
+ });
2200
+ const collectionId = deriveCollectionIdFromSpaceId(request.spaceId);
2201
+ const scheduler = new UpdateScheduler2(ctx, async () => {
2202
+ const state = await this._automergeHost.getCollectionSyncState(collectionId);
2203
+ next({
2204
+ peers: state.peers.map((peer) => ({
2205
+ peerId: peer.peerId,
2206
+ missingOnRemote: peer.missingOnRemote,
2207
+ missingOnLocal: peer.missingOnLocal,
2208
+ differentDocuments: peer.differentDocuments,
2209
+ localDocumentCount: peer.localDocumentCount,
2210
+ remoteDocumentCount: peer.remoteDocumentCount
2211
+ }))
2212
+ });
2213
+ });
2214
+ this._automergeHost.collectionStateUpdated.on(ctx, (e) => {
2215
+ if (e.collectionId === collectionId) {
2216
+ scheduler.trigger();
2217
+ }
2218
+ });
2219
+ scheduler.trigger();
2220
+ });
2221
+ }
2222
+ };
2223
+
2224
+ // packages/core/echo/echo-pipeline/src/db-host/echo-host.ts
2225
+ import { LifecycleState as LifecycleState4, Resource as Resource9 } from "@dxos/context";
2226
+ import { todo } from "@dxos/debug";
2227
+ import { createIdFromSpaceKey as createIdFromSpaceKey3, SpaceDocVersion as SpaceDocVersion3 } from "@dxos/echo-protocol";
2228
+ import { IndexMetadataStore, IndexStore, Indexer } from "@dxos/indexing";
2229
+ import { invariant as invariant11 } from "@dxos/invariant";
2230
+ import { IndexKind } from "@dxos/protocols/proto/dxos/echo/indexing";
2231
+ import { trace as trace5 } from "@dxos/tracing";
2232
+
2233
+ // packages/core/echo/echo-pipeline/src/db-host/documents-iterator.ts
2234
+ import * as A3 from "@dxos/automerge/automerge";
2235
+ import { Context as Context2 } from "@dxos/context";
2236
+ import { SpaceDocVersion } from "@dxos/echo-protocol";
2237
+ import { invariant as invariant8 } from "@dxos/invariant";
2238
+ import { log as log8 } from "@dxos/log";
2239
+ import { ObjectPointerVersion, objectPointerCodec as objectPointerCodec2 } from "@dxos/protocols";
2240
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/documents-iterator.ts";
2241
+ var LOG_VIEW_OPERATION_THRESHOLD = 300;
2242
+ var createSelectedDocumentsIterator = (automergeHost) => (
2243
+ /**
2244
+ * Get object data blobs from Automerge Repo by ids.
2245
+ */
2246
+ // TODO(mykola): Unload automerge handles after usage.
2247
+ async function* loadDocuments(objects) {
2248
+ for (const [id, heads] of objects.entries()) {
2249
+ try {
2250
+ const { documentId, objectId } = objectPointerCodec2.decode(id);
2251
+ const handle = await automergeHost.loadDoc(Context2.default(void 0, {
2252
+ F: __dxlog_file9,
2253
+ L: 30
2254
+ }), documentId);
2255
+ let doc = handle.docSync();
2256
+ invariant8(doc, void 0, {
2257
+ F: __dxlog_file9,
2258
+ L: 33,
2259
+ S: this,
2260
+ A: [
2261
+ "doc",
2262
+ ""
2263
+ ]
2264
+ });
2265
+ const currentHeads = A3.getHeads(doc);
2266
+ if (!A3.equals(currentHeads, heads)) {
2267
+ const begin = Date.now();
2268
+ doc = A3.view(doc, heads);
2269
+ const end = Date.now();
2270
+ if (end - begin > LOG_VIEW_OPERATION_THRESHOLD) {
2271
+ log8.info("Checking out document version is taking too long", {
2272
+ duration: end - begin,
2273
+ requestedHeads: heads,
2274
+ originalHeads: currentHeads
2275
+ }, {
2276
+ F: __dxlog_file9,
2277
+ L: 44,
2278
+ S: this,
2279
+ C: (f, a) => f(...a)
2280
+ });
2281
+ }
2282
+ }
2283
+ if (doc.version !== SpaceDocVersion.CURRENT) {
2284
+ continue;
2285
+ }
2286
+ if (!doc.objects?.[objectId]) {
2287
+ continue;
2288
+ }
2289
+ let newId = id;
2290
+ if (objectPointerCodec2.getVersion(id) === ObjectPointerVersion.V0) {
2291
+ const spaceKey = getSpaceKeyFromDoc(doc) ?? void 0;
2292
+ newId = objectPointerCodec2.encode({
2293
+ documentId,
2294
+ objectId,
2295
+ spaceKey
2296
+ });
2297
+ }
2298
+ yield [
2299
+ {
2300
+ id: newId,
2301
+ object: doc.objects[objectId],
2302
+ heads
2303
+ }
2304
+ ];
2305
+ } catch (error) {
2306
+ log8.error("Error loading document", {
2307
+ heads,
2308
+ id,
2309
+ error
2310
+ }, {
2311
+ F: __dxlog_file9,
2312
+ L: 70,
2313
+ S: this,
2314
+ C: (f, a) => f(...a)
2315
+ });
2316
+ }
2317
+ }
2318
+ }
2319
+ );
2320
+
2321
+ // packages/core/echo/echo-pipeline/src/db-host/query-service.ts
2322
+ import { DeferredTask } from "@dxos/async";
2323
+ import { getHeads as getHeads3 } from "@dxos/automerge/automerge";
2324
+ import { Stream as Stream2 } from "@dxos/codec-protobuf";
2325
+ import { Context as Context4, Resource as Resource7 } from "@dxos/context";
2326
+ import { log as log9 } from "@dxos/log";
2327
+ import { objectPointerCodec as objectPointerCodec4 } from "@dxos/protocols";
2328
+ import { trace as trace4 } from "@dxos/tracing";
2329
+
2330
+ // packages/core/echo/echo-pipeline/src/db-host/query-state.ts
2331
+ import { Context as Context3, LifecycleState as LifecycleState3, Resource as Resource6 } from "@dxos/context";
2332
+ import { createIdFromSpaceKey as createIdFromSpaceKey2 } from "@dxos/echo-protocol";
2333
+ import { invariant as invariant9 } from "@dxos/invariant";
2334
+ import { PublicKey as PublicKey3 } from "@dxos/keys";
2335
+ import { objectPointerCodec as objectPointerCodec3 } from "@dxos/protocols";
2336
+ import { trace as trace3 } from "@dxos/tracing";
2337
+ import { nonNullable as nonNullable2 } from "@dxos/util";
2338
+ function _ts_decorate4(decorators, target, key, desc) {
2339
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2340
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2341
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2342
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2343
+ }
2344
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/query-state.ts";
2345
+ var QueryState = class extends Resource6 {
2346
+ get active() {
2347
+ return this._lifecycleState === LifecycleState3.OPEN;
2348
+ }
2349
+ constructor(_params) {
2350
+ super();
2351
+ this._params = _params;
2352
+ this._results = [];
2353
+ this._firstRun = true;
2354
+ this.metrics = {
2355
+ objectsReturned: 0,
2356
+ objectsReturnedFromIndex: 0,
2357
+ documentsLoaded: 0,
2358
+ executionTime: 0,
2359
+ indexQueryTime: 0,
2360
+ documentLoadTime: 0
2361
+ };
2362
+ this.filter = _params.request.filter;
2363
+ }
2364
+ getResults() {
2365
+ return this._results;
2366
+ }
2367
+ // https://github.com/open-telemetry/semantic-conventions/blob/main/docs/attributes-registry/db.md#generic-database-attributes
2368
+ async execQuery() {
2369
+ const filter = this._params.request.filter;
2370
+ const beginQuery = performance.now();
2371
+ const hits = filter.objectIds && filter.objectIds?.length > 0 ? [] : await this._params.indexer.execQuery(filterToIndexQuery(filter));
2372
+ if (this._firstRun) {
2373
+ this.metrics.indexQueryTime = performance.now() - beginQuery;
2374
+ }
2375
+ const beginFilter = performance.now();
2376
+ const results = (await Promise.all(hits.map(async (result) => {
2377
+ if (this._firstRun) {
2378
+ this.metrics.objectsReturnedFromIndex++;
2379
+ }
2380
+ const { objectId, documentId, spaceKey: spaceKeyInIndex } = objectPointerCodec3.decode(result.id);
2381
+ let spaceKey;
2382
+ if (spaceKeyInIndex !== void 0) {
2383
+ spaceKey = spaceKeyInIndex;
2384
+ } else {
2385
+ if (this._firstRun) {
2386
+ this.metrics.documentsLoaded++;
2387
+ }
2388
+ const handle = await this._params.automergeHost.loadDoc(Context3.default(void 0, {
2389
+ F: __dxlog_file10,
2390
+ L: 116
2391
+ }), documentId);
2392
+ if (this._ctx.disposed) {
2393
+ return;
2394
+ }
2395
+ spaceKey = getSpaceKeyFromDoc(handle.docSync());
2396
+ }
2397
+ if (!spaceKey) {
2398
+ return;
2399
+ }
2400
+ if (this._params.request.filter.options?.spaces?.length && !this._params.request.filter.options.spaces.some((key) => key.equals(spaceKey))) {
2401
+ return;
2402
+ }
2403
+ if (this._firstRun) {
2404
+ this.metrics.objectsReturned++;
2405
+ }
2406
+ return {
2407
+ id: objectId,
2408
+ documentId,
2409
+ spaceId: await createIdFromSpaceKey2(PublicKey3.from(spaceKey)),
2410
+ spaceKey: PublicKey3.from(spaceKey),
2411
+ rank: result.rank
2412
+ };
2413
+ }))).filter(nonNullable2);
2414
+ if (this._firstRun) {
2415
+ this.metrics.documentLoadTime = performance.now() - beginFilter;
2416
+ }
2417
+ if (this._ctx.disposed) {
2418
+ return {
2419
+ changed: false
2420
+ };
2421
+ }
2422
+ const areResultsUnchanged = !this._firstRun && this._results.length === results.length && this._results.every((oldResult) => results.some((result) => result.id === oldResult.id)) && results.every((result) => this._results.some((oldResult) => oldResult.id === result.id));
2423
+ if (this._firstRun) {
2424
+ this.metrics.executionTime = performance.now() - beginQuery;
2425
+ }
2426
+ this._firstRun = false;
2427
+ if (areResultsUnchanged) {
2428
+ return {
2429
+ changed: false
2430
+ };
2431
+ }
2432
+ this._results = results;
2433
+ return {
2434
+ changed: true
2435
+ };
2436
+ }
2437
+ };
2438
+ _ts_decorate4([
2439
+ trace3.info({
2440
+ depth: null
2441
+ })
2442
+ ], QueryState.prototype, "filter", void 0);
2443
+ _ts_decorate4([
2444
+ trace3.info()
2445
+ ], QueryState.prototype, "metrics", void 0);
2446
+ _ts_decorate4([
2447
+ trace3.info()
2448
+ ], QueryState.prototype, "active", null);
2449
+ _ts_decorate4([
2450
+ trace3.span({
2451
+ showInBrowserTimeline: true,
2452
+ op: "db.query",
2453
+ attributes: {
2454
+ "db.system": "echo"
2455
+ }
2456
+ })
2457
+ ], QueryState.prototype, "execQuery", null);
2458
+ QueryState = _ts_decorate4([
2459
+ trace3.resource()
2460
+ ], QueryState);
2461
+ var filterToIndexQuery = (filter) => {
2462
+ invariant9(!(filter.type && (filter.or ?? []).length > 0), "Cannot mix type and or filters.", {
2463
+ F: __dxlog_file10,
2464
+ L: 181,
2465
+ S: void 0,
2466
+ A: [
2467
+ "!(filter.type && (filter.or ?? []).length > 0)",
2468
+ "'Cannot mix type and or filters.'"
2469
+ ]
2470
+ });
2471
+ invariant9((filter.or ?? []).every((subFilter) => !(subFilter.type && (subFilter.or ?? []).length > 0)), "Cannot mix type and or filters.", {
2472
+ F: __dxlog_file10,
2473
+ L: 182,
2474
+ S: void 0,
2475
+ A: [
2476
+ "(filter.or ?? []).every((subFilter) => !(subFilter.type && (subFilter.or ?? []).length > 0))",
2477
+ "'Cannot mix type and or filters.'"
2478
+ ]
2479
+ });
2480
+ if (filter.type || (filter.or ?? []).length > 0 && (filter.or ?? []).every((subFilter) => !subFilter.not && subFilter.type)) {
2481
+ return {
2482
+ typenames: filter.type?.objectId ? [
2483
+ filter.type.objectId
2484
+ ] : (filter.or ?? []).map((f) => f.type?.objectId).filter(nonNullable2),
2485
+ inverted: filter.not
2486
+ };
2487
+ } else {
2488
+ return {
2489
+ typenames: []
2490
+ };
2491
+ }
2492
+ };
2493
+
2494
+ // packages/core/echo/echo-pipeline/src/db-host/query-service.ts
2495
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/query-service.ts";
2496
+ var QueryServiceImpl = class extends Resource7 {
2497
+ // TODO(burdon): OK for options, but not params. Pass separately and type readonly here.
2498
+ constructor(_params) {
2499
+ super();
2500
+ this._params = _params;
2501
+ this._queries = /* @__PURE__ */ new Set();
2502
+ this._updateQueries = new DeferredTask(this._ctx, async () => {
2503
+ await Promise.all(Array.from(this._queries).map(async (query) => {
2504
+ try {
2505
+ const { changed } = await query.state.execQuery();
2506
+ if (changed) {
2507
+ query.sendResults(query.state.getResults());
2508
+ }
2509
+ } catch (err) {
2510
+ log9.catch(err, void 0, {
2511
+ F: __dxlog_file11,
2512
+ L: 52,
2513
+ S: this,
2514
+ C: (f, a) => f(...a)
2515
+ });
2516
+ }
2517
+ }));
2518
+ });
2519
+ trace4.diagnostic({
2520
+ id: "active-queries",
2521
+ name: "Active Queries",
2522
+ fetch: () => {
2523
+ return Array.from(this._queries).map((query) => {
2524
+ return {
2525
+ filter: JSON.stringify(query.state.filter),
2526
+ metrics: query.state.metrics
2527
+ };
2528
+ });
2529
+ }
2530
+ });
2531
+ }
2532
+ async _open() {
2533
+ this._params.indexer.updated.on(this._ctx, () => this._updateQueries.schedule());
2534
+ }
2535
+ async _close() {
2536
+ await Promise.all(Array.from(this._queries).map((query) => query.close()));
2537
+ }
2538
+ async setConfig(config) {
2539
+ if (this._params.indexer.initialized) {
2540
+ log9.warn("Indexer already initialized.", void 0, {
2541
+ F: __dxlog_file11,
2542
+ L: 86,
2543
+ S: this,
2544
+ C: (f, a) => f(...a)
2545
+ });
2546
+ return;
2547
+ }
2548
+ this._params.indexer.setConfig(config);
2549
+ }
2550
+ execQuery(request) {
2551
+ return new Stream2(({ next, close, ctx }) => {
2552
+ const query = {
2553
+ state: new QueryState({
2554
+ indexer: this._params.indexer,
2555
+ automergeHost: this._params.automergeHost,
2556
+ request
2557
+ }),
2558
+ sendResults: (results) => {
2559
+ if (ctx.disposed) {
2560
+ return;
2561
+ }
2562
+ next({
2563
+ queryId: request.queryId,
2564
+ results
2565
+ });
2566
+ },
2567
+ close: async () => {
2568
+ close();
2569
+ await query.state.close();
2570
+ this._queries.delete(query);
2571
+ }
2572
+ };
2573
+ this._queries.add(query);
2574
+ queueMicrotask(async () => {
2575
+ await query.state.open();
2576
+ try {
2577
+ const { changed } = await query.state.execQuery();
2578
+ if (changed) {
2579
+ query.sendResults(query.state.getResults());
2580
+ }
2581
+ } catch (error) {
2582
+ log9.catch(error, void 0, {
2583
+ F: __dxlog_file11,
2584
+ L: 123,
2585
+ S: this,
2586
+ C: (f, a) => f(...a)
2587
+ });
2588
+ }
2589
+ });
2590
+ return query.close;
2591
+ });
2592
+ }
2593
+ /**
2594
+ * Re-index all loaded documents.
2595
+ */
2596
+ async reindex() {
2597
+ log9.info("Reindexing all documents...", void 0, {
2598
+ F: __dxlog_file11,
2599
+ L: 135,
2600
+ S: this,
2601
+ C: (f, a) => f(...a)
2602
+ });
2603
+ const iterator = createDocumentsIterator(this._params.automergeHost);
2604
+ const ids = /* @__PURE__ */ new Map();
2605
+ for await (const documents of iterator()) {
2606
+ for (const { id, heads } of documents) {
2607
+ ids.set(id, heads);
2608
+ }
2609
+ if (ids.size % 100 === 0) {
2610
+ log9.info("Collected documents...", {
2611
+ count: ids.size
2612
+ }, {
2613
+ F: __dxlog_file11,
2614
+ L: 143,
2615
+ S: this,
2616
+ C: (f, a) => f(...a)
2617
+ });
2618
+ }
2619
+ }
2620
+ log9.info("Marking all documents as dirty...", {
2621
+ count: ids.size
2622
+ }, {
2623
+ F: __dxlog_file11,
2624
+ L: 147,
2625
+ S: this,
2626
+ C: (f, a) => f(...a)
2627
+ });
2628
+ await this._params.indexer.reindex(ids);
2629
+ }
2630
+ };
2631
+ var createDocumentsIterator = (automergeHost) => (
2632
+ /**
2633
+ * Recursively get all object data blobs from loaded documents from Automerge Repo.
2634
+ */
2635
+ // TODO(mykola): Unload automerge handles after usage.
2636
+ async function* getAllDocuments() {
2637
+ const visited = /* @__PURE__ */ new Set();
2638
+ async function* getObjectsFromHandle(handle) {
2639
+ if (visited.has(handle.documentId)) {
2640
+ return;
2641
+ }
2642
+ const doc = handle.docSync();
2643
+ const spaceKey = getSpaceKeyFromDoc(doc) ?? void 0;
2644
+ if (doc.objects) {
2645
+ yield Object.entries(doc.objects).map(([objectId, object]) => {
2646
+ return {
2647
+ id: objectPointerCodec4.encode({
2648
+ documentId: handle.documentId,
2649
+ objectId,
2650
+ spaceKey
2651
+ }),
2652
+ object,
2653
+ heads: getHeads3(doc)
2654
+ };
2655
+ });
2656
+ }
2657
+ if (doc.links) {
2658
+ for (const id of Object.values(doc.links)) {
2659
+ if (visited.has(id)) {
2660
+ continue;
2661
+ }
2662
+ const linkHandle = await automergeHost.loadDoc(Context4.default(void 0, {
2663
+ F: __dxlog_file11,
2664
+ L: 188
2665
+ }), id);
2666
+ for await (const result of getObjectsFromHandle(linkHandle)) {
2667
+ yield result;
2668
+ }
2669
+ }
2670
+ }
2671
+ visited.add(handle.documentId);
2672
+ }
2673
+ for (const handle of Object.values(automergeHost.repo.handles)) {
2674
+ if (visited.has(handle.documentId)) {
2675
+ continue;
2676
+ }
2677
+ for await (const result of getObjectsFromHandle(handle)) {
2678
+ yield result;
2679
+ }
2680
+ visited.add(handle.documentId);
2681
+ }
2682
+ }
2683
+ );
2684
+
2685
+ // packages/core/echo/echo-pipeline/src/db-host/space-state-manager.ts
2686
+ import isEqual from "lodash.isequal";
2687
+ import { Event as Event3, UpdateScheduler as UpdateScheduler3 } from "@dxos/async";
2688
+ import { interpretAsDocumentId } from "@dxos/automerge/automerge-repo";
2689
+ import { Resource as Resource8, Context as Context5 } from "@dxos/context";
2690
+
2691
+ // packages/core/echo/echo-pipeline/src/db-host/database-root.ts
2692
+ import { SpaceDocVersion as SpaceDocVersion2 } from "@dxos/echo-protocol";
2693
+ import { invariant as invariant10 } from "@dxos/invariant";
2694
+
2695
+ // packages/core/echo/echo-pipeline/src/db-host/automerge-metrics.ts
2696
+ import * as A4 from "@dxos/automerge/automerge";
2697
+ import { log as log10 } from "@dxos/log";
2698
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/automerge-metrics.ts";
2699
+ var measureDocMetrics = (doc) => {
2700
+ const snapshot = A4.save(doc);
2701
+ const start = Date.now();
2702
+ const temp = A4.load(snapshot);
2703
+ const end = Date.now();
2704
+ A4.free(temp);
2705
+ const getAllChangesStart = Date.now();
2706
+ const mutationCount = A4.getAllChanges(doc).length;
2707
+ const getAllChangesEnd = Date.now();
2708
+ if (getAllChangesEnd - getAllChangesStart > 300) {
2709
+ log10.warn("getAllChanges took too long", {
2710
+ elapsed: getAllChangesEnd - getAllChangesStart
2711
+ }, {
2712
+ F: __dxlog_file12,
2713
+ L: 30,
2714
+ S: void 0,
2715
+ C: (f, a) => f(...a)
2716
+ });
2717
+ }
2718
+ return {
2719
+ compressedByteSize: snapshot.byteLength,
2720
+ loadTime: end - start,
2721
+ mutationCount
2722
+ };
2723
+ };
2724
+
2725
+ // packages/core/echo/echo-pipeline/src/db-host/database-root.ts
2726
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/database-root.ts";
2727
+ var DatabaseRoot = class {
2728
+ constructor(_rootHandle) {
2729
+ this._rootHandle = _rootHandle;
2730
+ }
2731
+ get documentId() {
2732
+ return this._rootHandle.documentId;
2733
+ }
2734
+ get url() {
2735
+ return this._rootHandle.url;
2736
+ }
2737
+ get isLoaded() {
2738
+ return !!this._rootHandle.docSync();
2739
+ }
2740
+ get handle() {
2741
+ return this._rootHandle;
2742
+ }
2743
+ docSync() {
2744
+ return this._rootHandle.docSync();
2745
+ }
2746
+ getVersion() {
2747
+ const doc = this.docSync();
2748
+ if (!doc) {
2749
+ return null;
2750
+ }
2751
+ return doc.version ?? SpaceDocVersion2.LEGACY;
2752
+ }
2753
+ getSpaceKey() {
2754
+ const doc = this.docSync();
2755
+ if (!doc) {
2756
+ return null;
2757
+ }
2758
+ return getSpaceKeyFromDoc(doc);
2759
+ }
2760
+ getInlineObjectCount() {
2761
+ const doc = this.docSync();
2762
+ if (!doc) {
2763
+ return null;
2764
+ }
2765
+ return Object.keys(doc.objects ?? {}).length;
2766
+ }
2767
+ getLinkedObjectCount() {
2768
+ const doc = this.docSync();
2769
+ if (!doc) {
2770
+ return null;
2771
+ }
2772
+ return Object.keys(doc.links ?? {}).length;
2773
+ }
2774
+ getAllLinkedDocuments() {
2775
+ const doc = this.docSync();
2776
+ invariant10(doc, void 0, {
2777
+ F: __dxlog_file13,
2778
+ L: 74,
2779
+ S: this,
2780
+ A: [
2781
+ "doc",
2782
+ ""
2783
+ ]
2784
+ });
2785
+ return Object.values(doc.links ?? {});
2786
+ }
2787
+ measureMetrics() {
2788
+ const doc = this.docSync();
2789
+ if (!doc) {
2790
+ return null;
2791
+ }
2792
+ return measureDocMetrics(doc);
2793
+ }
2794
+ };
2795
+
2796
+ // packages/core/echo/echo-pipeline/src/db-host/space-state-manager.ts
2797
+ var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/space-state-manager.ts";
2798
+ var SpaceStateManager = class extends Resource8 {
2799
+ constructor() {
2800
+ super(...arguments);
2801
+ this._roots = /* @__PURE__ */ new Map();
2802
+ this._rootBySpace = /* @__PURE__ */ new Map();
2803
+ this._perRootContext = /* @__PURE__ */ new Map();
2804
+ this._lastSpaceDocumentList = /* @__PURE__ */ new Map();
2805
+ this.spaceDocumentListUpdated = new Event3();
2806
+ }
2807
+ async _close(ctx) {
2808
+ for (const [_, rootCtx] of this._perRootContext) {
2809
+ await rootCtx.dispose();
2810
+ }
2811
+ this._roots.clear();
2812
+ }
2813
+ get roots() {
2814
+ return this._roots;
2815
+ }
2816
+ getRootByDocumentId(documentId) {
2817
+ return this._roots.get(documentId);
2818
+ }
2819
+ async assignRootToSpace(spaceId, handle) {
2820
+ let root;
2821
+ if (this._roots.has(handle.documentId)) {
2822
+ root = this._roots.get(handle.documentId);
2823
+ } else {
2824
+ root = new DatabaseRoot(handle);
2825
+ this._roots.set(handle.documentId, root);
2826
+ }
2827
+ if (this._rootBySpace.get(spaceId) === root.handle.documentId) {
2828
+ return root;
2829
+ }
2830
+ const prevRootId = this._rootBySpace.get(spaceId);
2831
+ if (prevRootId) {
2832
+ void this._perRootContext.get(prevRootId)?.dispose();
2833
+ this._perRootContext.delete(prevRootId);
2834
+ }
2835
+ this._rootBySpace.set(spaceId, root.handle.documentId);
2836
+ const ctx = new Context5(void 0, {
2837
+ F: __dxlog_file14,
2838
+ L: 58
2839
+ });
2840
+ this._perRootContext.set(root.handle.documentId, ctx);
2841
+ await root.handle.whenReady();
2842
+ const documentListCheckScheduler = new UpdateScheduler3(ctx, async () => {
2843
+ const documentIds = [
2844
+ root.documentId,
2845
+ ...root.getAllLinkedDocuments().map((url) => interpretAsDocumentId(url))
2846
+ ];
2847
+ if (!isEqual(documentIds, this._lastSpaceDocumentList.get(spaceId))) {
2848
+ this._lastSpaceDocumentList.set(spaceId, documentIds);
2849
+ this.spaceDocumentListUpdated.emit(new SpaceDocumentListUpdatedEvent(spaceId, documentIds));
2850
+ }
2851
+ }, {
2852
+ maxFrequency: 50
2853
+ });
2854
+ const triggerCheckOnChange = () => documentListCheckScheduler.trigger();
2855
+ root.handle.addListener("change", triggerCheckOnChange);
2856
+ ctx.onDispose(() => root.handle.removeListener("change", triggerCheckOnChange));
2857
+ documentListCheckScheduler.trigger();
2858
+ return root;
2859
+ }
2860
+ };
2861
+ var SpaceDocumentListUpdatedEvent = class {
2862
+ constructor(spaceId, documentIds) {
2863
+ this.spaceId = spaceId;
2864
+ this.documentIds = documentIds;
2865
+ }
2866
+ };
2867
+
2868
+ // packages/core/echo/echo-pipeline/src/db-host/echo-host.ts
2869
+ var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/echo-host.ts";
2870
+ var INDEXER_CONFIG = {
2871
+ enabled: true,
2872
+ indexes: [
2873
+ {
2874
+ kind: IndexKind.Kind.SCHEMA_MATCH
2875
+ }
2876
+ ]
2877
+ };
2878
+ var EchoHost = class extends Resource9 {
2879
+ constructor({ kv }) {
2880
+ super();
2881
+ this._spaceStateManager = new SpaceStateManager();
2882
+ this._indexMetadataStore = new IndexMetadataStore({
2883
+ db: kv.sublevel("index-metadata")
2884
+ });
2885
+ this._echoDataMonitor = new EchoDataMonitor();
2886
+ this._automergeHost = new AutomergeHost({
2887
+ db: kv,
2888
+ dataMonitor: this._echoDataMonitor,
2889
+ indexMetadataStore: this._indexMetadataStore
2890
+ });
2891
+ this._indexer = new Indexer({
2892
+ db: kv,
2893
+ indexStore: new IndexStore({
2894
+ db: kv.sublevel("index-storage")
2895
+ }),
2896
+ metadataStore: this._indexMetadataStore,
2897
+ loadDocuments: createSelectedDocumentsIterator(this._automergeHost),
2898
+ indexCooldownTime: process.env.NODE_ENV === "test" ? 0 : void 0
2899
+ });
2900
+ this._indexer.setConfig(INDEXER_CONFIG);
2901
+ this._queryService = new QueryServiceImpl({
2902
+ automergeHost: this._automergeHost,
2903
+ indexer: this._indexer
2904
+ });
2905
+ this._dataService = new DataServiceImpl({
2906
+ automergeHost: this._automergeHost,
2907
+ updateIndexes: async () => {
2908
+ await this._indexer.updateIndexes();
2909
+ }
2910
+ });
2911
+ trace5.diagnostic({
2912
+ id: "echo-stats",
2913
+ name: "Echo Stats",
2914
+ fetch: async () => {
2915
+ return {
2916
+ dataStats: this._echoDataMonitor.computeStats(),
2917
+ loadedDocsCount: this._automergeHost.loadedDocsCount
2918
+ };
2919
+ }
2920
+ });
2921
+ trace5.diagnostic({
2922
+ id: "database-roots",
2923
+ name: "Database Roots",
2924
+ fetch: async () => {
2925
+ return Array.from(this._spaceStateManager.roots.values()).map((root) => ({
2926
+ url: root.url,
2927
+ isLoaded: root.isLoaded,
2928
+ spaceKey: root.getSpaceKey(),
2929
+ inlineObjects: root.getInlineObjectCount(),
2930
+ linkedObjects: root.getLinkedObjectCount()
2931
+ }));
2932
+ }
2933
+ });
2934
+ trace5.diagnostic({
2935
+ id: "database-root-metrics",
2936
+ name: "Database Roots (with metrics)",
2937
+ fetch: async () => {
2938
+ return Array.from(this._spaceStateManager.roots.values()).map((root) => ({
2939
+ url: root.url,
2940
+ isLoaded: root.isLoaded,
2941
+ spaceKey: root.getSpaceKey(),
2942
+ inlineObjects: root.getInlineObjectCount(),
2943
+ linkedObjects: root.getLinkedObjectCount(),
2944
+ ...root.measureMetrics() ?? {}
2945
+ }));
2946
+ }
2947
+ });
2948
+ }
2949
+ get queryService() {
2950
+ return this._queryService;
2951
+ }
2952
+ get dataService() {
2953
+ return this._dataService;
2954
+ }
2955
+ /**
2956
+ * @deprecated To be abstracted away.
2957
+ */
2958
+ get automergeRepo() {
2959
+ return this._automergeHost.repo;
2960
+ }
2961
+ get roots() {
2962
+ return this._spaceStateManager.roots;
2963
+ }
2964
+ async _open(ctx) {
2965
+ await this._automergeHost.open();
2966
+ await this._indexer.open(ctx);
2967
+ await this._queryService.open(ctx);
2968
+ await this._spaceStateManager.open(ctx);
2969
+ this._spaceStateManager.spaceDocumentListUpdated.on(this._ctx, (e) => {
2970
+ void this._automergeHost.updateLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId), e.documentIds);
2971
+ });
2972
+ }
2973
+ async _close(ctx) {
2974
+ await this._spaceStateManager.close();
2975
+ await this._queryService.close(ctx);
2976
+ await this._indexer.close(ctx);
2977
+ await this._automergeHost.close();
2978
+ }
2979
+ /**
2980
+ * Flush all pending writes to the underlying storage.
2981
+ */
2982
+ async flush() {
2983
+ await this._automergeHost.repo.flush();
2984
+ }
2985
+ /**
2986
+ * Perform any pending index updates.
2987
+ */
2988
+ async updateIndexes() {
2989
+ await this._indexer.updateIndexes();
2990
+ }
2991
+ /**
2992
+ * Loads the document handle from the repo and waits for it to be ready.
2993
+ */
2994
+ async loadDoc(ctx, documentId, opts) {
2995
+ return await this._automergeHost.loadDoc(ctx, documentId, opts);
2996
+ }
2997
+ /**
2998
+ * Create new persisted document.
2999
+ */
3000
+ createDoc(initialValue, opts) {
3001
+ return this._automergeHost.createDoc(initialValue, opts);
3002
+ }
3003
+ /**
3004
+ * Create new space root.
3005
+ */
3006
+ async createSpaceRoot(spaceKey) {
3007
+ invariant11(this._lifecycleState === LifecycleState4.OPEN, void 0, {
3008
+ F: __dxlog_file15,
3009
+ L: 206,
3010
+ S: this,
3011
+ A: [
3012
+ "this._lifecycleState === LifecycleState.OPEN",
3013
+ ""
3014
+ ]
3015
+ });
3016
+ const spaceId = await createIdFromSpaceKey3(spaceKey);
3017
+ const automergeRoot = this._automergeHost.createDoc({
3018
+ version: SpaceDocVersion3.CURRENT,
3019
+ access: {
3020
+ spaceKey: spaceKey.toHex()
3021
+ }
3022
+ });
3023
+ await this._automergeHost.flush({
3024
+ documentIds: [
3025
+ automergeRoot.documentId
3026
+ ]
3027
+ });
3028
+ return await this.openSpaceRoot(spaceId, automergeRoot.url);
3029
+ }
3030
+ // TODO(dmaretskyi): Change to document id.
3031
+ async openSpaceRoot(spaceId, automergeUrl) {
3032
+ invariant11(this._lifecycleState === LifecycleState4.OPEN, void 0, {
3033
+ F: __dxlog_file15,
3034
+ L: 221,
3035
+ S: this,
3036
+ A: [
3037
+ "this._lifecycleState === LifecycleState.OPEN",
3038
+ ""
3039
+ ]
3040
+ });
3041
+ const handle = this._automergeHost.repo.find(automergeUrl);
3042
+ return this._spaceStateManager.assignRootToSpace(spaceId, handle);
3043
+ }
3044
+ // TODO(dmaretskyi): Change to document id.
3045
+ async closeSpaceRoot(automergeUrl) {
3046
+ todo();
3047
+ }
3048
+ /**
3049
+ * Install data replicator.
3050
+ */
3051
+ async addReplicator(replicator) {
3052
+ await this._automergeHost.addReplicator(replicator);
3053
+ }
3054
+ /**
3055
+ * Remove data replicator.
3056
+ */
3057
+ async removeReplicator(replicator) {
3058
+ await this._automergeHost.removeReplicator(replicator);
3059
+ }
3060
+ async getSpaceSyncState(spaceId) {
3061
+ const collectionId = deriveCollectionIdFromSpaceId(spaceId);
3062
+ return this._automergeHost.getCollectionSyncState(collectionId);
3063
+ }
3064
+ };
3065
+
3066
+ // packages/core/echo/echo-pipeline/src/db-host/migration.ts
3067
+ import { convertLegacyReference } from "@dxos/echo-protocol";
3068
+ import { decodeReference, encodeReference, isLegacyReference, LEGACY_TYPE_PROPERTIES, Reference, SpaceDocVersion as SpaceDocVersion4 } from "@dxos/echo-protocol";
3069
+ import { TYPE_PROPERTIES } from "@dxos/echo-schema";
3070
+ import { deepMapValuesAsync } from "@dxos/util";
3071
+ var convertLegacyReferences = async (doc) => {
3072
+ const newDoc = await deepMapValuesAsync(doc, async (value, recurse) => {
3073
+ if (isLegacyReference(value)) {
3074
+ return convertLegacyReference(value);
3075
+ }
3076
+ return recurse(value);
3077
+ });
3078
+ newDoc.version = SpaceDocVersion4.CURRENT;
3079
+ return newDoc;
3080
+ };
3081
+ var convertLegacySpaceRootDoc = async (root) => {
3082
+ const newDoc = await convertLegacyReferences(root);
3083
+ const properties = findInlineObjectOfType(newDoc, LEGACY_TYPE_PROPERTIES);
3084
+ if (properties) {
3085
+ const [_, obj] = properties;
3086
+ obj.system.type = encodeReference(Reference.fromLegacyTypename(TYPE_PROPERTIES));
3087
+ }
3088
+ return newDoc;
3089
+ };
3090
+ var findInlineObjectOfType = (spaceDoc, typename) => {
3091
+ for (const id in spaceDoc.objects ?? {}) {
3092
+ const obj = spaceDoc.objects[id];
3093
+ if (obj.system.type && decodeReference(obj.system.type).objectId === typename) {
3094
+ return [
3095
+ id,
3096
+ obj
3097
+ ];
3098
+ }
3099
+ }
3100
+ return void 0;
3101
+ };
3102
+
3103
+ // packages/core/echo/echo-pipeline/src/edge/echo-edge-replicator.ts
3104
+ import { Mutex, Trigger as Trigger2 } from "@dxos/async";
3105
+ import * as A5 from "@dxos/automerge/automerge";
3106
+ import { cbor as cbor2 } from "@dxos/automerge/automerge-repo";
3107
+ import { Context as Context6, Resource as Resource10 } from "@dxos/context";
3108
+ import { randomUUID } from "@dxos/crypto";
3109
+ import { invariant as invariant12 } from "@dxos/invariant";
3110
+ import { log as log11 } from "@dxos/log";
3111
+ import { EdgeService } from "@dxos/protocols";
3112
+ import { buf } from "@dxos/protocols/buf";
3113
+ import { MessageSchema as RouterMessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
3114
+ import { bufferToArray } from "@dxos/util";
3115
+ function _using_ctx() {
3116
+ var _disposeSuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed) {
3117
+ var err = new Error();
3118
+ err.name = "SuppressedError";
3119
+ err.suppressed = suppressed;
3120
+ err.error = error;
3121
+ return err;
3122
+ }, empty = {}, stack = [];
3123
+ function using(isAwait, value) {
3124
+ if (value != null) {
3125
+ if (Object(value) !== value) {
3126
+ throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
3127
+ }
3128
+ if (isAwait) {
3129
+ var dispose = value[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")];
3130
+ }
3131
+ if (dispose == null) {
3132
+ dispose = value[Symbol.dispose || Symbol.for("Symbol.dispose")];
3133
+ }
3134
+ if (typeof dispose !== "function") {
3135
+ throw new TypeError(`Property [Symbol.dispose] is not a function.`);
3136
+ }
3137
+ stack.push({
3138
+ v: value,
3139
+ d: dispose,
3140
+ a: isAwait
3141
+ });
3142
+ } else if (isAwait) {
3143
+ stack.push({
3144
+ d: value,
3145
+ a: isAwait
3146
+ });
3147
+ }
3148
+ return value;
3149
+ }
3150
+ return {
3151
+ e: empty,
3152
+ u: using.bind(null, false),
3153
+ a: using.bind(null, true),
3154
+ d: function() {
3155
+ var error = this.e;
3156
+ function next() {
3157
+ while (resource = stack.pop()) {
3158
+ try {
3159
+ var resource, disposalResult = resource.d && resource.d.call(resource.v);
3160
+ if (resource.a) {
3161
+ return Promise.resolve(disposalResult).then(next, err);
3162
+ }
3163
+ } catch (e) {
3164
+ return err(e);
3165
+ }
3166
+ }
3167
+ if (error !== empty) throw error;
3168
+ }
3169
+ function err(e) {
3170
+ error = error !== empty ? new _disposeSuppressedError(error, e) : e;
3171
+ return next();
3172
+ }
3173
+ return next();
3174
+ }
3175
+ };
3176
+ }
3177
+ var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/edge/echo-edge-replicator.ts";
3178
+ var EchoEdgeReplicator = class {
3179
+ constructor({ edgeConnection, disableSharePolicy }) {
3180
+ this._mutex = new Mutex();
3181
+ this._ctx = void 0;
3182
+ this._context = null;
3183
+ this._connectedSpaces = /* @__PURE__ */ new Set();
3184
+ this._connections = /* @__PURE__ */ new Map();
3185
+ this._sharePolicyEnabled = true;
3186
+ this._edgeConnection = edgeConnection;
3187
+ this._sharePolicyEnabled = !disableSharePolicy;
3188
+ }
3189
+ async connect(context) {
3190
+ log11.info("connect", {
3191
+ peerId: context.peerId
3192
+ }, {
3193
+ F: __dxlog_file16,
3194
+ L: 53,
3195
+ S: this,
3196
+ C: (f, a) => f(...a)
3197
+ });
3198
+ this._context = context;
3199
+ this._ctx = Context6.default(void 0, {
3200
+ F: __dxlog_file16,
3201
+ L: 56
3202
+ });
3203
+ this._edgeConnection.reconnect.on(this._ctx, async () => {
3204
+ try {
3205
+ var _usingCtx = _using_ctx();
3206
+ const _guard = _usingCtx.u(await this._mutex.acquire());
3207
+ const spaces = [
3208
+ ...this._connectedSpaces
3209
+ ];
3210
+ for (const connection of this._connections.values()) {
3211
+ await connection.close();
3212
+ }
3213
+ this._connections.clear();
3214
+ if (this._context !== null) {
3215
+ for (const spaceId of spaces) {
3216
+ await this._openConnection(spaceId);
3217
+ }
3218
+ }
3219
+ } catch (_) {
3220
+ _usingCtx.e = _;
3221
+ } finally {
3222
+ _usingCtx.d();
3223
+ }
3224
+ });
3225
+ for (const spaceId of this._connectedSpaces) {
3226
+ await this._openConnection(spaceId);
3227
+ }
3228
+ }
3229
+ async disconnect() {
3230
+ try {
3231
+ var _usingCtx = _using_ctx();
3232
+ const _guard = _usingCtx.u(await this._mutex.acquire());
3233
+ for (const connection of this._connections.values()) {
3234
+ await connection.close();
3235
+ }
3236
+ this._connections.clear();
3237
+ } catch (_) {
3238
+ _usingCtx.e = _;
3239
+ } finally {
3240
+ _usingCtx.d();
3241
+ }
3242
+ }
3243
+ async connectToSpace(spaceId) {
3244
+ try {
3245
+ var _usingCtx = _using_ctx();
3246
+ const _guard = _usingCtx.u(await this._mutex.acquire());
3247
+ this._connectedSpaces.add(spaceId);
3248
+ if (this._context !== null) {
3249
+ await this._openConnection(spaceId);
3250
+ }
3251
+ } catch (_) {
3252
+ _usingCtx.e = _;
3253
+ } finally {
3254
+ _usingCtx.d();
3255
+ }
3256
+ }
3257
+ async disconnectFromSpace(spaceId) {
3258
+ try {
3259
+ var _usingCtx = _using_ctx();
3260
+ const _guard = _usingCtx.u(await this._mutex.acquire());
3261
+ this._connectedSpaces.delete(spaceId);
3262
+ const connection = this._connections.get(spaceId);
3263
+ if (connection) {
3264
+ await connection.close();
3265
+ this._connections.delete(spaceId);
3266
+ }
3267
+ } catch (_) {
3268
+ _usingCtx.e = _;
3269
+ } finally {
3270
+ _usingCtx.d();
3271
+ }
3272
+ }
3273
+ async _openConnection(spaceId) {
3274
+ invariant12(this._context, void 0, {
3275
+ F: __dxlog_file16,
3276
+ L: 111,
3277
+ S: this,
3278
+ A: [
3279
+ "this._context",
3280
+ ""
3281
+ ]
3282
+ });
3283
+ const connection = new EdgeReplicatorConnection({
3284
+ edgeConnection: this._edgeConnection,
3285
+ ownPeerId: this._context.peerId,
3286
+ spaceId,
3287
+ context: this._context,
3288
+ sharedPolicyEnabled: this._sharePolicyEnabled,
3289
+ onRemoteConnected: async () => {
3290
+ this._context?.onConnectionOpen(connection);
3291
+ },
3292
+ onRemoteDisconnected: async () => {
3293
+ this._context?.onConnectionClosed(connection);
3294
+ }
3295
+ });
3296
+ this._connections.set(spaceId, connection);
3297
+ await connection.open();
3298
+ }
3299
+ };
3300
+ var EdgeReplicatorConnection = class extends Resource10 {
3301
+ constructor({ edgeConnection, ownPeerId, spaceId, context, sharedPolicyEnabled, onRemoteConnected, onRemoteDisconnected }) {
3302
+ super();
3303
+ this._remotePeerId = null;
3304
+ this._streamStarted = new Trigger2();
3305
+ this._edgeConnection = edgeConnection;
3306
+ this._ownPeerId = ownPeerId;
3307
+ this._spaceId = spaceId;
3308
+ this._context = context;
3309
+ this._remotePeerId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}-${randomUUID()}`;
3310
+ this._targetServiceId = `${EdgeService.AUTOMERGE_REPLICATOR}:${spaceId}`;
3311
+ this._sharedPolicyEnabled = sharedPolicyEnabled;
3312
+ this._onRemoteConnected = onRemoteConnected;
3313
+ this._onRemoteDisconnected = onRemoteDisconnected;
3314
+ this.readable = new ReadableStream({
3315
+ start: (controller) => {
3316
+ this._readableStreamController = controller;
3317
+ this._ctx.onDispose(() => controller.close());
3318
+ this._streamStarted.wake();
3319
+ }
3320
+ });
3321
+ this.writable = new WritableStream({
3322
+ write: async (message, controller) => {
3323
+ await this._sendMessage(message);
3324
+ }
3325
+ });
3326
+ }
3327
+ async _open(ctx) {
3328
+ this._ctx.onDispose(this._edgeConnection.addListener((msg) => {
3329
+ this._onMessage(msg);
3330
+ }));
3331
+ await this._onRemoteConnected();
3332
+ }
3333
+ async _close() {
3334
+ await this._onRemoteDisconnected();
3335
+ }
3336
+ get peerId() {
3337
+ invariant12(this._remotePeerId, "Not connected", {
3338
+ F: __dxlog_file16,
3339
+ L: 214,
3340
+ S: this,
3341
+ A: [
3342
+ "this._remotePeerId",
3343
+ "'Not connected'"
3344
+ ]
3345
+ });
3346
+ return this._remotePeerId;
3347
+ }
3348
+ async shouldAdvertise(params) {
3349
+ if (!this._sharedPolicyEnabled) {
3350
+ return true;
3351
+ }
3352
+ const spaceId = await this._context.getContainingSpaceIdForDocument(params.documentId);
3353
+ if (!spaceId) {
3354
+ return true;
3355
+ }
3356
+ return spaceId === this._spaceId;
3357
+ }
3358
+ shouldSyncCollection(params) {
3359
+ if (!this._sharedPolicyEnabled) {
3360
+ return true;
3361
+ }
3362
+ const spaceId = getSpaceIdFromCollectionId(params.collectionId);
3363
+ return spaceId === this._spaceId;
3364
+ }
3365
+ _onMessage(message) {
3366
+ if (message.serviceId !== this._targetServiceId) {
3367
+ return;
3368
+ }
3369
+ const payload = cbor2.decode(message.payload.value);
3370
+ log11("recv", () => {
3371
+ const decodedData = payload.type === "sync" && payload.data ? A5.decodeSyncMessage(payload.data) : payload.type === "collection-state" ? payload.state : payload;
3372
+ return {
3373
+ from: message.serviceId,
3374
+ type: payload.type,
3375
+ decodedData
3376
+ };
3377
+ }, {
3378
+ F: __dxlog_file16,
3379
+ L: 245,
3380
+ S: this,
3381
+ C: (f, a) => f(...a)
3382
+ });
3383
+ payload.senderId = this._remotePeerId;
3384
+ this._processMessage(payload);
3385
+ }
3386
+ _processMessage(message) {
3387
+ this._readableStreamController.enqueue(message);
3388
+ }
3389
+ async _sendMessage(message) {
3390
+ message.targetId = this._targetServiceId;
3391
+ log11("send", {
3392
+ type: message.type,
3393
+ senderId: message.senderId,
3394
+ targetId: message.targetId,
3395
+ documentId: message.documentId
3396
+ }, {
3397
+ F: __dxlog_file16,
3398
+ L: 267,
3399
+ S: this,
3400
+ C: (f, a) => f(...a)
3401
+ });
3402
+ const encoded = cbor2.encode(message);
3403
+ await this._edgeConnection.send(buf.create(RouterMessageSchema, {
3404
+ serviceId: this._targetServiceId,
3405
+ source: {
3406
+ identityKey: this._edgeConnection.identityKey,
3407
+ peerKey: this._edgeConnection.peerKey
3408
+ },
3409
+ payload: {
3410
+ value: bufferToArray(encoded)
3411
+ }
3412
+ }));
3413
+ }
3414
+ };
39
3415
  export {
40
3416
  AuthExtension,
41
3417
  AuthStatus,
@@ -43,25 +3419,33 @@ export {
43
3419
  CredentialRetrieverExtension,
44
3420
  CredentialServerExtension,
45
3421
  DataServiceImpl,
3422
+ DatabaseRoot,
46
3423
  DocumentsSynchronizer,
47
3424
  EchoDataMonitor,
3425
+ EchoEdgeReplicator,
3426
+ EchoHost,
48
3427
  LevelDBStorageAdapter,
49
3428
  MOCK_AUTH_PROVIDER,
50
3429
  MOCK_AUTH_VERIFIER,
51
3430
  MeshEchoReplicator,
52
3431
  MetadataStore,
53
3432
  Pipeline,
3433
+ QueryServiceImpl,
3434
+ QueryState,
54
3435
  Space,
55
3436
  SpaceManager,
56
3437
  SpaceProtocol,
57
3438
  SpaceProtocolSession,
58
3439
  TimeframeClock,
59
3440
  codec,
3441
+ convertLegacyReferences,
3442
+ convertLegacySpaceRootDoc,
60
3443
  createIdFromSpaceKey,
61
3444
  createMappedFeedWriter,
62
3445
  deriveCollectionIdFromSpaceId,
63
3446
  diffCollectionState,
64
3447
  encodingOptions,
3448
+ findInlineObjectOfType,
65
3449
  getSpaceIdFromCollectionId,
66
3450
  getSpaceKeyFromDoc,
67
3451
  hasInvitationExpired,