@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
@@ -25,7 +25,7 @@ import {
25
25
  type StorageKey,
26
26
  } from '@dxos/automerge/automerge-repo';
27
27
  import { Context, Resource, cancelWithContext, type Lifecycle } from '@dxos/context';
28
- import { type SpaceDoc } from '@dxos/echo-protocol';
28
+ import { type CollectionId, type SpaceDoc } from '@dxos/echo-protocol';
29
29
  import { type IndexMetadataStore } from '@dxos/indexing';
30
30
  import { invariant } from '@dxos/invariant';
31
31
  import { PublicKey } from '@dxos/keys';
@@ -82,6 +82,8 @@ export class AutomergeHost extends Resource {
82
82
  @trace.info()
83
83
  private _peerId!: PeerId;
84
84
 
85
+ public readonly collectionStateUpdated = new Event<{ collectionId: CollectionId }>();
86
+
85
87
  constructor({ db, indexMetadataStore, dataMonitor }: AutomergeHostParams) {
86
88
  super();
87
89
  this._db = db;
@@ -128,6 +130,7 @@ export class AutomergeHost extends Resource {
128
130
 
129
131
  this._collectionSynchronizer.remoteStateUpdated.on(this._ctx, ({ collectionId, peerId }) => {
130
132
  this._onRemoteCollectionStateUpdated(collectionId, peerId);
133
+ this.collectionStateUpdated.emit({ collectionId: collectionId as CollectionId });
131
134
  });
132
135
 
133
136
  await this._echoNetworkAdapter.open();
@@ -416,7 +419,11 @@ export class AutomergeHost extends Resource {
416
419
  const diff = diffCollectionState(localState, state);
417
420
  result.peers.push({
418
421
  peerId,
422
+ missingOnRemote: diff.missingOnRemote.length,
423
+ missingOnLocal: diff.missingOnLocal.length,
419
424
  differentDocuments: diff.different.length,
425
+ localDocumentCount: Object.keys(localState.documents).length,
426
+ remoteDocumentCount: Object.keys(state.documents).length,
420
427
  });
421
428
  }
422
429
 
@@ -466,31 +473,37 @@ export class AutomergeHost extends Resource {
466
473
  return;
467
474
  }
468
475
 
469
- const { different } = diffCollectionState(localState, remoteState);
476
+ const { different, missingOnLocal, missingOnRemote } = diffCollectionState(localState, remoteState);
477
+ const toReplicate = [...missingOnLocal, ...missingOnRemote, ...different];
470
478
 
471
- if (different.length === 0) {
479
+ if (toReplicate.length === 0) {
472
480
  return;
473
481
  }
474
482
 
475
483
  log.info('replication documents after collection sync', {
476
- count: different.length,
484
+ count: toReplicate.length,
477
485
  });
478
486
 
479
- // Load the documents that are different.
480
- for (const documentId of different) {
487
+ // Load the documents so they will start syncing.
488
+ for (const documentId of toReplicate) {
481
489
  this._repo.find(documentId);
482
490
  }
483
491
  }
484
492
 
485
493
  private _onHeadsChanged(documentId: DocumentId, heads: Heads) {
494
+ const collectionsChanged = new Set<CollectionId>();
486
495
  for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
487
496
  const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);
488
497
  if (state?.documents[documentId]) {
489
498
  const newState = structuredClone(state);
490
499
  newState.documents[documentId] = heads;
491
500
  this._collectionSynchronizer.setLocalCollectionState(collectionId, newState);
501
+ collectionsChanged.add(collectionId as CollectionId);
492
502
  }
493
503
  }
504
+ for (const collectionId of collectionsChanged) {
505
+ this.collectionStateUpdated.emit({ collectionId });
506
+ }
494
507
  }
495
508
  }
496
509
 
@@ -540,5 +553,28 @@ export type CollectionSyncState = {
540
553
 
541
554
  export type PeerSyncState = {
542
555
  peerId: PeerId;
556
+ /**
557
+ * Documents that are present locally but not on the remote peer.
558
+ */
559
+ missingOnRemote: number;
560
+
561
+ /**
562
+ * Documents that are present on the remote peer but not locally.
563
+ */
564
+ missingOnLocal: number;
565
+
566
+ /**
567
+ * Documents that are present on both peers but have different heads.
568
+ */
543
569
  differentDocuments: number;
570
+
571
+ /**
572
+ * Total number of documents locally.
573
+ */
574
+ localDocumentCount: number;
575
+
576
+ /**
577
+ * Total number of documents on the remote peer.
578
+ */
579
+ remoteDocumentCount: number;
544
580
  };
@@ -72,7 +72,9 @@ describe('CollectionSynchronizer', () => {
72
72
  const diff = diffCollectionState(STATE_1, STATE_2);
73
73
 
74
74
  expect(diff).to.deep.equal({
75
- different: ['b', 'c', 'd'],
75
+ missingOnLocal: ['d'],
76
+ missingOnRemote: ['c'],
77
+ different: ['b'],
76
78
  });
77
79
  });
78
80
  });
@@ -6,6 +6,7 @@ import { asyncReturn, Event, scheduleTask, scheduleTaskInterval } from '@dxos/as
6
6
  import { next as am } from '@dxos/automerge/automerge';
7
7
  import type { DocumentId, PeerId } from '@dxos/automerge/automerge-repo';
8
8
  import { Resource, type Context } from '@dxos/context';
9
+ import { log } from '@dxos/log';
9
10
  import { defaultMap } from '@dxos/util';
10
11
 
11
12
  const MIN_QUERY_INTERVAL = 5_000;
@@ -64,6 +65,7 @@ export class CollectionSynchronizer extends Resource {
64
65
  }
65
66
 
66
67
  setLocalCollectionState(collectionId: string, state: CollectionState) {
68
+ log('setLocalCollectionState', { collectionId, state });
67
69
  this._getPerCollectionState(collectionId).localState = state;
68
70
 
69
71
  queueMicrotask(async () => {
@@ -143,6 +145,7 @@ export class CollectionSynchronizer extends Resource {
143
145
  * Callback when a peer sends the state of a collection.
144
146
  */
145
147
  onRemoteStateReceived(collectionId: string, peerId: PeerId, state: CollectionState) {
148
+ log('onRemoteStateReceived', { collectionId, peerId, state });
146
149
  validateCollectionState(state);
147
150
  const perCollectionState = this._getPerCollectionState(collectionId);
148
151
  perCollectionState.remoteStates.set(peerId, state);
@@ -184,24 +187,32 @@ export type CollectionState = {
184
187
  };
185
188
 
186
189
  export type CollectionStateDiff = {
190
+ missingOnRemote: DocumentId[];
191
+ missingOnLocal: DocumentId[];
187
192
  different: DocumentId[];
188
193
  };
189
194
 
190
195
  export const diffCollectionState = (local: CollectionState, remote: CollectionState): CollectionStateDiff => {
191
196
  const allDocuments = new Set<DocumentId>([...Object.keys(local.documents), ...Object.keys(remote.documents)] as any);
192
197
 
198
+ const missingOnRemote: DocumentId[] = [];
199
+ const missingOnLocal: DocumentId[] = [];
193
200
  const different: DocumentId[] = [];
194
201
  for (const documentId of allDocuments) {
195
- if (
196
- !local.documents[documentId] ||
197
- !remote.documents[documentId] ||
198
- !am.equals(local.documents[documentId], remote.documents[documentId])
199
- ) {
202
+ if (!local.documents[documentId]) {
203
+ missingOnLocal.push(documentId as DocumentId);
204
+ } else if (!remote.documents[documentId]) {
205
+ missingOnRemote.push(documentId as DocumentId);
206
+ } else if (!am.equals(local.documents[documentId], remote.documents[documentId])) {
200
207
  different.push(documentId as DocumentId);
201
208
  }
202
209
  }
203
210
 
204
- return { different };
211
+ return {
212
+ missingOnRemote,
213
+ missingOnLocal,
214
+ different,
215
+ };
205
216
  };
206
217
 
207
218
  const validateCollectionState = (state: CollectionState) => {
@@ -2,6 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ import type { CollectionId } from '@dxos/echo-protocol';
5
6
  import { invariant } from '@dxos/invariant';
6
7
  import { PublicKey, type SpaceId } from '@dxos/keys';
7
8
  import { log } from '@dxos/log';
@@ -126,7 +127,7 @@ export class MeshEchoReplicator implements EchoReplicator {
126
127
  }
127
128
  },
128
129
  shouldSyncCollection: ({ collectionId }) => {
129
- const spaceId = getSpaceIdFromCollectionId(collectionId);
130
+ const spaceId = getSpaceIdFromCollectionId(collectionId as CollectionId);
130
131
 
131
132
  const authorizedDevices = this._authorizedDevices.get(spaceId);
132
133
 
@@ -2,12 +2,13 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ import type { CollectionId } from '@dxos/echo-protocol';
5
6
  import { invariant } from '@dxos/invariant';
6
7
  import { SpaceId } from '@dxos/keys';
7
8
 
8
- export const deriveCollectionIdFromSpaceId = (spaceId: SpaceId): string => `space:${spaceId}`;
9
+ export const deriveCollectionIdFromSpaceId = (spaceId: SpaceId): CollectionId => `space:${spaceId}` as CollectionId;
9
10
 
10
- export const getSpaceIdFromCollectionId = (collectionId: string): SpaceId => {
11
+ export const getSpaceIdFromCollectionId = (collectionId: CollectionId): SpaceId => {
11
12
  const spaceId = collectionId.replace(/^space:/, '');
12
13
  invariant(SpaceId.isValid(spaceId));
13
14
  return spaceId;
@@ -0,0 +1,38 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import * as A from '@dxos/automerge/automerge';
6
+ import { log } from '@dxos/log';
7
+
8
+ export type DocMetrics = {
9
+ compressedByteSize: number;
10
+ loadTime: number;
11
+ mutationCount: number;
12
+ };
13
+
14
+ /**
15
+ * WARN: Slow to run on large docs.
16
+ */
17
+ export const measureDocMetrics = (doc: A.Doc<any>): DocMetrics => {
18
+ const snapshot = A.save(doc);
19
+
20
+ const start = Date.now();
21
+ const temp = A.load(snapshot);
22
+ const end = Date.now();
23
+ A.free(temp);
24
+
25
+ const getAllChangesStart = Date.now();
26
+ const mutationCount = A.getAllChanges(doc).length;
27
+ const getAllChangesEnd = Date.now();
28
+
29
+ if (getAllChangesEnd - getAllChangesStart > 300) {
30
+ log.warn('getAllChanges took too long', { elapsed: getAllChangesEnd - getAllChangesStart });
31
+ }
32
+
33
+ return {
34
+ compressedByteSize: snapshot.byteLength,
35
+ loadTime: end - start,
36
+ mutationCount,
37
+ };
38
+ };
@@ -2,8 +2,10 @@
2
2
  // Copyright 2021 DXOS.org
3
3
  //
4
4
 
5
+ import { UpdateScheduler } from '@dxos/async';
5
6
  import { type DocumentId } from '@dxos/automerge/automerge-repo';
6
- import { type RequestOptions, Stream } from '@dxos/codec-protobuf';
7
+ import { type RequestOptions } from '@dxos/codec-protobuf';
8
+ import { Stream } from '@dxos/codec-protobuf/stream';
7
9
  import { invariant } from '@dxos/invariant';
8
10
  import { SpaceId } from '@dxos/keys';
9
11
  import { log } from '@dxos/log';
@@ -120,19 +122,32 @@ export class DataServiceImpl implements DataService {
120
122
  await this._updateIndexes();
121
123
  }
122
124
 
123
- async getSpaceSyncState(
124
- request: GetSpaceSyncStateRequest,
125
- options?: RequestOptions | undefined,
126
- ): Promise<SpaceSyncState> {
127
- invariant(SpaceId.isValid(request.spaceId));
128
- const collectionId = deriveCollectionIdFromSpaceId(request.spaceId);
129
- const state = await this._automergeHost.getCollectionSyncState(collectionId);
125
+ subscribeSpaceSyncState(request: GetSpaceSyncStateRequest): Stream<SpaceSyncState> {
126
+ return new Stream<SpaceSyncState>(({ ctx, next, ready }) => {
127
+ invariant(SpaceId.isValid(request.spaceId));
128
+ const collectionId = deriveCollectionIdFromSpaceId(request.spaceId);
129
+
130
+ const scheduler = new UpdateScheduler(ctx, async () => {
131
+ const state = await this._automergeHost.getCollectionSyncState(collectionId);
132
+
133
+ next({
134
+ peers: state.peers.map((peer) => ({
135
+ peerId: peer.peerId,
136
+ missingOnRemote: peer.missingOnRemote,
137
+ missingOnLocal: peer.missingOnLocal,
138
+ differentDocuments: peer.differentDocuments,
139
+ localDocumentCount: peer.localDocumentCount,
140
+ remoteDocumentCount: peer.remoteDocumentCount,
141
+ })),
142
+ });
143
+ });
130
144
 
131
- return {
132
- peers: state.peers.map((peer) => ({
133
- peerId: peer.peerId,
134
- documentsToReconcile: peer.differentDocuments,
135
- })),
136
- };
145
+ this._automergeHost.collectionStateUpdated.on(ctx, (e) => {
146
+ if (e.collectionId === collectionId) {
147
+ scheduler.trigger();
148
+ }
149
+ });
150
+ scheduler.trigger();
151
+ });
137
152
  }
138
153
  }
@@ -0,0 +1,86 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import type * as A from '@dxos/automerge/automerge';
6
+ import type { AutomergeUrl, DocHandle, DocumentId } from '@dxos/automerge/automerge-repo';
7
+ import { type SpaceDoc, SpaceDocVersion } from '@dxos/echo-protocol';
8
+ import { invariant } from '@dxos/invariant';
9
+
10
+ import { measureDocMetrics, type DocMetrics } from './automerge-metrics';
11
+ import { getSpaceKeyFromDoc } from '../automerge';
12
+
13
+ export class DatabaseRoot {
14
+ constructor(private readonly _rootHandle: DocHandle<SpaceDoc>) {}
15
+
16
+ get documentId(): DocumentId {
17
+ return this._rootHandle.documentId;
18
+ }
19
+
20
+ get url() {
21
+ return this._rootHandle.url;
22
+ }
23
+
24
+ get isLoaded(): boolean {
25
+ return !!this._rootHandle.docSync();
26
+ }
27
+
28
+ get handle(): DocHandle<SpaceDoc> {
29
+ return this._rootHandle;
30
+ }
31
+
32
+ docSync(): A.Doc<SpaceDoc> | null {
33
+ return this._rootHandle.docSync();
34
+ }
35
+
36
+ getVersion(): SpaceDocVersion | null {
37
+ const doc = this.docSync();
38
+ if (!doc) {
39
+ return null;
40
+ }
41
+
42
+ return doc.version ?? SpaceDocVersion.LEGACY;
43
+ }
44
+
45
+ getSpaceKey(): string | null {
46
+ const doc = this.docSync();
47
+ if (!doc) {
48
+ return null;
49
+ }
50
+
51
+ return getSpaceKeyFromDoc(doc);
52
+ }
53
+
54
+ getInlineObjectCount(): number | null {
55
+ const doc = this.docSync();
56
+ if (!doc) {
57
+ return null;
58
+ }
59
+
60
+ return Object.keys(doc.objects ?? {}).length;
61
+ }
62
+
63
+ getLinkedObjectCount(): number | null {
64
+ const doc = this.docSync();
65
+ if (!doc) {
66
+ return null;
67
+ }
68
+
69
+ return Object.keys(doc.links ?? {}).length;
70
+ }
71
+
72
+ getAllLinkedDocuments(): AutomergeUrl[] {
73
+ const doc = this.docSync();
74
+ invariant(doc);
75
+
76
+ return Object.values(doc.links ?? {}) as AutomergeUrl[];
77
+ }
78
+
79
+ measureMetrics(): DocMetrics | null {
80
+ const doc = this.docSync();
81
+ if (!doc) {
82
+ return null;
83
+ }
84
+ return measureDocMetrics(doc);
85
+ }
86
+ }
@@ -0,0 +1,73 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import * as A from '@dxos/automerge/automerge';
6
+ import { type DocumentId } from '@dxos/automerge/automerge-repo';
7
+ import { Context } from '@dxos/context';
8
+ import { SpaceDocVersion, type SpaceDoc } from '@dxos/echo-protocol';
9
+ import { type ObjectSnapshot, type IdToHeads } from '@dxos/indexing';
10
+ import { invariant } from '@dxos/invariant';
11
+ import { log } from '@dxos/log';
12
+ import { ObjectPointerVersion, objectPointerCodec } from '@dxos/protocols';
13
+
14
+ import { type AutomergeHost, getSpaceKeyFromDoc } from '../automerge';
15
+
16
+ const LOG_VIEW_OPERATION_THRESHOLD = 300;
17
+
18
+ /**
19
+ * Factory for `loadDocuments` iterator.
20
+ */
21
+ export const createSelectedDocumentsIterator = (automergeHost: AutomergeHost) =>
22
+ /**
23
+ * Get object data blobs from Automerge Repo by ids.
24
+ */
25
+ // TODO(mykola): Unload automerge handles after usage.
26
+ async function* loadDocuments(objects: IdToHeads): AsyncGenerator<ObjectSnapshot[], void, void> {
27
+ for (const [id, heads] of objects.entries()) {
28
+ try {
29
+ const { documentId, objectId } = objectPointerCodec.decode(id);
30
+ const handle = await automergeHost.loadDoc(Context.default(), documentId as DocumentId);
31
+
32
+ let doc: A.Doc<SpaceDoc> = handle.docSync();
33
+ invariant(doc);
34
+
35
+ const currentHeads = A.getHeads(doc);
36
+
37
+ // Checkout the requested version of the document.
38
+ if (!A.equals(currentHeads, heads)) {
39
+ const begin = Date.now();
40
+ // `view` can take a long time even if the document is already at the right version.
41
+ doc = A.view(doc, heads);
42
+ const end = Date.now();
43
+ if (end - begin > LOG_VIEW_OPERATION_THRESHOLD) {
44
+ log.info('Checking out document version is taking too long', {
45
+ duration: end - begin,
46
+ requestedHeads: heads,
47
+ originalHeads: currentHeads,
48
+ });
49
+ }
50
+ }
51
+
52
+ // Skip outdated docs.
53
+ if (doc.version !== SpaceDocVersion.CURRENT) {
54
+ continue;
55
+ }
56
+
57
+ if (!doc.objects?.[objectId]) {
58
+ continue;
59
+ }
60
+
61
+ // Upgrade V0 object pointers to V1.
62
+ let newId = id;
63
+ if (objectPointerCodec.getVersion(id) === ObjectPointerVersion.V0) {
64
+ const spaceKey = getSpaceKeyFromDoc(doc) ?? undefined;
65
+ newId = objectPointerCodec.encode({ documentId, objectId, spaceKey });
66
+ }
67
+
68
+ yield [{ id: newId, object: doc.objects![objectId], heads }];
69
+ } catch (error) {
70
+ log.error('Error loading document', { heads, id, error });
71
+ }
72
+ }
73
+ };