@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,2152 +0,0 @@
1
- import "@dxos/node-std/globals";
2
- import {
3
- Buffer,
4
- createIdFromSpaceKey
5
- } from "./chunk-XPCF2V5U.mjs";
6
-
7
- // packages/core/echo/echo-pipeline/src/db-host/documents-synchronizer.ts
8
- import { UpdateScheduler } from "@dxos/async";
9
- import { next as A } from "@dxos/automerge/automerge";
10
- import { Resource } from "@dxos/context";
11
- import { invariant } from "@dxos/invariant";
12
- import { log } from "@dxos/log";
13
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/documents-synchronizer.ts";
14
- var MAX_UPDATE_FREQ = 10;
15
- var DocumentsSynchronizer = class extends Resource {
16
- constructor(_params) {
17
- super();
18
- this._params = _params;
19
- this._syncStates = /* @__PURE__ */ new Map();
20
- this._pendingUpdates = /* @__PURE__ */ new Set();
21
- this._sendUpdatesJob = void 0;
22
- }
23
- addDocuments(documentIds, retryCounter = 0) {
24
- if (retryCounter > 3) {
25
- log.warn("Failed to load document, retry limit reached", {
26
- documentIds
27
- }, {
28
- F: __dxlog_file,
29
- L: 49,
30
- S: this,
31
- C: (f, a) => f(...a)
32
- });
33
- return;
34
- }
35
- for (const documentId of documentIds) {
36
- const doc = this._params.repo.find(documentId);
37
- doc.whenReady().then(() => {
38
- this._startSync(doc);
39
- this._pendingUpdates.add(doc.documentId);
40
- this._sendUpdatesJob.trigger();
41
- }).catch((error) => {
42
- log.warn("Failed to load document, wraparound", {
43
- documentId,
44
- error
45
- }, {
46
- F: __dxlog_file,
47
- L: 63,
48
- S: this,
49
- C: (f, a) => f(...a)
50
- });
51
- this.addDocuments([
52
- documentId
53
- ], retryCounter + 1);
54
- });
55
- }
56
- }
57
- removeDocuments(documentIds) {
58
- for (const documentId of documentIds) {
59
- this._syncStates.get(documentId)?.clearSubscriptions?.();
60
- this._syncStates.delete(documentId);
61
- this._pendingUpdates.delete(documentId);
62
- }
63
- }
64
- async _open() {
65
- this._sendUpdatesJob = new UpdateScheduler(this._ctx, this._checkAndSendUpdates.bind(this), {
66
- maxFrequency: MAX_UPDATE_FREQ
67
- });
68
- }
69
- async _close() {
70
- await this._sendUpdatesJob.join();
71
- this._syncStates.clear();
72
- }
73
- update(updates) {
74
- for (const { documentId, mutation, isNew } of updates) {
75
- if (isNew) {
76
- const doc = this._params.repo.find(documentId);
77
- doc.update((doc2) => A.loadIncremental(doc2, mutation));
78
- this._startSync(doc);
79
- } else {
80
- this._writeMutation(documentId, mutation);
81
- }
82
- }
83
- }
84
- _startSync(doc) {
85
- if (this._syncStates.has(doc.documentId)) {
86
- log.info("Document already being synced", {
87
- documentId: doc.documentId
88
- }, {
89
- F: __dxlog_file,
90
- L: 102,
91
- S: this,
92
- C: (f, a) => f(...a)
93
- });
94
- return;
95
- }
96
- const syncState = {
97
- handle: doc
98
- };
99
- this._subscribeForChanges(syncState);
100
- this._syncStates.set(doc.documentId, syncState);
101
- }
102
- _subscribeForChanges(syncState) {
103
- const handler = () => {
104
- this._pendingUpdates.add(syncState.handle.documentId);
105
- this._sendUpdatesJob.trigger();
106
- };
107
- syncState.handle.on("heads-changed", handler);
108
- syncState.clearSubscriptions = () => syncState.handle.off("heads-changed", handler);
109
- }
110
- async _checkAndSendUpdates() {
111
- const updates = [];
112
- const docsWithPendingUpdates = Array.from(this._pendingUpdates);
113
- this._pendingUpdates.clear();
114
- for (const documentId of docsWithPendingUpdates) {
115
- const update = this._getPendingChanges(documentId);
116
- if (update) {
117
- updates.push({
118
- documentId,
119
- mutation: update
120
- });
121
- }
122
- }
123
- if (updates.length > 0) {
124
- this._params.sendUpdates({
125
- updates
126
- });
127
- }
128
- }
129
- _getPendingChanges(documentId) {
130
- const syncState = this._syncStates.get(documentId);
131
- invariant(syncState, "Sync state for document not found", {
132
- F: __dxlog_file,
133
- L: 143,
134
- S: this,
135
- A: [
136
- "syncState",
137
- "'Sync state for document not found'"
138
- ]
139
- });
140
- const doc = syncState.handle.docSync();
141
- if (!doc) {
142
- return;
143
- }
144
- const mutation = syncState.lastSentHead ? A.saveSince(doc, syncState.lastSentHead) : A.save(doc);
145
- if (mutation.length === 0) {
146
- return;
147
- }
148
- syncState.lastSentHead = A.getHeads(doc);
149
- return mutation;
150
- }
151
- _writeMutation(documentId, mutation) {
152
- const syncState = this._syncStates.get(documentId);
153
- invariant(syncState, "Sync state for document not found", {
154
- F: __dxlog_file,
155
- L: 158,
156
- S: this,
157
- A: [
158
- "syncState",
159
- "'Sync state for document not found'"
160
- ]
161
- });
162
- syncState.handle.update((doc) => {
163
- const headsBefore = A.getHeads(doc);
164
- const newDoc = A.loadIncremental(doc, mutation);
165
- if (A.equals(headsBefore, syncState.lastSentHead)) {
166
- syncState.lastSentHead = A.getHeads(newDoc);
167
- }
168
- return newDoc;
169
- });
170
- }
171
- };
172
-
173
- // packages/core/echo/echo-pipeline/src/automerge/collection-synchronizer.ts
174
- import { asyncReturn, Event, scheduleTask, scheduleTaskInterval } from "@dxos/async";
175
- import { next as am } from "@dxos/automerge/automerge";
176
- import { Resource as Resource2 } from "@dxos/context";
177
- import { defaultMap } from "@dxos/util";
178
- var MIN_QUERY_INTERVAL = 5e3;
179
- var POLL_INTERVAL = 3e4;
180
- var CollectionSynchronizer = class extends Resource2 {
181
- constructor(params) {
182
- super();
183
- /**
184
- * CollectionId -> State.
185
- */
186
- this._perCollectionStates = /* @__PURE__ */ new Map();
187
- this._connectedPeers = /* @__PURE__ */ new Set();
188
- this.remoteStateUpdated = new Event();
189
- this._sendCollectionState = params.sendCollectionState;
190
- this._queryCollectionState = params.queryCollectionState;
191
- this._shouldSyncCollection = params.shouldSyncCollection;
192
- }
193
- async _open(ctx) {
194
- scheduleTaskInterval(this._ctx, async () => {
195
- for (const collectionId of this._perCollectionStates.keys()) {
196
- this.refreshCollection(collectionId);
197
- await asyncReturn();
198
- }
199
- }, POLL_INTERVAL);
200
- }
201
- getRegisteredCollectionIds() {
202
- return [
203
- ...this._perCollectionStates.keys()
204
- ];
205
- }
206
- getLocalCollectionState(collectionId) {
207
- return this._getPerCollectionState(collectionId).localState;
208
- }
209
- setLocalCollectionState(collectionId, state) {
210
- this._getPerCollectionState(collectionId).localState = state;
211
- queueMicrotask(async () => {
212
- if (!this._ctx.disposed) {
213
- this._refreshInterestedPeers(collectionId);
214
- this.refreshCollection(collectionId);
215
- }
216
- });
217
- }
218
- getRemoteCollectionStates(collectionId) {
219
- return this._getPerCollectionState(collectionId).remoteStates;
220
- }
221
- refreshCollection(collectionId) {
222
- let scheduleAnotherRefresh = false;
223
- const state = this._getPerCollectionState(collectionId);
224
- for (const peerId of this._connectedPeers) {
225
- if (state.interestedPeers.has(peerId)) {
226
- const lastQueried = state.lastQueried.get(peerId) ?? 0;
227
- if (Date.now() - lastQueried > MIN_QUERY_INTERVAL) {
228
- state.lastQueried.set(peerId, Date.now());
229
- this._queryCollectionState(collectionId, peerId);
230
- } else {
231
- scheduleAnotherRefresh = true;
232
- }
233
- }
234
- }
235
- if (scheduleAnotherRefresh) {
236
- scheduleTask(this._ctx, () => this.refreshCollection(collectionId), MIN_QUERY_INTERVAL);
237
- }
238
- }
239
- /**
240
- * Callback when a connection to a peer is established.
241
- */
242
- onConnectionOpen(peerId) {
243
- this._connectedPeers.add(peerId);
244
- queueMicrotask(async () => {
245
- if (this._ctx.disposed) {
246
- return;
247
- }
248
- for (const [collectionId, state] of this._perCollectionStates.entries()) {
249
- if (this._shouldSyncCollection(collectionId, peerId)) {
250
- state.interestedPeers.add(peerId);
251
- state.lastQueried.set(peerId, Date.now());
252
- this._queryCollectionState(collectionId, peerId);
253
- }
254
- }
255
- });
256
- }
257
- /**
258
- * Callback when a connection to a peer is closed.
259
- */
260
- onConnectionClosed(peerId) {
261
- this._connectedPeers.delete(peerId);
262
- for (const perCollectionState of this._perCollectionStates.values()) {
263
- perCollectionState.remoteStates.delete(peerId);
264
- }
265
- }
266
- /**
267
- * Callback when a peer queries the state of a collection.
268
- */
269
- onCollectionStateQueried(collectionId, peerId) {
270
- const perCollectionState = this._getPerCollectionState(collectionId);
271
- if (perCollectionState.localState) {
272
- this._sendCollectionState(collectionId, peerId, perCollectionState.localState);
273
- }
274
- }
275
- /**
276
- * Callback when a peer sends the state of a collection.
277
- */
278
- onRemoteStateReceived(collectionId, peerId, state) {
279
- validateCollectionState(state);
280
- const perCollectionState = this._getPerCollectionState(collectionId);
281
- perCollectionState.remoteStates.set(peerId, state);
282
- this.remoteStateUpdated.emit({
283
- peerId,
284
- collectionId
285
- });
286
- }
287
- _getPerCollectionState(collectionId) {
288
- return defaultMap(this._perCollectionStates, collectionId, () => ({
289
- localState: void 0,
290
- remoteStates: /* @__PURE__ */ new Map(),
291
- interestedPeers: /* @__PURE__ */ new Set(),
292
- lastQueried: /* @__PURE__ */ new Map()
293
- }));
294
- }
295
- _refreshInterestedPeers(collectionId) {
296
- for (const peerId of this._connectedPeers) {
297
- if (this._shouldSyncCollection(collectionId, peerId)) {
298
- this._getPerCollectionState(collectionId).interestedPeers.add(peerId);
299
- } else {
300
- this._getPerCollectionState(collectionId).interestedPeers.delete(peerId);
301
- }
302
- }
303
- }
304
- };
305
- var diffCollectionState = (local, remote) => {
306
- const allDocuments = /* @__PURE__ */ new Set([
307
- ...Object.keys(local.documents),
308
- ...Object.keys(remote.documents)
309
- ]);
310
- const different = [];
311
- for (const documentId of allDocuments) {
312
- if (!local.documents[documentId] || !remote.documents[documentId] || !am.equals(local.documents[documentId], remote.documents[documentId])) {
313
- different.push(documentId);
314
- }
315
- }
316
- return {
317
- different
318
- };
319
- };
320
- var validateCollectionState = (state) => {
321
- Object.entries(state.documents).forEach(([documentId, heads]) => {
322
- if (!isValidDocumentId(documentId)) {
323
- throw new Error(`Invalid documentId: ${documentId}`);
324
- }
325
- if (Array.isArray(heads) && heads.some((head) => typeof head !== "string")) {
326
- throw new Error(`Invalid heads: ${heads}`);
327
- }
328
- });
329
- };
330
- var isValidDocumentId = (documentId) => {
331
- return typeof documentId === "string" && !documentId.includes(":");
332
- };
333
-
334
- // packages/core/echo/echo-pipeline/src/automerge/leveldb-storage-adapter.ts
335
- import { LifecycleState, Resource as Resource3 } from "@dxos/context";
336
- var LevelDBStorageAdapter = class extends Resource3 {
337
- constructor(_params) {
338
- super();
339
- this._params = _params;
340
- }
341
- async load(keyArray) {
342
- try {
343
- if (this._lifecycleState !== LifecycleState.OPEN) {
344
- return void 0;
345
- }
346
- const startMs = Date.now();
347
- const chunk = await this._params.db.get(keyArray, {
348
- ...encodingOptions
349
- });
350
- this._params.monitor?.recordBytesLoaded(chunk.byteLength);
351
- this._params.monitor?.recordLoadDuration(Date.now() - startMs);
352
- return chunk;
353
- } catch (err) {
354
- if (isLevelDbNotFoundError(err)) {
355
- return void 0;
356
- }
357
- throw err;
358
- }
359
- }
360
- async save(keyArray, binary) {
361
- if (this._lifecycleState !== LifecycleState.OPEN) {
362
- return void 0;
363
- }
364
- const startMs = Date.now();
365
- const batch = this._params.db.batch();
366
- await this._params.callbacks?.beforeSave?.({
367
- path: keyArray,
368
- batch
369
- });
370
- batch.put(keyArray, Buffer.from(binary), {
371
- ...encodingOptions
372
- });
373
- await batch.write();
374
- this._params.monitor?.recordBytesStored(binary.byteLength);
375
- await this._params.callbacks?.afterSave?.(keyArray);
376
- this._params.monitor?.recordStoreDuration(Date.now() - startMs);
377
- }
378
- async remove(keyArray) {
379
- if (this._lifecycleState !== LifecycleState.OPEN) {
380
- return void 0;
381
- }
382
- await this._params.db.del(keyArray, {
383
- ...encodingOptions
384
- });
385
- }
386
- async loadRange(keyPrefix) {
387
- if (this._lifecycleState !== LifecycleState.OPEN) {
388
- return [];
389
- }
390
- const startMs = Date.now();
391
- const result = [];
392
- for await (const [key, value] of this._params.db.iterator({
393
- gte: keyPrefix,
394
- lte: [
395
- ...keyPrefix,
396
- "\uFFFF"
397
- ],
398
- ...encodingOptions
399
- })) {
400
- result.push({
401
- key,
402
- data: value
403
- });
404
- this._params.monitor?.recordBytesLoaded(value.byteLength);
405
- }
406
- this._params.monitor?.recordLoadDuration(Date.now() - startMs);
407
- return result;
408
- }
409
- async removeRange(keyPrefix) {
410
- if (this._lifecycleState !== LifecycleState.OPEN) {
411
- return void 0;
412
- }
413
- const batch = this._params.db.batch();
414
- for await (const [key] of this._params.db.iterator({
415
- gte: keyPrefix,
416
- lte: [
417
- ...keyPrefix,
418
- "\uFFFF"
419
- ],
420
- ...encodingOptions
421
- })) {
422
- batch.del(key, {
423
- ...encodingOptions
424
- });
425
- }
426
- await batch.write();
427
- }
428
- };
429
- var keyEncoder = {
430
- encode: (key) => Buffer.from(key.map((k) => k.replaceAll("%", "%25").replaceAll("-", "%2D")).join("-")),
431
- decode: (key) => Buffer.from(key).toString().split("-").map((k) => k.replaceAll("%2D", "-").replaceAll("%25", "%")),
432
- format: "buffer"
433
- };
434
- var encodingOptions = {
435
- keyEncoding: keyEncoder,
436
- valueEncoding: "buffer"
437
- };
438
- var isLevelDbNotFoundError = (err) => err.code === "LEVEL_NOT_FOUND";
439
-
440
- // packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts
441
- import { Event as Event2, asyncTimeout } from "@dxos/async";
442
- import { getBackend, getHeads, isAutomerge, equals as headsEquals, save } from "@dxos/automerge/automerge";
443
- import { Repo } from "@dxos/automerge/automerge-repo";
444
- import { Context, Resource as Resource4, cancelWithContext } from "@dxos/context";
445
- import { invariant as invariant3 } from "@dxos/invariant";
446
- import { PublicKey } from "@dxos/keys";
447
- import { log as log3 } from "@dxos/log";
448
- import { objectPointerCodec } from "@dxos/protocols";
449
- import { trace } from "@dxos/tracing";
450
-
451
- // packages/core/echo/echo-pipeline/src/automerge/echo-network-adapter.ts
452
- import { synchronized, Trigger } from "@dxos/async";
453
- import { NetworkAdapter } from "@dxos/automerge/automerge-repo";
454
- import { LifecycleState as LifecycleState2 } from "@dxos/context";
455
- import { invariant as invariant2 } from "@dxos/invariant";
456
- import { log as log2 } from "@dxos/log";
457
- import { nonNullable } from "@dxos/util";
458
-
459
- // packages/core/echo/echo-pipeline/src/automerge/network-protocol.ts
460
- import { MESSAGE_TYPE_COLLECTION_QUERY, MESSAGE_TYPE_COLLECTION_STATE } from "@dxos/protocols";
461
- var isCollectionQueryMessage = (message) => message.type === MESSAGE_TYPE_COLLECTION_QUERY;
462
- var isCollectionStateMessage = (message) => message.type === MESSAGE_TYPE_COLLECTION_STATE;
463
-
464
- // packages/core/echo/echo-pipeline/src/automerge/echo-network-adapter.ts
465
- function _ts_decorate(decorators, target, key, desc) {
466
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
467
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
468
- 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;
469
- return c > 3 && r && Object.defineProperty(target, key, r), r;
470
- }
471
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/echo-network-adapter.ts";
472
- var EchoNetworkAdapter = class extends NetworkAdapter {
473
- constructor(_params) {
474
- super();
475
- this._params = _params;
476
- this._replicators = /* @__PURE__ */ new Set();
477
- this._connections = /* @__PURE__ */ new Map();
478
- this._lifecycleState = LifecycleState2.CLOSED;
479
- this._connected = new Trigger();
480
- }
481
- connect(peerId, peerMetadata) {
482
- this.peerId = peerId;
483
- this.peerMetadata = peerMetadata;
484
- this._connected.wake();
485
- }
486
- send(message) {
487
- this._send(message);
488
- }
489
- disconnect() {
490
- }
491
- async open() {
492
- if (this._lifecycleState === LifecycleState2.OPEN) {
493
- return;
494
- }
495
- this._lifecycleState = LifecycleState2.OPEN;
496
- log2("emit ready", void 0, {
497
- F: __dxlog_file2,
498
- L: 81,
499
- S: this,
500
- C: (f, a) => f(...a)
501
- });
502
- this.emit("ready", {
503
- network: this
504
- });
505
- }
506
- async close() {
507
- if (this._lifecycleState === LifecycleState2.CLOSED) {
508
- return this;
509
- }
510
- for (const replicator of this._replicators) {
511
- await replicator.disconnect();
512
- }
513
- this._replicators.clear();
514
- this._lifecycleState = LifecycleState2.CLOSED;
515
- }
516
- async whenConnected() {
517
- await this._connected.wait({
518
- timeout: 1e4
519
- });
520
- }
521
- async addReplicator(replicator) {
522
- invariant2(this._lifecycleState === LifecycleState2.OPEN, void 0, {
523
- F: __dxlog_file2,
524
- L: 107,
525
- S: this,
526
- A: [
527
- "this._lifecycleState === LifecycleState.OPEN",
528
- ""
529
- ]
530
- });
531
- invariant2(this.peerId, void 0, {
532
- F: __dxlog_file2,
533
- L: 108,
534
- S: this,
535
- A: [
536
- "this.peerId",
537
- ""
538
- ]
539
- });
540
- invariant2(!this._replicators.has(replicator), void 0, {
541
- F: __dxlog_file2,
542
- L: 109,
543
- S: this,
544
- A: [
545
- "!this._replicators.has(replicator)",
546
- ""
547
- ]
548
- });
549
- this._replicators.add(replicator);
550
- await replicator.connect({
551
- peerId: this.peerId,
552
- onConnectionOpen: this._onConnectionOpen.bind(this),
553
- onConnectionClosed: this._onConnectionClosed.bind(this),
554
- onConnectionAuthScopeChanged: this._onConnectionAuthScopeChanged.bind(this),
555
- isDocumentInRemoteCollection: this._params.isDocumentInRemoteCollection,
556
- getContainingSpaceForDocument: this._params.getContainingSpaceForDocument,
557
- getContainingSpaceIdForDocument: async (documentId) => {
558
- const key = await this._params.getContainingSpaceForDocument(documentId);
559
- return key ? createIdFromSpaceKey(key) : null;
560
- }
561
- });
562
- }
563
- async removeReplicator(replicator) {
564
- invariant2(this._lifecycleState === LifecycleState2.OPEN, void 0, {
565
- F: __dxlog_file2,
566
- L: 128,
567
- S: this,
568
- A: [
569
- "this._lifecycleState === LifecycleState.OPEN",
570
- ""
571
- ]
572
- });
573
- invariant2(this._replicators.has(replicator), void 0, {
574
- F: __dxlog_file2,
575
- L: 129,
576
- S: this,
577
- A: [
578
- "this._replicators.has(replicator)",
579
- ""
580
- ]
581
- });
582
- await replicator.disconnect();
583
- this._replicators.delete(replicator);
584
- }
585
- async shouldAdvertise(peerId, params) {
586
- const connection = this._connections.get(peerId);
587
- if (!connection) {
588
- return false;
589
- }
590
- return connection.connection.shouldAdvertise(params);
591
- }
592
- shouldSyncCollection(peerId, params) {
593
- const connection = this._connections.get(peerId);
594
- if (!connection) {
595
- return false;
596
- }
597
- return connection.connection.shouldSyncCollection(params);
598
- }
599
- queryCollectionState(collectionId, targetId) {
600
- const message = {
601
- type: "collection-query",
602
- senderId: this.peerId,
603
- targetId,
604
- collectionId
605
- };
606
- this._send(message);
607
- }
608
- sendCollectionState(collectionId, targetId, state) {
609
- const message = {
610
- type: "collection-state",
611
- senderId: this.peerId,
612
- targetId,
613
- collectionId,
614
- state
615
- };
616
- this._send(message);
617
- }
618
- _send(message) {
619
- const connectionEntry = this._connections.get(message.targetId);
620
- if (!connectionEntry) {
621
- throw new Error("Connection not found.");
622
- }
623
- const writeStart = Date.now();
624
- connectionEntry.writer.write(message).then(() => {
625
- const durationMs = Date.now() - writeStart;
626
- this._params.monitor?.recordMessageSent(message, durationMs);
627
- }).catch((err) => {
628
- if (connectionEntry.isOpen) {
629
- log2.catch(err, void 0, {
630
- F: __dxlog_file2,
631
- L: 189,
632
- S: this,
633
- C: (f, a) => f(...a)
634
- });
635
- }
636
- this._params.monitor?.recordMessageSendingFailed(message);
637
- });
638
- }
639
- // TODO(dmaretskyi): Remove.
640
- getPeersInterestedInCollection(collectionId) {
641
- return Array.from(this._connections.values()).map((connection) => {
642
- return connection.connection.shouldSyncCollection({
643
- collectionId
644
- }) ? connection.connection.peerId : null;
645
- }).filter(nonNullable);
646
- }
647
- _onConnectionOpen(connection) {
648
- log2("Connection opened", {
649
- peerId: connection.peerId
650
- }, {
651
- F: __dxlog_file2,
652
- L: 207,
653
- S: this,
654
- C: (f, a) => f(...a)
655
- });
656
- invariant2(!this._connections.has(connection.peerId), void 0, {
657
- F: __dxlog_file2,
658
- L: 208,
659
- S: this,
660
- A: [
661
- "!this._connections.has(connection.peerId as PeerId)",
662
- ""
663
- ]
664
- });
665
- const reader = connection.readable.getReader();
666
- const writer = connection.writable.getWriter();
667
- const connectionEntry = {
668
- connection,
669
- reader,
670
- writer,
671
- isOpen: true
672
- };
673
- this._connections.set(connection.peerId, connectionEntry);
674
- queueMicrotask(async () => {
675
- try {
676
- while (true) {
677
- const { done, value } = await reader.read();
678
- if (done) {
679
- break;
680
- }
681
- this._onMessage(value);
682
- }
683
- } catch (err) {
684
- if (connectionEntry.isOpen) {
685
- log2.catch(err, void 0, {
686
- F: __dxlog_file2,
687
- L: 227,
688
- S: this,
689
- C: (f, a) => f(...a)
690
- });
691
- }
692
- }
693
- });
694
- log2("emit peer-candidate", {
695
- peerId: connection.peerId
696
- }, {
697
- F: __dxlog_file2,
698
- L: 232,
699
- S: this,
700
- C: (f, a) => f(...a)
701
- });
702
- this._emitPeerCandidate(connection);
703
- this._params.monitor?.recordPeerConnected(connection.peerId);
704
- }
705
- _onMessage(message) {
706
- if (isCollectionQueryMessage(message)) {
707
- this._params.onCollectionStateQueried(message.collectionId, message.senderId);
708
- } else if (isCollectionStateMessage(message)) {
709
- this._params.onCollectionStateReceived(message.collectionId, message.senderId, message.state);
710
- } else {
711
- this.emit("message", message);
712
- }
713
- this._params.monitor?.recordMessageReceived(message);
714
- }
715
- /**
716
- * Trigger doc-synchronizer shared documents set recalculation. Happens on peer-candidate.
717
- * TODO(y): replace with a proper API call when sharePolicy update becomes supported by automerge-repo
718
- */
719
- _onConnectionAuthScopeChanged(connection) {
720
- log2("Connection auth scope changed", {
721
- peerId: connection.peerId
722
- }, {
723
- F: __dxlog_file2,
724
- L: 253,
725
- S: this,
726
- C: (f, a) => f(...a)
727
- });
728
- const entry = this._connections.get(connection.peerId);
729
- invariant2(entry, void 0, {
730
- F: __dxlog_file2,
731
- L: 255,
732
- S: this,
733
- A: [
734
- "entry",
735
- ""
736
- ]
737
- });
738
- this.emit("peer-disconnected", {
739
- peerId: connection.peerId
740
- });
741
- this._emitPeerCandidate(connection);
742
- }
743
- _onConnectionClosed(connection) {
744
- log2("Connection closed", {
745
- peerId: connection.peerId
746
- }, {
747
- F: __dxlog_file2,
748
- L: 261,
749
- S: this,
750
- C: (f, a) => f(...a)
751
- });
752
- const entry = this._connections.get(connection.peerId);
753
- invariant2(entry, void 0, {
754
- F: __dxlog_file2,
755
- L: 263,
756
- S: this,
757
- A: [
758
- "entry",
759
- ""
760
- ]
761
- });
762
- entry.isOpen = false;
763
- this.emit("peer-disconnected", {
764
- peerId: connection.peerId
765
- });
766
- this._params.monitor?.recordPeerDisconnected(connection.peerId);
767
- void entry.reader.cancel().catch((err) => log2.catch(err, void 0, {
768
- F: __dxlog_file2,
769
- L: 269,
770
- S: this,
771
- C: (f, a) => f(...a)
772
- }));
773
- void entry.writer.abort().catch((err) => log2.catch(err, void 0, {
774
- F: __dxlog_file2,
775
- L: 270,
776
- S: this,
777
- C: (f, a) => f(...a)
778
- }));
779
- this._connections.delete(connection.peerId);
780
- }
781
- _emitPeerCandidate(connection) {
782
- this.emit("peer-candidate", {
783
- peerId: connection.peerId,
784
- peerMetadata: createEchoPeerMetadata()
785
- });
786
- }
787
- };
788
- _ts_decorate([
789
- synchronized
790
- ], EchoNetworkAdapter.prototype, "open", null);
791
- _ts_decorate([
792
- synchronized
793
- ], EchoNetworkAdapter.prototype, "close", null);
794
- _ts_decorate([
795
- synchronized
796
- ], EchoNetworkAdapter.prototype, "addReplicator", null);
797
- _ts_decorate([
798
- synchronized
799
- ], EchoNetworkAdapter.prototype, "removeReplicator", null);
800
- var createEchoPeerMetadata = () => ({
801
- // TODO(dmaretskyi): Refactor this.
802
- dxos_peerSource: "EchoNetworkAdapter"
803
- });
804
- var isEchoPeerMetadata = (metadata) => metadata?.dxos_peerSource === "EchoNetworkAdapter";
805
-
806
- // packages/core/echo/echo-pipeline/src/automerge/heads-store.ts
807
- import { headsEncoding } from "@dxos/indexing";
808
- var HeadsStore = class {
809
- constructor({ db }) {
810
- this._db = db;
811
- }
812
- setHeads(documentId, heads, batch) {
813
- batch.put(documentId, heads, {
814
- sublevel: this._db,
815
- keyEncoding: "utf8",
816
- valueEncoding: headsEncoding
817
- });
818
- }
819
- // TODO(dmaretskyi): Make batched.
820
- async getHeads(documentIds) {
821
- return this._db.getMany(documentIds, {
822
- keyEncoding: "utf8",
823
- valueEncoding: headsEncoding
824
- });
825
- }
826
- };
827
-
828
- // packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts
829
- function _ts_decorate2(decorators, target, key, desc) {
830
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
831
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
832
- 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;
833
- return c > 3 && r && Object.defineProperty(target, key, r), r;
834
- }
835
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/automerge-host.ts";
836
- var AutomergeHost = class extends Resource4 {
837
- constructor({ db, indexMetadataStore, dataMonitor }) {
838
- super();
839
- this._collectionSynchronizer = new CollectionSynchronizer({
840
- queryCollectionState: this._queryCollectionState.bind(this),
841
- sendCollectionState: this._sendCollectionState.bind(this),
842
- shouldSyncCollection: this._shouldSyncCollection.bind(this)
843
- });
844
- this._db = db;
845
- this._storage = new LevelDBStorageAdapter({
846
- db: db.sublevel("automerge"),
847
- callbacks: {
848
- beforeSave: async (params) => this._beforeSave(params),
849
- afterSave: async (key) => this._afterSave(key)
850
- },
851
- monitor: dataMonitor
852
- });
853
- this._echoNetworkAdapter = new EchoNetworkAdapter({
854
- getContainingSpaceForDocument: this._getContainingSpaceForDocument.bind(this),
855
- isDocumentInRemoteCollection: this._isDocumentInRemoteCollection.bind(this),
856
- onCollectionStateQueried: this._onCollectionStateQueried.bind(this),
857
- onCollectionStateReceived: this._onCollectionStateReceived.bind(this),
858
- monitor: dataMonitor
859
- });
860
- this._headsStore = new HeadsStore({
861
- db: db.sublevel("heads")
862
- });
863
- this._indexMetadataStore = indexMetadataStore;
864
- }
865
- async _open() {
866
- this._peerId = `host-${PublicKey.random().toHex()}`;
867
- await this._storage.open?.();
868
- this._repo = new Repo({
869
- peerId: this._peerId,
870
- sharePolicy: this._sharePolicy.bind(this),
871
- storage: this._storage,
872
- network: [
873
- // Upstream swarm.
874
- this._echoNetworkAdapter
875
- ]
876
- });
877
- Event2.wrap(this._echoNetworkAdapter, "peer-candidate").on(this._ctx, (e) => this._onPeerConnected(e.peerId));
878
- Event2.wrap(this._echoNetworkAdapter, "peer-disconnected").on(this._ctx, (e) => this._onPeerDisconnected(e.peerId));
879
- this._collectionSynchronizer.remoteStateUpdated.on(this._ctx, ({ collectionId, peerId }) => {
880
- this._onRemoteCollectionStateUpdated(collectionId, peerId);
881
- });
882
- await this._echoNetworkAdapter.open();
883
- await this._collectionSynchronizer.open();
884
- await this._echoNetworkAdapter.open();
885
- await this._echoNetworkAdapter.whenConnected();
886
- }
887
- async _close() {
888
- await this._collectionSynchronizer.close();
889
- await this._storage.close?.();
890
- await this._echoNetworkAdapter.close();
891
- await this._ctx.dispose();
892
- }
893
- /**
894
- * @deprecated To be abstracted away.
895
- */
896
- get repo() {
897
- return this._repo;
898
- }
899
- get peerId() {
900
- return this._peerId;
901
- }
902
- get loadedDocsCount() {
903
- return Object.keys(this._repo.handles).length;
904
- }
905
- async addReplicator(replicator) {
906
- await this._echoNetworkAdapter.addReplicator(replicator);
907
- }
908
- async removeReplicator(replicator) {
909
- await this._echoNetworkAdapter.removeReplicator(replicator);
910
- }
911
- /**
912
- * Loads the document handle from the repo and waits for it to be ready.
913
- */
914
- async loadDoc(ctx, documentId, opts) {
915
- let handle;
916
- if (typeof documentId === "string") {
917
- handle = this._repo.handles[documentId];
918
- }
919
- if (!handle) {
920
- handle = this._repo.find(documentId);
921
- }
922
- if (!handle.isReady()) {
923
- if (!opts?.timeout) {
924
- await cancelWithContext(ctx, handle.whenReady());
925
- } else {
926
- await cancelWithContext(ctx, asyncTimeout(handle.whenReady(), opts.timeout));
927
- }
928
- }
929
- return handle;
930
- }
931
- /**
932
- * Create new persisted document.
933
- */
934
- createDoc(initialValue, opts) {
935
- if (opts?.preserveHistory) {
936
- if (!isAutomerge(initialValue)) {
937
- throw new TypeError("Initial value must be an Automerge document");
938
- }
939
- return this._repo.import(save(initialValue));
940
- } else {
941
- return this._repo.create(initialValue);
942
- }
943
- }
944
- async waitUntilHeadsReplicated(heads) {
945
- const entries = heads.entries;
946
- if (!entries?.length) {
947
- return;
948
- }
949
- const documentIds = entries.map((entry) => entry.documentId);
950
- const documentHeads = await this.getHeads(documentIds);
951
- const headsToWait = entries.filter((entry, index) => {
952
- const targetHeads = entry.heads;
953
- if (!targetHeads || targetHeads.length === 0) {
954
- return false;
955
- }
956
- const currentHeads = documentHeads[index];
957
- return !(currentHeads !== null && headsEquals(currentHeads, targetHeads));
958
- });
959
- if (headsToWait.length > 0) {
960
- await Promise.all(headsToWait.map(async (entry, index) => {
961
- const handle = await this.loadDoc(Context.default(void 0, {
962
- F: __dxlog_file3,
963
- L: 227
964
- }), entry.documentId);
965
- await waitForHeads(handle, entry.heads);
966
- }));
967
- }
968
- await this._repo.flush(documentIds.filter((documentId) => !!this._repo.handles[documentId]));
969
- }
970
- async reIndexHeads(documentIds) {
971
- for (const documentId of documentIds) {
972
- log3.info("re-indexing heads for document", {
973
- documentId
974
- }, {
975
- F: __dxlog_file3,
976
- L: 239,
977
- S: this,
978
- C: (f, a) => f(...a)
979
- });
980
- const handle = this._repo.find(documentId);
981
- await handle.whenReady([
982
- "ready",
983
- "requesting"
984
- ]);
985
- if (handle.inState([
986
- "requesting"
987
- ])) {
988
- log3.warn("document is not available locally, skipping", {
989
- documentId
990
- }, {
991
- F: __dxlog_file3,
992
- L: 243,
993
- S: this,
994
- C: (f, a) => f(...a)
995
- });
996
- continue;
997
- }
998
- const doc = handle.docSync();
999
- invariant3(doc, void 0, {
1000
- F: __dxlog_file3,
1001
- L: 248,
1002
- S: this,
1003
- A: [
1004
- "doc",
1005
- ""
1006
- ]
1007
- });
1008
- const heads = getHeads(doc);
1009
- const batch = this._db.batch();
1010
- this._headsStore.setHeads(documentId, heads, batch);
1011
- await batch.write();
1012
- }
1013
- log3.info("done re-indexing heads", void 0, {
1014
- F: __dxlog_file3,
1015
- L: 255,
1016
- S: this,
1017
- C: (f, a) => f(...a)
1018
- });
1019
- }
1020
- // TODO(dmaretskyi): Share based on HALO permissions and space affinity.
1021
- // Hosts, running in the worker, don't share documents unless requested by other peers.
1022
- // NOTE: If both peers return sharePolicy=false the replication will not happen
1023
- // https://github.com/automerge/automerge-repo/pull/292
1024
- async _sharePolicy(peerId, documentId) {
1025
- if (peerId.startsWith("client-")) {
1026
- return false;
1027
- }
1028
- if (!documentId) {
1029
- return false;
1030
- }
1031
- const peerMetadata = this.repo.peerMetadataByPeerId[peerId];
1032
- if (isEchoPeerMetadata(peerMetadata)) {
1033
- return this._echoNetworkAdapter.shouldAdvertise(peerId, {
1034
- documentId
1035
- });
1036
- }
1037
- return false;
1038
- }
1039
- async _beforeSave({ path, batch }) {
1040
- const handle = this._repo.handles[path[0]];
1041
- if (!handle) {
1042
- return;
1043
- }
1044
- const doc = handle.docSync();
1045
- if (!doc) {
1046
- return;
1047
- }
1048
- const heads = getHeads(doc);
1049
- this._headsStore.setHeads(handle.documentId, heads, batch);
1050
- const spaceKey = getSpaceKeyFromDoc(doc) ?? void 0;
1051
- const objectIds = Object.keys(doc.objects ?? {});
1052
- const encodedIds = objectIds.map((objectId) => objectPointerCodec.encode({
1053
- documentId: handle.documentId,
1054
- objectId,
1055
- spaceKey
1056
- }));
1057
- const idToLastHash = new Map(encodedIds.map((id) => [
1058
- id,
1059
- heads
1060
- ]));
1061
- this._indexMetadataStore.markDirty(idToLastHash, batch);
1062
- }
1063
- _shouldSyncCollection(collectionId, peerId) {
1064
- const peerMetadata = this._repo.peerMetadataByPeerId[peerId];
1065
- if (isEchoPeerMetadata(peerMetadata)) {
1066
- return this._echoNetworkAdapter.shouldSyncCollection(peerId, {
1067
- collectionId
1068
- });
1069
- }
1070
- return false;
1071
- }
1072
- /**
1073
- * Called by AutomergeStorageAdapter after levelDB batch commit.
1074
- */
1075
- async _afterSave(path) {
1076
- this._indexMetadataStore.notifyMarkedDirty();
1077
- const documentId = path[0];
1078
- const document = this._repo.handles[documentId]?.docSync();
1079
- if (document) {
1080
- const heads = getHeads(document);
1081
- this._onHeadsChanged(documentId, heads);
1082
- }
1083
- }
1084
- _automergePeers() {
1085
- return this._repo.peers;
1086
- }
1087
- async _isDocumentInRemoteCollection(params) {
1088
- for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
1089
- const remoteCollections = this._collectionSynchronizer.getRemoteCollectionStates(collectionId);
1090
- const remotePeerDocs = remoteCollections.get(params.peerId)?.documents;
1091
- if (remotePeerDocs && params.documentId in remotePeerDocs) {
1092
- return true;
1093
- }
1094
- }
1095
- return false;
1096
- }
1097
- async _getContainingSpaceForDocument(documentId) {
1098
- const doc = this._repo.handles[documentId]?.docSync();
1099
- if (!doc) {
1100
- return null;
1101
- }
1102
- const spaceKeyHex = getSpaceKeyFromDoc(doc);
1103
- if (!spaceKeyHex) {
1104
- return null;
1105
- }
1106
- return PublicKey.from(spaceKeyHex);
1107
- }
1108
- /**
1109
- * Flush documents to disk.
1110
- */
1111
- async flush({ documentIds } = {}) {
1112
- await this._repo.flush(documentIds);
1113
- }
1114
- async getHeads(documentIds) {
1115
- const result = [];
1116
- const storeRequestIds = [];
1117
- const storeResultIndices = [];
1118
- for (const documentId of documentIds) {
1119
- const doc = this._repo.handles[documentId]?.docSync();
1120
- if (doc) {
1121
- result.push(getHeads(doc));
1122
- } else {
1123
- storeRequestIds.push(documentId);
1124
- storeResultIndices.push(result.length);
1125
- result.push(void 0);
1126
- }
1127
- }
1128
- if (storeRequestIds.length > 0) {
1129
- const storedHeads = await this._headsStore.getHeads(storeRequestIds);
1130
- for (let i = 0; i < storedHeads.length; i++) {
1131
- result[storeResultIndices[i]] = storedHeads[i];
1132
- }
1133
- }
1134
- return result;
1135
- }
1136
- //
1137
- // Collection sync.
1138
- //
1139
- getLocalCollectionState(collectionId) {
1140
- return this._collectionSynchronizer.getLocalCollectionState(collectionId);
1141
- }
1142
- getRemoteCollectionStates(collectionId) {
1143
- return this._collectionSynchronizer.getRemoteCollectionStates(collectionId);
1144
- }
1145
- refreshCollection(collectionId) {
1146
- this._collectionSynchronizer.refreshCollection(collectionId);
1147
- }
1148
- async getCollectionSyncState(collectionId) {
1149
- const result = {
1150
- peers: []
1151
- };
1152
- const localState = this.getLocalCollectionState(collectionId);
1153
- const remoteState = this.getRemoteCollectionStates(collectionId);
1154
- if (!localState) {
1155
- return result;
1156
- }
1157
- for (const [peerId, state] of remoteState) {
1158
- const diff = diffCollectionState(localState, state);
1159
- result.peers.push({
1160
- peerId,
1161
- differentDocuments: diff.different.length
1162
- });
1163
- }
1164
- return result;
1165
- }
1166
- /**
1167
- * Update the local collection state based on the locally stored document heads.
1168
- */
1169
- async updateLocalCollectionState(collectionId, documentIds) {
1170
- const heads = await this.getHeads(documentIds);
1171
- const documents = Object.fromEntries(heads.map((heads2, index) => [
1172
- documentIds[index],
1173
- heads2 ?? []
1174
- ]));
1175
- this._collectionSynchronizer.setLocalCollectionState(collectionId, {
1176
- documents
1177
- });
1178
- }
1179
- _onCollectionStateQueried(collectionId, peerId) {
1180
- this._collectionSynchronizer.onCollectionStateQueried(collectionId, peerId);
1181
- }
1182
- _onCollectionStateReceived(collectionId, peerId, state) {
1183
- this._collectionSynchronizer.onRemoteStateReceived(collectionId, peerId, decodeCollectionState(state));
1184
- }
1185
- _queryCollectionState(collectionId, peerId) {
1186
- this._echoNetworkAdapter.queryCollectionState(collectionId, peerId);
1187
- }
1188
- _sendCollectionState(collectionId, peerId, state) {
1189
- this._echoNetworkAdapter.sendCollectionState(collectionId, peerId, encodeCollectionState(state));
1190
- }
1191
- _onPeerConnected(peerId) {
1192
- this._collectionSynchronizer.onConnectionOpen(peerId);
1193
- }
1194
- _onPeerDisconnected(peerId) {
1195
- this._collectionSynchronizer.onConnectionClosed(peerId);
1196
- }
1197
- _onRemoteCollectionStateUpdated(collectionId, peerId) {
1198
- const localState = this._collectionSynchronizer.getLocalCollectionState(collectionId);
1199
- const remoteState = this._collectionSynchronizer.getRemoteCollectionStates(collectionId).get(peerId);
1200
- if (!localState || !remoteState) {
1201
- return;
1202
- }
1203
- const { different } = diffCollectionState(localState, remoteState);
1204
- if (different.length === 0) {
1205
- return;
1206
- }
1207
- log3.info("replication documents after collection sync", {
1208
- count: different.length
1209
- }, {
1210
- F: __dxlog_file3,
1211
- L: 475,
1212
- S: this,
1213
- C: (f, a) => f(...a)
1214
- });
1215
- for (const documentId of different) {
1216
- this._repo.find(documentId);
1217
- }
1218
- }
1219
- _onHeadsChanged(documentId, heads) {
1220
- for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
1221
- const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);
1222
- if (state?.documents[documentId]) {
1223
- const newState = structuredClone(state);
1224
- newState.documents[documentId] = heads;
1225
- this._collectionSynchronizer.setLocalCollectionState(collectionId, newState);
1226
- }
1227
- }
1228
- }
1229
- };
1230
- _ts_decorate2([
1231
- trace.info()
1232
- ], AutomergeHost.prototype, "_peerId", void 0);
1233
- _ts_decorate2([
1234
- trace.info({
1235
- depth: null
1236
- })
1237
- ], AutomergeHost.prototype, "_automergePeers", null);
1238
- _ts_decorate2([
1239
- trace.span({
1240
- showInBrowserTimeline: true
1241
- })
1242
- ], AutomergeHost.prototype, "flush", null);
1243
- AutomergeHost = _ts_decorate2([
1244
- trace.resource()
1245
- ], AutomergeHost);
1246
- var getSpaceKeyFromDoc = (doc) => {
1247
- const rawSpaceKey = doc.access?.spaceKey ?? doc.experimental_spaceKey;
1248
- if (rawSpaceKey == null) {
1249
- return null;
1250
- }
1251
- return String(rawSpaceKey);
1252
- };
1253
- var waitForHeads = async (handle, heads) => {
1254
- const unavailableHeads = new Set(heads);
1255
- await handle.whenReady();
1256
- await Event2.wrap(handle, "change").waitForCondition(() => {
1257
- for (const changeHash of unavailableHeads.values()) {
1258
- if (changeIsPresentInDoc(handle.docSync(), changeHash)) {
1259
- unavailableHeads.delete(changeHash);
1260
- }
1261
- }
1262
- return unavailableHeads.size === 0;
1263
- });
1264
- };
1265
- var changeIsPresentInDoc = (doc, changeHash) => {
1266
- return !!getBackend(doc).getChangeByHash(changeHash);
1267
- };
1268
- var decodeCollectionState = (state) => {
1269
- invariant3(typeof state === "object" && state !== null, "Invalid state", {
1270
- F: __dxlog_file3,
1271
- L: 528,
1272
- S: void 0,
1273
- A: [
1274
- "typeof state === 'object' && state !== null",
1275
- "'Invalid state'"
1276
- ]
1277
- });
1278
- return state;
1279
- };
1280
- var encodeCollectionState = (state) => {
1281
- return state;
1282
- };
1283
-
1284
- // packages/core/echo/echo-pipeline/src/automerge/space-collection.ts
1285
- import { invariant as invariant4 } from "@dxos/invariant";
1286
- import { SpaceId } from "@dxos/keys";
1287
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/space-collection.ts";
1288
- var deriveCollectionIdFromSpaceId = (spaceId) => `space:${spaceId}`;
1289
- var getSpaceIdFromCollectionId = (collectionId) => {
1290
- const spaceId = collectionId.replace(/^space:/, "");
1291
- invariant4(SpaceId.isValid(spaceId), void 0, {
1292
- F: __dxlog_file4,
1293
- L: 12,
1294
- S: void 0,
1295
- A: [
1296
- "SpaceId.isValid(spaceId)",
1297
- ""
1298
- ]
1299
- });
1300
- return spaceId;
1301
- };
1302
-
1303
- // packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts
1304
- import { invariant as invariant6 } from "@dxos/invariant";
1305
- import { PublicKey as PublicKey2 } from "@dxos/keys";
1306
- import { log as log5 } from "@dxos/log";
1307
- import { ComplexSet, defaultMap as defaultMap2 } from "@dxos/util";
1308
-
1309
- // packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator-connection.ts
1310
- import * as A2 from "@dxos/automerge/automerge";
1311
- import { cbor } from "@dxos/automerge/automerge-repo";
1312
- import { Resource as Resource5 } from "@dxos/context";
1313
- import { invariant as invariant5 } from "@dxos/invariant";
1314
- import { log as log4 } from "@dxos/log";
1315
- import { AutomergeReplicator } from "@dxos/teleport-extension-automerge-replicator";
1316
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator-connection.ts";
1317
- var DEFAULT_FACTORY = (params) => new AutomergeReplicator(...params);
1318
- var MeshReplicatorConnection = class extends Resource5 {
1319
- constructor(_params) {
1320
- super();
1321
- this._params = _params;
1322
- this.remoteDeviceKey = null;
1323
- this._remotePeerId = null;
1324
- this._isEnabled = false;
1325
- let readableStreamController;
1326
- this.readable = new ReadableStream({
1327
- start: (controller) => {
1328
- readableStreamController = controller;
1329
- this._ctx.onDispose(() => controller.close());
1330
- }
1331
- });
1332
- this.writable = new WritableStream({
1333
- write: async (message, controller) => {
1334
- invariant5(this._isEnabled, "Writing to a disabled connection", {
1335
- F: __dxlog_file5,
1336
- L: 49,
1337
- S: this,
1338
- A: [
1339
- "this._isEnabled",
1340
- "'Writing to a disabled connection'"
1341
- ]
1342
- });
1343
- try {
1344
- logSendSync(message);
1345
- await this.replicatorExtension.sendSyncMessage({
1346
- payload: cbor.encode(message)
1347
- });
1348
- } catch (err) {
1349
- controller.error(err);
1350
- this._disconnectIfEnabled();
1351
- }
1352
- }
1353
- });
1354
- const createAutomergeReplicator = this._params.replicatorFactory ?? DEFAULT_FACTORY;
1355
- this.replicatorExtension = createAutomergeReplicator([
1356
- {
1357
- peerId: this._params.ownPeerId
1358
- },
1359
- {
1360
- onStartReplication: async (info, remotePeerId) => {
1361
- this.remoteDeviceKey = remotePeerId;
1362
- this._remotePeerId = info.id;
1363
- log4("onStartReplication", {
1364
- id: info.id,
1365
- thisPeerId: this.peerId,
1366
- remotePeerId: remotePeerId.toHex()
1367
- }, {
1368
- F: __dxlog_file5,
1369
- L: 84,
1370
- S: this,
1371
- C: (f, a) => f(...a)
1372
- });
1373
- this._params.onRemoteConnected();
1374
- },
1375
- onSyncMessage: async ({ payload }) => {
1376
- if (!this._isEnabled) {
1377
- return;
1378
- }
1379
- const message = cbor.decode(payload);
1380
- readableStreamController.enqueue(message);
1381
- },
1382
- onClose: async () => {
1383
- this._disconnectIfEnabled();
1384
- }
1385
- }
1386
- ]);
1387
- }
1388
- _disconnectIfEnabled() {
1389
- if (this._isEnabled) {
1390
- this._params.onRemoteDisconnected();
1391
- }
1392
- }
1393
- get peerId() {
1394
- invariant5(this._remotePeerId != null, "Remote peer has not connected yet.", {
1395
- F: __dxlog_file5,
1396
- L: 110,
1397
- S: this,
1398
- A: [
1399
- "this._remotePeerId != null",
1400
- "'Remote peer has not connected yet.'"
1401
- ]
1402
- });
1403
- return this._remotePeerId;
1404
- }
1405
- async shouldAdvertise(params) {
1406
- return this._params.shouldAdvertise(params);
1407
- }
1408
- shouldSyncCollection(params) {
1409
- return this._params.shouldSyncCollection(params);
1410
- }
1411
- /**
1412
- * Start exchanging messages with the remote peer.
1413
- * Call after the remote peer has connected.
1414
- */
1415
- enable() {
1416
- invariant5(this._remotePeerId != null, "Remote peer has not connected yet.", {
1417
- F: __dxlog_file5,
1418
- L: 127,
1419
- S: this,
1420
- A: [
1421
- "this._remotePeerId != null",
1422
- "'Remote peer has not connected yet.'"
1423
- ]
1424
- });
1425
- this._isEnabled = true;
1426
- }
1427
- /**
1428
- * Stop exchanging messages with the remote peer.
1429
- */
1430
- disable() {
1431
- this._isEnabled = false;
1432
- }
1433
- };
1434
- var logSendSync = (message) => {
1435
- log4("sendSyncMessage", () => {
1436
- const decodedSyncMessage = message.type === "sync" && message.data ? A2.decodeSyncMessage(message.data) : void 0;
1437
- return {
1438
- sync: decodedSyncMessage && {
1439
- headsLength: decodedSyncMessage.heads.length,
1440
- requesting: decodedSyncMessage.need.length > 0,
1441
- sendingChanges: decodedSyncMessage.changes.length > 0
1442
- },
1443
- type: message.type,
1444
- from: message.senderId,
1445
- to: message.targetId
1446
- };
1447
- }, {
1448
- F: __dxlog_file5,
1449
- L: 140,
1450
- S: void 0,
1451
- C: (f, a) => f(...a)
1452
- });
1453
- };
1454
-
1455
- // packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts
1456
- var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/automerge/mesh-echo-replicator.ts";
1457
- var MeshEchoReplicator = class {
1458
- constructor() {
1459
- this._connections = /* @__PURE__ */ new Set();
1460
- /**
1461
- * Using automerge peerId as a key.
1462
- */
1463
- this._connectionsPerPeer = /* @__PURE__ */ new Map();
1464
- /**
1465
- * spaceId -> deviceKey[]
1466
- */
1467
- this._authorizedDevices = /* @__PURE__ */ new Map();
1468
- this._context = null;
1469
- }
1470
- async connect(context) {
1471
- this._context = context;
1472
- }
1473
- async disconnect() {
1474
- for (const connection of this._connectionsPerPeer.values()) {
1475
- this._context?.onConnectionClosed(connection);
1476
- }
1477
- for (const connection of this._connections) {
1478
- await connection.close();
1479
- }
1480
- this._connections.clear();
1481
- this._connectionsPerPeer.clear();
1482
- this._context = null;
1483
- }
1484
- createExtension(extensionFactory) {
1485
- invariant6(this._context, void 0, {
1486
- F: __dxlog_file6,
1487
- L: 56,
1488
- S: this,
1489
- A: [
1490
- "this._context",
1491
- ""
1492
- ]
1493
- });
1494
- const connection = new MeshReplicatorConnection({
1495
- ownPeerId: this._context.peerId,
1496
- replicatorFactory: extensionFactory,
1497
- onRemoteConnected: async () => {
1498
- log5("onRemoteConnected", {
1499
- peerId: connection.peerId
1500
- }, {
1501
- F: __dxlog_file6,
1502
- L: 62,
1503
- S: this,
1504
- C: (f, a) => f(...a)
1505
- });
1506
- invariant6(this._context, void 0, {
1507
- F: __dxlog_file6,
1508
- L: 63,
1509
- S: this,
1510
- A: [
1511
- "this._context",
1512
- ""
1513
- ]
1514
- });
1515
- if (this._connectionsPerPeer.has(connection.peerId)) {
1516
- this._context.onConnectionAuthScopeChanged(connection);
1517
- } else {
1518
- this._connectionsPerPeer.set(connection.peerId, connection);
1519
- this._context.onConnectionOpen(connection);
1520
- connection.enable();
1521
- }
1522
- },
1523
- onRemoteDisconnected: async () => {
1524
- log5("onRemoteDisconnected", {
1525
- peerId: connection.peerId
1526
- }, {
1527
- F: __dxlog_file6,
1528
- L: 74,
1529
- S: this,
1530
- C: (f, a) => f(...a)
1531
- });
1532
- this._context?.onConnectionClosed(connection);
1533
- this._connectionsPerPeer.delete(connection.peerId);
1534
- connection.disable();
1535
- this._connections.delete(connection);
1536
- },
1537
- shouldAdvertise: async (params) => {
1538
- log5("shouldAdvertise", {
1539
- peerId: connection.peerId,
1540
- documentId: params.documentId
1541
- }, {
1542
- F: __dxlog_file6,
1543
- L: 81,
1544
- S: this,
1545
- C: (f, a) => f(...a)
1546
- });
1547
- invariant6(this._context, void 0, {
1548
- F: __dxlog_file6,
1549
- L: 82,
1550
- S: this,
1551
- A: [
1552
- "this._context",
1553
- ""
1554
- ]
1555
- });
1556
- try {
1557
- const spaceKey = await this._context.getContainingSpaceForDocument(params.documentId);
1558
- if (!spaceKey) {
1559
- const remoteDocumentExists = await this._context.isDocumentInRemoteCollection({
1560
- documentId: params.documentId,
1561
- peerId: connection.peerId
1562
- });
1563
- log5("document not found locally for share policy check, accepting the remote document", {
1564
- peerId: connection.peerId,
1565
- documentId: params.documentId,
1566
- remoteDocumentExists
1567
- }, {
1568
- F: __dxlog_file6,
1569
- L: 90,
1570
- S: this,
1571
- C: (f, a) => f(...a)
1572
- });
1573
- return remoteDocumentExists;
1574
- }
1575
- const spaceId = await createIdFromSpaceKey(spaceKey);
1576
- const authorizedDevices = this._authorizedDevices.get(spaceId);
1577
- if (!connection.remoteDeviceKey) {
1578
- log5("device key not found for share policy check", {
1579
- peerId: connection.peerId,
1580
- documentId: params.documentId
1581
- }, {
1582
- F: __dxlog_file6,
1583
- L: 106,
1584
- S: this,
1585
- C: (f, a) => f(...a)
1586
- });
1587
- return false;
1588
- }
1589
- const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false;
1590
- log5("share policy check", {
1591
- localPeer: this._context.peerId,
1592
- remotePeer: connection.peerId,
1593
- documentId: params.documentId,
1594
- deviceKey: connection.remoteDeviceKey,
1595
- spaceKey,
1596
- isAuthorized
1597
- }, {
1598
- F: __dxlog_file6,
1599
- L: 114,
1600
- S: this,
1601
- C: (f, a) => f(...a)
1602
- });
1603
- return isAuthorized;
1604
- } catch (err) {
1605
- log5.catch(err, void 0, {
1606
- F: __dxlog_file6,
1607
- L: 124,
1608
- S: this,
1609
- C: (f, a) => f(...a)
1610
- });
1611
- return false;
1612
- }
1613
- },
1614
- shouldSyncCollection: ({ collectionId }) => {
1615
- const spaceId = getSpaceIdFromCollectionId(collectionId);
1616
- const authorizedDevices = this._authorizedDevices.get(spaceId);
1617
- if (!connection.remoteDeviceKey) {
1618
- log5("device key not found for collection sync check", {
1619
- peerId: connection.peerId,
1620
- collectionId
1621
- }, {
1622
- F: __dxlog_file6,
1623
- L: 134,
1624
- S: this,
1625
- C: (f, a) => f(...a)
1626
- });
1627
- return false;
1628
- }
1629
- const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false;
1630
- return isAuthorized;
1631
- }
1632
- });
1633
- this._connections.add(connection);
1634
- return connection.replicatorExtension;
1635
- }
1636
- async authorizeDevice(spaceKey, deviceKey) {
1637
- log5("authorizeDevice", {
1638
- spaceKey,
1639
- deviceKey
1640
- }, {
1641
- F: __dxlog_file6,
1642
- L: 151,
1643
- S: this,
1644
- C: (f, a) => f(...a)
1645
- });
1646
- const spaceId = await createIdFromSpaceKey(spaceKey);
1647
- defaultMap2(this._authorizedDevices, spaceId, () => new ComplexSet(PublicKey2.hash)).add(deviceKey);
1648
- for (const connection of this._connections) {
1649
- if (connection.remoteDeviceKey && connection.remoteDeviceKey.equals(deviceKey)) {
1650
- if (this._connectionsPerPeer.has(connection.peerId)) {
1651
- this._context?.onConnectionAuthScopeChanged(connection);
1652
- }
1653
- }
1654
- }
1655
- }
1656
- };
1657
-
1658
- // packages/core/echo/echo-pipeline/src/automerge/echo-data-monitor.ts
1659
- import { trace as trace2 } from "@dxos/tracing";
1660
- import { CircularBuffer, mapValues, SlidingWindowSummary } from "@dxos/util";
1661
- function _ts_decorate3(decorators, target, key, desc) {
1662
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1663
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1664
- 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;
1665
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1666
- }
1667
- var PER_SECOND_RATE_AVG_WINDOW_SIZE = 5;
1668
- var DEFAULT_AVG_WINDOW_SIZE = 25;
1669
- var EchoDataMonitor = class {
1670
- constructor(_params = {
1671
- timeSeriesLength: 30
1672
- }) {
1673
- this._params = _params;
1674
- this._lastTick = 0;
1675
- this._activeCounters = createLocalCounters();
1676
- this._localTimeSeries = createLocalTimeSeries();
1677
- this._storageAverages = createStorageAverages();
1678
- this._replicationAverages = createNetworkAverages();
1679
- this._sizeByMessageType = {};
1680
- this._lastReceivedMessages = new CircularBuffer(100);
1681
- this._lastSentMessages = new CircularBuffer(100);
1682
- this._connectionsCount = 0;
1683
- }
1684
- tick(timeMs) {
1685
- this._advanceTimeWindow(timeMs - this._lastTick);
1686
- this._lastTick = timeMs;
1687
- }
1688
- computeStats() {
1689
- return {
1690
- meta: {
1691
- rateAverageOverSeconds: PER_SECOND_RATE_AVG_WINDOW_SIZE
1692
- },
1693
- storage: {
1694
- reads: {
1695
- payloadSize: this._storageAverages.loadedChunkSize.average(),
1696
- opDuration: this._storageAverages.loadDuration.average(),
1697
- countPerSecond: this._storageAverages.loadsPerSecond.average()
1698
- },
1699
- writes: {
1700
- payloadSize: this._storageAverages.storedChunkSize.average(),
1701
- opDuration: this._storageAverages.storeDuration.average(),
1702
- countPerSecond: this._storageAverages.storesPerSecond.average()
1703
- }
1704
- },
1705
- replicator: {
1706
- connections: this._connectionsCount,
1707
- receivedMessages: {
1708
- payloadSize: this._replicationAverages.receivedMessageSize.average(),
1709
- countPerSecond: this._replicationAverages.receivedPerSecond.average()
1710
- },
1711
- sentMessages: {
1712
- payloadSize: this._replicationAverages.sentMessageSize.average(),
1713
- opDuration: this._replicationAverages.sendDuration.average(),
1714
- countPerSecond: this._replicationAverages.sentPerSecond.average(),
1715
- failedPerSecond: this._replicationAverages.sendsFailedPerSecond.average()
1716
- },
1717
- countByMessageType: this._computeMessageHistogram("type"),
1718
- avgSizeByMessageType: mapValues(this._sizeByMessageType, (summary) => summary.average())
1719
- }
1720
- };
1721
- }
1722
- get connectionsCount() {
1723
- return this._connectionsCount;
1724
- }
1725
- /**
1726
- * @internal
1727
- */
1728
- get lastPerSecondStats() {
1729
- return this._lastCompleteCounters;
1730
- }
1731
- /**
1732
- * @internal
1733
- */
1734
- get timeSeries() {
1735
- return {
1736
- ...this._localTimeSeries.storage,
1737
- ...this._localTimeSeries.replication
1738
- };
1739
- }
1740
- /**
1741
- * @internal
1742
- */
1743
- get messagesByPeerId() {
1744
- return this._computeMessageHistogram("peerId");
1745
- }
1746
- _advanceTimeWindow(millisPassed) {
1747
- const oldMetrics = Object.freeze(this._activeCounters);
1748
- this._activeCounters = createLocalCounters();
1749
- this._lastCompleteCounters = oldMetrics;
1750
- for (const peerId of Object.keys(oldMetrics.byPeerId)) {
1751
- this._activeCounters.byPeerId[peerId] = createMessageCounter();
1752
- }
1753
- this._addToTimeSeries(oldMetrics.replication, this._localTimeSeries.replication);
1754
- this._addToTimeSeries(oldMetrics.storage, this._localTimeSeries.storage);
1755
- if (Math.abs(millisPassed - 1e3) < 100) {
1756
- this._reportPerSecondRate(oldMetrics);
1757
- }
1758
- }
1759
- _addToTimeSeries(values, timeSeries) {
1760
- for (const [key, value] of Object.entries(values)) {
1761
- const values2 = timeSeries[key];
1762
- values2.push(value);
1763
- if (values2.length > this._params.timeSeriesLength) {
1764
- values2.shift();
1765
- }
1766
- }
1767
- }
1768
- _reportPerSecondRate(metrics) {
1769
- const toReport = [
1770
- [
1771
- "storage.load",
1772
- metrics.storage.loadedChunks,
1773
- this._storageAverages.loadsPerSecond
1774
- ],
1775
- [
1776
- "storage.store",
1777
- metrics.storage.storedChunks,
1778
- this._storageAverages.storesPerSecond
1779
- ],
1780
- [
1781
- "network.receive",
1782
- metrics.replication.received,
1783
- this._replicationAverages.receivedPerSecond
1784
- ],
1785
- [
1786
- "network.send",
1787
- metrics.replication.sent,
1788
- this._replicationAverages.sentPerSecond
1789
- ]
1790
- ];
1791
- for (const [metricName, metric, summary] of toReport) {
1792
- summary.record(metric);
1793
- if (metric > 0) {
1794
- trace2.metrics.distribution(`dxos.echo.${metricName}-rate`, metric);
1795
- trace2.metrics.increment(`dxos.echo.${metricName}`, 1, {
1796
- tags: {
1797
- status: "busy"
1798
- }
1799
- });
1800
- } else {
1801
- trace2.metrics.increment(`dxos.echo.${metricName}`, 1, {
1802
- tags: {
1803
- status: "idle"
1804
- }
1805
- });
1806
- }
1807
- }
1808
- this._replicationAverages.sendsFailedPerSecond.record(metrics.replication.failed);
1809
- }
1810
- recordPeerConnected(peerId) {
1811
- this._activeCounters.byPeerId[peerId] = createMessageCounter();
1812
- this._connectionsCount++;
1813
- }
1814
- recordPeerDisconnected(peerId) {
1815
- this._connectionsCount--;
1816
- delete this._activeCounters.byPeerId[peerId];
1817
- }
1818
- recordBytesStored(count) {
1819
- this._activeCounters.storage.storedChunks++;
1820
- this._activeCounters.storage.storedBytes += count;
1821
- this._storageAverages.storedChunkSize.record(count);
1822
- trace2.metrics.distribution("dxos.echo.storage.bytes-stored", count, {
1823
- unit: "bytes"
1824
- });
1825
- }
1826
- recordLoadDuration(durationMs) {
1827
- this._storageAverages.loadDuration.record(durationMs);
1828
- }
1829
- recordStoreDuration(durationMs) {
1830
- this._storageAverages.storeDuration.record(durationMs);
1831
- }
1832
- recordBytesLoaded(count) {
1833
- this._activeCounters.storage.loadedChunks++;
1834
- this._activeCounters.storage.loadedBytes += count;
1835
- this._storageAverages.loadedChunkSize.record(count);
1836
- trace2.metrics.distribution("dxos.echo.storage.bytes-loaded", count, {
1837
- unit: "bytes"
1838
- });
1839
- }
1840
- recordMessageSent(message, duration) {
1841
- let metricsGroupName;
1842
- const bytes = getByteCount(message);
1843
- const tags = {
1844
- type: message.type
1845
- };
1846
- if (isAutomergeProtocolMessage(message)) {
1847
- this._activeCounters.replication.sent++;
1848
- this._replicationAverages.sendDuration.record(duration);
1849
- this._replicationAverages.sentMessageSize.record(bytes);
1850
- metricsGroupName = "replication";
1851
- } else {
1852
- metricsGroupName = "collection-sync";
1853
- }
1854
- trace2.metrics.distribution(`dxos.echo.${metricsGroupName}.bytes-sent`, bytes, {
1855
- unit: "bytes",
1856
- tags
1857
- });
1858
- trace2.metrics.distribution(`dxos.echo.${metricsGroupName}.send-duration`, duration, {
1859
- unit: "millisecond",
1860
- tags
1861
- });
1862
- trace2.metrics.increment(`dxos.echo.${metricsGroupName}.send-status`, 1, {
1863
- tags: {
1864
- ...tags,
1865
- success: true
1866
- }
1867
- });
1868
- const { messageSize, messageCounts } = this._getStatsForType(message);
1869
- messageSize.record(bytes);
1870
- messageCounts.sent++;
1871
- this._lastSentMessages.push({
1872
- type: message.type,
1873
- peerId: message.targetId
1874
- });
1875
- }
1876
- recordMessageReceived(message) {
1877
- const bytes = getByteCount(message);
1878
- const tags = {
1879
- type: message.type
1880
- };
1881
- if (isAutomergeProtocolMessage(message)) {
1882
- this._activeCounters.replication.received++;
1883
- this._replicationAverages.receivedMessageSize.record(bytes);
1884
- trace2.metrics.distribution("dxos.echo.replication.bytes-received", bytes, {
1885
- unit: "bytes",
1886
- tags
1887
- });
1888
- } else {
1889
- trace2.metrics.distribution("dxos.echo.collection-sync.bytes-received", bytes, {
1890
- unit: "bytes",
1891
- tags
1892
- });
1893
- }
1894
- const { messageSize, messageCounts } = this._getStatsForType(message);
1895
- messageSize.record(bytes);
1896
- messageCounts.received++;
1897
- this._lastReceivedMessages.push({
1898
- type: message.type,
1899
- peerId: message.senderId
1900
- });
1901
- }
1902
- recordMessageSendingFailed(message) {
1903
- const tags = {
1904
- type: message.type,
1905
- success: false
1906
- };
1907
- if (isAutomergeProtocolMessage(message)) {
1908
- this._activeCounters.replication.failed++;
1909
- trace2.metrics.increment("dxos.echo.replication.send-status", 1, {
1910
- unit: "bytes",
1911
- tags
1912
- });
1913
- } else {
1914
- trace2.metrics.increment("dxos.echo.collection-sync.send-status", 1, {
1915
- unit: "bytes",
1916
- tags
1917
- });
1918
- }
1919
- const { messageCounts } = this._getStatsForType(message);
1920
- messageCounts.failed++;
1921
- }
1922
- _getStatsForType(message) {
1923
- const messageSize = this._sizeByMessageType[message.type] ??= createSlidingWindow();
1924
- const messageCounts = this._activeCounters.byType[message.type] ??= createMessageCounter();
1925
- return {
1926
- messageCounts,
1927
- messageSize
1928
- };
1929
- }
1930
- _computeMessageHistogram(groupKey) {
1931
- const result = {};
1932
- for (const receivedMessage of this._lastReceivedMessages) {
1933
- const counters = result[receivedMessage[groupKey]] ??= {
1934
- received: 0,
1935
- sent: 0
1936
- };
1937
- counters.received++;
1938
- }
1939
- for (const receivedMessage of this._lastSentMessages) {
1940
- const counters = result[receivedMessage[groupKey]] ??= {
1941
- received: 0,
1942
- sent: 0
1943
- };
1944
- counters.sent++;
1945
- }
1946
- return result;
1947
- }
1948
- };
1949
- EchoDataMonitor = _ts_decorate3([
1950
- trace2.resource()
1951
- ], EchoDataMonitor);
1952
- var isAutomergeProtocolMessage = (message) => {
1953
- return !(isCollectionQueryMessage(message) || isCollectionStateMessage(message));
1954
- };
1955
- var createSlidingWindow = (overrides) => new SlidingWindowSummary({
1956
- dataPoints: DEFAULT_AVG_WINDOW_SIZE,
1957
- precision: 2,
1958
- ...overrides
1959
- });
1960
- var createLocalCounters = () => ({
1961
- storage: {
1962
- loadedBytes: 0,
1963
- storedBytes: 0,
1964
- storedChunks: 0,
1965
- loadedChunks: 0
1966
- },
1967
- replication: createMessageCounter(),
1968
- byPeerId: {},
1969
- byType: {}
1970
- });
1971
- var createLocalTimeSeries = () => ({
1972
- storage: {
1973
- loadedBytes: [],
1974
- storedBytes: [],
1975
- storedChunks: [],
1976
- loadedChunks: []
1977
- },
1978
- replication: {
1979
- sent: [],
1980
- failed: [],
1981
- received: []
1982
- }
1983
- });
1984
- var createMessageCounter = () => ({
1985
- sent: 0,
1986
- received: 0,
1987
- failed: 0
1988
- });
1989
- var createNetworkAverages = () => ({
1990
- receivedMessageSize: createSlidingWindow(),
1991
- sentMessageSize: createSlidingWindow(),
1992
- sendDuration: createSlidingWindow(),
1993
- receivedPerSecond: createSlidingWindow({
1994
- dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
1995
- }),
1996
- sentPerSecond: createSlidingWindow({
1997
- dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
1998
- }),
1999
- sendsFailedPerSecond: createSlidingWindow({
2000
- dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2001
- })
2002
- });
2003
- var createStorageAverages = () => ({
2004
- storedChunkSize: createSlidingWindow(),
2005
- loadedChunkSize: createSlidingWindow(),
2006
- loadDuration: createSlidingWindow(),
2007
- storeDuration: createSlidingWindow(),
2008
- loadsPerSecond: createSlidingWindow({
2009
- dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2010
- }),
2011
- storesPerSecond: createSlidingWindow({
2012
- dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE
2013
- })
2014
- });
2015
- var getByteCount = (message) => {
2016
- return message.type.length + message.senderId.length + message.targetId.length + (message.data?.byteLength ?? 0) + (message.documentId?.length ?? 0);
2017
- };
2018
-
2019
- // packages/core/echo/echo-pipeline/src/db-host/data-service.ts
2020
- import { Stream } from "@dxos/codec-protobuf";
2021
- import { invariant as invariant7 } from "@dxos/invariant";
2022
- import { SpaceId as SpaceId2 } from "@dxos/keys";
2023
- import { log as log6 } from "@dxos/log";
2024
- var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/echo/echo-pipeline/src/db-host/data-service.ts";
2025
- var DataServiceImpl = class {
2026
- constructor(params) {
2027
- /**
2028
- * Map of subscriptions.
2029
- * subscriptionId -> DocumentsSynchronizer
2030
- */
2031
- this._subscriptions = /* @__PURE__ */ new Map();
2032
- this._automergeHost = params.automergeHost;
2033
- this._updateIndexes = params.updateIndexes;
2034
- }
2035
- subscribe(request) {
2036
- return new Stream(({ next, ready }) => {
2037
- const synchronizer = new DocumentsSynchronizer({
2038
- repo: this._automergeHost.repo,
2039
- sendUpdates: (updates) => next(updates)
2040
- });
2041
- synchronizer.open().then(() => {
2042
- this._subscriptions.set(request.subscriptionId, synchronizer);
2043
- ready();
2044
- }).catch((err) => log6.catch(err, void 0, {
2045
- F: __dxlog_file7,
2046
- L: 64,
2047
- S: this,
2048
- C: (f, a) => f(...a)
2049
- }));
2050
- return () => synchronizer.close();
2051
- });
2052
- }
2053
- async updateSubscription(request) {
2054
- const synchronizer = this._subscriptions.get(request.subscriptionId);
2055
- invariant7(synchronizer, "Subscription not found", {
2056
- F: __dxlog_file7,
2057
- L: 71,
2058
- S: this,
2059
- A: [
2060
- "synchronizer",
2061
- "'Subscription not found'"
2062
- ]
2063
- });
2064
- if (request.addIds?.length) {
2065
- await synchronizer.addDocuments(request.addIds);
2066
- }
2067
- if (request.removeIds?.length) {
2068
- await synchronizer.removeDocuments(request.removeIds);
2069
- }
2070
- }
2071
- async update(request) {
2072
- if (!request.updates) {
2073
- return;
2074
- }
2075
- const synchronizer = this._subscriptions.get(request.subscriptionId);
2076
- invariant7(synchronizer, "Subscription not found", {
2077
- F: __dxlog_file7,
2078
- L: 86,
2079
- S: this,
2080
- A: [
2081
- "synchronizer",
2082
- "'Subscription not found'"
2083
- ]
2084
- });
2085
- synchronizer.update(request.updates);
2086
- }
2087
- async flush(request) {
2088
- await this._automergeHost.flush(request);
2089
- }
2090
- async getDocumentHeads(request) {
2091
- const documentIds = request.documentIds;
2092
- if (!documentIds) {
2093
- return {
2094
- heads: {
2095
- entries: []
2096
- }
2097
- };
2098
- }
2099
- const heads = await this._automergeHost.getHeads(documentIds);
2100
- return {
2101
- heads: {
2102
- entries: heads.map((heads2, idx) => ({
2103
- documentId: documentIds[idx],
2104
- heads: heads2
2105
- }))
2106
- }
2107
- };
2108
- }
2109
- async waitUntilHeadsReplicated(request, options) {
2110
- await this._automergeHost.waitUntilHeadsReplicated(request.heads);
2111
- }
2112
- async reIndexHeads(request, options) {
2113
- await this._automergeHost.reIndexHeads(request.documentIds ?? []);
2114
- }
2115
- async updateIndexes() {
2116
- await this._updateIndexes();
2117
- }
2118
- async getSpaceSyncState(request, options) {
2119
- invariant7(SpaceId2.isValid(request.spaceId), void 0, {
2120
- F: __dxlog_file7,
2121
- L: 127,
2122
- S: this,
2123
- A: [
2124
- "SpaceId.isValid(request.spaceId)",
2125
- ""
2126
- ]
2127
- });
2128
- const collectionId = deriveCollectionIdFromSpaceId(request.spaceId);
2129
- const state = await this._automergeHost.getCollectionSyncState(collectionId);
2130
- return {
2131
- peers: state.peers.map((peer) => ({
2132
- peerId: peer.peerId,
2133
- documentsToReconcile: peer.differentDocuments
2134
- }))
2135
- };
2136
- }
2137
- };
2138
-
2139
- export {
2140
- DocumentsSynchronizer,
2141
- diffCollectionState,
2142
- LevelDBStorageAdapter,
2143
- encodingOptions,
2144
- AutomergeHost,
2145
- getSpaceKeyFromDoc,
2146
- deriveCollectionIdFromSpaceId,
2147
- getSpaceIdFromCollectionId,
2148
- MeshEchoReplicator,
2149
- EchoDataMonitor,
2150
- DataServiceImpl
2151
- };
2152
- //# sourceMappingURL=chunk-MPWFDDQK.mjs.map