@dxos/echo-pipeline 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef

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 (189) hide show
  1. package/dist/lib/{browser/chunk-XGG76KKU.mjs → neutral/chunk-VIHYDCCC.mjs} +404 -963
  2. package/dist/lib/neutral/chunk-VIHYDCCC.mjs.map +7 -0
  3. package/dist/lib/{browser/chunk-BVR7OOZK.mjs → neutral/chunk-YBC6ONBZ.mjs} +23 -27
  4. package/dist/lib/neutral/chunk-YBC6ONBZ.mjs.map +7 -0
  5. package/dist/lib/{browser → neutral}/filter/index.mjs +1 -2
  6. package/dist/lib/{browser → neutral}/index.mjs +3143 -2206
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/lib/{browser → neutral}/testing/index.mjs +103 -395
  10. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  11. package/dist/types/src/automerge/automerge-host.d.ts +43 -23
  12. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  13. package/dist/types/src/automerge/automerge-repo.test.d.ts +1 -1
  14. package/dist/types/src/automerge/automerge-repo.test.d.ts.map +1 -1
  15. package/dist/types/src/automerge/collection-synchronizer.d.ts +5 -3
  16. package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
  17. package/dist/types/src/automerge/echo-data-monitor.d.ts.map +1 -1
  18. package/dist/types/src/automerge/echo-network-adapter.d.ts +17 -11
  19. package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
  20. package/dist/types/src/automerge/echo-replicator.d.ts +20 -16
  21. package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
  22. package/dist/types/src/automerge/heads-store.d.ts +9 -2
  23. package/dist/types/src/automerge/heads-store.d.ts.map +1 -1
  24. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts +4 -4
  25. package/dist/types/src/automerge/leveldb-storage-adapter.d.ts.map +1 -1
  26. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +8 -8
  27. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
  28. package/dist/types/src/automerge/mesh-echo-replicator.d.ts +6 -5
  29. package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
  30. package/dist/types/src/automerge/network-protocol.d.ts.map +1 -1
  31. package/dist/types/src/automerge/space-collection.d.ts.map +1 -1
  32. package/dist/types/src/common/feeds.d.ts.map +1 -1
  33. package/dist/types/src/common/space-id.d.ts.map +1 -1
  34. package/dist/types/src/db-host/automerge-data-source.d.ts +35 -0
  35. package/dist/types/src/db-host/automerge-data-source.d.ts.map +1 -0
  36. package/dist/types/src/db-host/automerge-data-source.test.d.ts +2 -0
  37. package/dist/types/src/db-host/automerge-data-source.test.d.ts.map +1 -0
  38. package/dist/types/src/db-host/automerge-metrics.d.ts.map +1 -1
  39. package/dist/types/src/db-host/data-service.d.ts +7 -6
  40. package/dist/types/src/db-host/data-service.d.ts.map +1 -1
  41. package/dist/types/src/db-host/database-root.d.ts.map +1 -1
  42. package/dist/types/src/db-host/documents-synchronizer.d.ts +8 -7
  43. package/dist/types/src/db-host/documents-synchronizer.d.ts.map +1 -1
  44. package/dist/types/src/db-host/echo-host.d.ts +58 -28
  45. package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
  46. package/dist/types/src/db-host/index.d.ts +2 -0
  47. package/dist/types/src/db-host/index.d.ts.map +1 -1
  48. package/dist/types/src/db-host/invalidation-hint.d.ts +19 -0
  49. package/dist/types/src/db-host/invalidation-hint.d.ts.map +1 -0
  50. package/dist/types/src/db-host/local-queue-service.d.ts +19 -0
  51. package/dist/types/src/db-host/local-queue-service.d.ts.map +1 -0
  52. package/dist/types/src/db-host/query-invalidation.test.d.ts +2 -0
  53. package/dist/types/src/db-host/query-invalidation.test.d.ts.map +1 -0
  54. package/dist/types/src/db-host/query-service.d.ts +18 -10
  55. package/dist/types/src/db-host/query-service.d.ts.map +1 -1
  56. package/dist/types/src/db-host/queue-data-source.d.ts +38 -0
  57. package/dist/types/src/db-host/queue-data-source.d.ts.map +1 -0
  58. package/dist/types/src/db-host/queue-service.test.d.ts +2 -0
  59. package/dist/types/src/db-host/queue-service.test.d.ts.map +1 -0
  60. package/dist/types/src/db-host/space-state-manager.d.ts +1 -0
  61. package/dist/types/src/db-host/space-state-manager.d.ts.map +1 -1
  62. package/dist/types/src/db-host/stub.d.ts +11 -0
  63. package/dist/types/src/db-host/stub.d.ts.map +1 -0
  64. package/dist/types/src/edge/echo-edge-replicator.d.ts +7 -6
  65. package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
  66. package/dist/types/src/edge/inflight-request-limiter.d.ts.map +1 -1
  67. package/dist/types/src/filter/filter-match.d.ts +2 -2
  68. package/dist/types/src/filter/filter-match.d.ts.map +1 -1
  69. package/dist/types/src/metadata/metadata-store.d.ts.map +1 -1
  70. package/dist/types/src/pipeline/message-selector.d.ts.map +1 -1
  71. package/dist/types/src/pipeline/pipeline.d.ts +2 -2
  72. package/dist/types/src/pipeline/pipeline.d.ts.map +1 -1
  73. package/dist/types/src/pipeline/timeframe-clock.d.ts.map +1 -1
  74. package/dist/types/src/query/errors.d.ts +16 -20
  75. package/dist/types/src/query/errors.d.ts.map +1 -1
  76. package/dist/types/src/query/plan.d.ts +59 -8
  77. package/dist/types/src/query/plan.d.ts.map +1 -1
  78. package/dist/types/src/query/query-executor.d.ts +62 -10
  79. package/dist/types/src/query/query-executor.d.ts.map +1 -1
  80. package/dist/types/src/query/query-planner.d.ts +10 -1
  81. package/dist/types/src/query/query-planner.d.ts.map +1 -1
  82. package/dist/types/src/space/admission-discovery-extension.d.ts.map +1 -1
  83. package/dist/types/src/space/auth.d.ts +3 -3
  84. package/dist/types/src/space/auth.d.ts.map +1 -1
  85. package/dist/types/src/space/control-pipeline.d.ts +4 -3
  86. package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
  87. package/dist/types/src/space/space-manager.d.ts +7 -7
  88. package/dist/types/src/space/space-manager.d.ts.map +1 -1
  89. package/dist/types/src/space/space-protocol.d.ts +9 -8
  90. package/dist/types/src/space/space-protocol.d.ts.map +1 -1
  91. package/dist/types/src/space/space.d.ts +5 -5
  92. package/dist/types/src/space/space.d.ts.map +1 -1
  93. package/dist/types/src/testing/change-metadata.d.ts.map +1 -1
  94. package/dist/types/src/testing/index.d.ts +0 -2
  95. package/dist/types/src/testing/index.d.ts.map +1 -1
  96. package/dist/types/src/testing/test-agent-builder.d.ts.map +1 -1
  97. package/dist/types/src/testing/test-feed-builder.d.ts.map +1 -1
  98. package/dist/types/src/testing/test-network-adapter.d.ts +1 -1
  99. package/dist/types/src/testing/test-network-adapter.d.ts.map +1 -1
  100. package/dist/types/src/testing/test-replicator.d.ts +13 -13
  101. package/dist/types/src/testing/test-replicator.d.ts.map +1 -1
  102. package/dist/types/src/util.d.ts.map +1 -1
  103. package/dist/types/tsconfig.tsbuildinfo +1 -1
  104. package/package.json +51 -54
  105. package/src/automerge/automerge-host.test.ts +42 -23
  106. package/src/automerge/automerge-host.ts +163 -88
  107. package/src/automerge/automerge-repo.test.ts +149 -32
  108. package/src/automerge/collection-synchronizer.test.ts +19 -13
  109. package/src/automerge/collection-synchronizer.ts +69 -28
  110. package/src/automerge/echo-network-adapter.test.ts +2 -1
  111. package/src/automerge/echo-network-adapter.ts +40 -29
  112. package/src/automerge/echo-replicator.ts +21 -16
  113. package/src/automerge/heads-store.ts +42 -3
  114. package/src/automerge/leveldb-storage-adapter.ts +4 -4
  115. package/src/automerge/mesh-echo-replicator-connection.ts +8 -8
  116. package/src/automerge/mesh-echo-replicator.ts +14 -11
  117. package/src/db-host/automerge-data-source.test.ts +299 -0
  118. package/src/db-host/automerge-data-source.ts +186 -0
  119. package/src/db-host/data-service.ts +17 -10
  120. package/src/db-host/documents-synchronizer.test.ts +143 -14
  121. package/src/db-host/documents-synchronizer.ts +54 -51
  122. package/src/db-host/echo-host.ts +321 -86
  123. package/src/db-host/index.ts +2 -0
  124. package/src/db-host/invalidation-hint.ts +50 -0
  125. package/src/db-host/local-queue-service.ts +127 -0
  126. package/src/db-host/query-invalidation.test.ts +270 -0
  127. package/src/db-host/query-service.ts +110 -112
  128. package/src/db-host/queue-data-source.ts +159 -0
  129. package/src/db-host/queue-service.test.ts +145 -0
  130. package/src/db-host/space-state-manager.ts +5 -1
  131. package/src/db-host/stub.ts +33 -0
  132. package/src/edge/echo-edge-replicator.test.ts +9 -9
  133. package/src/edge/echo-edge-replicator.ts +76 -47
  134. package/src/filter/filter-match.test.ts +41 -25
  135. package/src/filter/filter-match.ts +33 -36
  136. package/src/metadata/metadata-store.ts +8 -5
  137. package/src/pipeline/pipeline-stress.test.ts +1 -3
  138. package/src/pipeline/pipeline.test.ts +0 -1
  139. package/src/pipeline/pipeline.ts +2 -3
  140. package/src/query/errors.ts +2 -2
  141. package/src/query/plan.ts +71 -8
  142. package/src/query/query-executor.ts +1170 -197
  143. package/src/query/query-planner.test.ts +854 -86
  144. package/src/query/query-planner.ts +408 -38
  145. package/src/space/admission-discovery-extension.ts +1 -1
  146. package/src/space/auth.ts +6 -6
  147. package/src/space/control-pipeline.test.ts +2 -2
  148. package/src/space/control-pipeline.ts +7 -7
  149. package/src/space/space-manager.ts +12 -17
  150. package/src/space/space-protocol.browser.test.ts +13 -12
  151. package/src/space/space-protocol.test.ts +13 -13
  152. package/src/space/space-protocol.ts +16 -15
  153. package/src/space/space.test.ts +2 -2
  154. package/src/space/space.ts +9 -10
  155. package/src/testing/index.ts +0 -2
  156. package/src/testing/test-agent-builder.ts +0 -1
  157. package/src/testing/test-network-adapter.ts +16 -3
  158. package/src/testing/test-replicator.ts +19 -18
  159. package/src/util.ts +7 -3
  160. package/dist/lib/browser/chunk-BVR7OOZK.mjs.map +0 -7
  161. package/dist/lib/browser/chunk-CGS2ULMK.mjs +0 -11
  162. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +0 -7
  163. package/dist/lib/browser/chunk-XGG76KKU.mjs.map +0 -7
  164. package/dist/lib/browser/index.mjs.map +0 -7
  165. package/dist/lib/browser/meta.json +0 -1
  166. package/dist/lib/browser/testing/index.mjs.map +0 -7
  167. package/dist/lib/node-esm/chunk-CHMJJ4DG.mjs +0 -2230
  168. package/dist/lib/node-esm/chunk-CHMJJ4DG.mjs.map +0 -7
  169. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  170. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  171. package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs +0 -251
  172. package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs.map +0 -7
  173. package/dist/lib/node-esm/filter/index.mjs +0 -13
  174. package/dist/lib/node-esm/filter/index.mjs.map +0 -7
  175. package/dist/lib/node-esm/index.mjs +0 -5560
  176. package/dist/lib/node-esm/index.mjs.map +0 -7
  177. package/dist/lib/node-esm/meta.json +0 -1
  178. package/dist/lib/node-esm/testing/index.mjs +0 -805
  179. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  180. package/dist/types/src/db-host/documents-iterator.d.ts +0 -7
  181. package/dist/types/src/db-host/documents-iterator.d.ts.map +0 -1
  182. package/dist/types/src/testing/test-data.d.ts +0 -18
  183. package/dist/types/src/testing/test-data.d.ts.map +0 -1
  184. package/dist/types/src/testing/test-schema.d.ts +0 -37
  185. package/dist/types/src/testing/test-schema.d.ts.map +0 -1
  186. package/src/db-host/documents-iterator.ts +0 -74
  187. package/src/testing/test-data.ts +0 -127
  188. package/src/testing/test-schema.ts +0 -53
  189. /package/dist/lib/{browser → neutral}/filter/index.mjs.map +0 -0
@@ -25,35 +25,33 @@ import {
25
25
  type StorageKey,
26
26
  interpretAsDocumentId,
27
27
  } from '@automerge/automerge-repo';
28
+ import type * as Record from 'effect/Record';
28
29
 
29
30
  import { DeferredTask, Event, asyncTimeout } from '@dxos/async';
30
31
  import { Context, type Lifecycle, Resource, cancelWithContext } from '@dxos/context';
31
32
  import { type CollectionId, DatabaseDirectory } from '@dxos/echo-protocol';
32
- import { type IndexMetadataStore } from '@dxos/indexing';
33
33
  import { invariant } from '@dxos/invariant';
34
34
  import { PublicKey } from '@dxos/keys';
35
35
  import { type LevelDB } from '@dxos/kv-store';
36
36
  import { log } from '@dxos/log';
37
- import { objectPointerCodec } from '@dxos/protocols';
38
37
  import { type SpaceSyncState } from '@dxos/protocols/proto/dxos/echo/service';
39
38
  import { type DocHeadsList, type FlushRequest } from '@dxos/protocols/proto/dxos/echo/service';
40
39
  import { trace } from '@dxos/tracing';
41
- import { ComplexSet, bufferToArray, isNonNullable, range } from '@dxos/util';
40
+ import { ComplexSet, bufferToArray, defaultMap, isNonNullable, range } from '@dxos/util';
42
41
 
43
42
  import { type CollectionState, CollectionSynchronizer, diffCollectionState } from './collection-synchronizer';
44
43
  import { type EchoDataMonitor } from './echo-data-monitor';
45
44
  import { EchoNetworkAdapter, isEchoPeerMetadata } from './echo-network-adapter';
46
- import { type EchoReplicator, type RemoteDocumentExistenceCheckParams } from './echo-replicator';
45
+ import { type AutomergeReplicator, type RemoteDocumentExistenceCheckProps } from './echo-replicator';
47
46
  import { HeadsStore } from './heads-store';
48
- import { type BeforeSaveParams, LevelDBStorageAdapter } from './leveldb-storage-adapter';
47
+ import { type BeforeSaveProps, LevelDBStorageAdapter } from './leveldb-storage-adapter';
49
48
 
50
49
  export type PeerIdProvider = () => string | undefined;
51
50
 
52
51
  export type RootDocumentSpaceKeyProvider = (documentId: string) => PublicKey | undefined;
53
52
 
54
- export type AutomergeHostParams = {
53
+ export type AutomergeHostProps = {
55
54
  db: LevelDB;
56
- indexMetadataStore: IndexMetadataStore;
57
55
  dataMonitor?: EchoDataMonitor;
58
56
 
59
57
  /**
@@ -65,6 +63,12 @@ export type AutomergeHostParams = {
65
63
 
66
64
  export type LoadDocOptions = {
67
65
  timeout?: number;
66
+
67
+ /**
68
+ * If true, the document will be fetched from the network if it is not found in the local storage.
69
+ * Setting this to false does not guarantee that the document will not be fetched from the network.
70
+ */
71
+ fetchFromNetwork?: boolean;
68
72
  };
69
73
 
70
74
  export type CreateDocOptions = {
@@ -72,6 +76,8 @@ export type CreateDocOptions = {
72
76
  * Import the document together with its history.
73
77
  */
74
78
  preserveHistory?: boolean;
79
+
80
+ documentId?: DocumentId;
75
81
  };
76
82
 
77
83
  export const FIND_PARAMS = {
@@ -91,13 +97,17 @@ const BUNDLE_SYNC_CONCURRENCY = 2;
91
97
  */
92
98
  const BUNDLE_SYNC_THRESHOLD = 50;
93
99
 
100
+ /**
101
+ * Only announce documents that are known to require sync.
102
+ */
103
+ const OPTIMIZED_SHARE_POLICY = true;
104
+
94
105
  /**
95
106
  * Abstracts over the AutomergeRepo.
96
107
  */
97
- @trace.resource()
108
+ @trace.resource({ lifecycle: true })
98
109
  export class AutomergeHost extends Resource {
99
110
  private readonly _db: LevelDB;
100
- private readonly _indexMetadataStore: IndexMetadataStore;
101
111
  private readonly _echoNetworkAdapter: EchoNetworkAdapter;
102
112
 
103
113
  private readonly _collectionSynchronizer = new CollectionSynchronizer({
@@ -132,15 +142,31 @@ export class AutomergeHost extends Resource {
132
142
  public readonly documentsSaved = new Event();
133
143
 
134
144
  private readonly _headsUpdates = new Map<DocumentId, Heads>();
135
- private _onHeadsChangedTask?: DeferredTask | undefined;
136
-
137
- constructor({
138
- db,
139
- indexMetadataStore,
140
- dataMonitor,
141
- peerIdProvider,
142
- getSpaceKeyByRootDocumentId,
143
- }: AutomergeHostParams) {
145
+ private _onHeadsChangedTask?: DeferredTask;
146
+
147
+ /**
148
+ * Documents created in this session.
149
+ */
150
+ private _createdDocuments = new Set<DocumentId>();
151
+
152
+ /**
153
+ * Documents that need to be synced based on the result of collection-sync.
154
+ */
155
+ private _documentsToSync = new Set<DocumentId>();
156
+
157
+ /**
158
+ * Documents that are not avaiale locally that should be requested.
159
+ */
160
+ private _documentsToRequest = new Set<DocumentId>();
161
+
162
+ /**
163
+ * Documents requested by remote peers.
164
+ */
165
+ private _documentsRequested = new Map<PeerId, Set<DocumentId>>();
166
+
167
+ private _sharePolicyChangedTask?: DeferredTask;
168
+
169
+ constructor({ db, dataMonitor, peerIdProvider, getSpaceKeyByRootDocumentId }: AutomergeHostProps) {
144
170
  super();
145
171
  this._db = db;
146
172
  this._storage = new LevelDBStorageAdapter({
@@ -158,13 +184,16 @@ export class AutomergeHost extends Resource {
158
184
  onCollectionStateReceived: this._onCollectionStateReceived.bind(this),
159
185
  monitor: dataMonitor,
160
186
  });
187
+ this._echoNetworkAdapter.documentRequested.on(({ peerId, documentId }) => {
188
+ defaultMap(this._documentsRequested, peerId, () => new Set()).add(documentId);
189
+ this._sharePolicyChangedTask!.schedule();
190
+ });
161
191
  this._headsStore = new HeadsStore({ db: db.sublevel('heads') });
162
- this._indexMetadataStore = indexMetadataStore;
163
192
  this._peerIdProvider = peerIdProvider;
164
193
  this._getSpaceKeyByRootDocumentId = getSpaceKeyByRootDocumentId;
165
194
  }
166
195
 
167
- protected override async _open(): Promise<void> {
196
+ protected override async _open(ctx: Context): Promise<void> {
168
197
  this._peerId = `host-${this._peerIdProvider?.() ?? PublicKey.random().toHex()}` as PeerId;
169
198
 
170
199
  this._onHeadsChangedTask = new DeferredTask(this._ctx, async () => {
@@ -178,7 +207,7 @@ export class AutomergeHost extends Resource {
178
207
  // Construct the automerge repo.
179
208
  this._repo = new Repo({
180
209
  peerId: this._peerId as PeerId,
181
- sharePolicy: this._sharePolicy.bind(this),
210
+ shareConfig: this._shareConfig,
182
211
  storage: this._storage,
183
212
  network: [
184
213
  // Upstream swarm.
@@ -218,7 +247,7 @@ export class AutomergeHost extends Resource {
218
247
  await Promise.all(
219
248
  collectionToSync.map(async ({ collectionId, peerId }) => {
220
249
  try {
221
- await this._handleCollectionSync(collectionId, peerId);
250
+ await this._handleCollectionSync(this._ctx, collectionId, peerId);
222
251
  } catch (err) {
223
252
  log.error('failed to sync collection', { collectionId, peerId, err });
224
253
  }
@@ -226,25 +255,24 @@ export class AutomergeHost extends Resource {
226
255
  );
227
256
  });
228
257
 
258
+ this._sharePolicyChangedTask = new DeferredTask(this._ctx, async () => {
259
+ log('share policy changed');
260
+ this._repo.shareConfigChanged();
261
+ });
262
+
229
263
  await this._echoNetworkAdapter.open();
230
- await this._collectionSynchronizer.open();
264
+ await this._collectionSynchronizer.open(ctx);
231
265
  await this._echoNetworkAdapter.open();
232
266
  await this._echoNetworkAdapter.whenConnected();
233
267
  }
234
268
 
235
- protected override async _close(): Promise<void> {
236
- await this._collectionSynchronizer.close();
269
+ protected override async _close(ctx: Context): Promise<void> {
270
+ await this._collectionSynchronizer.close(ctx);
237
271
  await this._storage.close?.();
238
272
  await this._echoNetworkAdapter.close();
239
273
  this._syncTask = undefined;
240
274
  this._onHeadsChangedTask = undefined;
241
- }
242
-
243
- /**
244
- * @deprecated To be abstracted away.
245
- */
246
- get repo(): Repo {
247
- return this._repo;
275
+ this._sharePolicyChangedTask = undefined;
248
276
  }
249
277
 
250
278
  get peerId(): PeerId {
@@ -255,12 +283,16 @@ export class AutomergeHost extends Resource {
255
283
  return Object.keys(this._repo.handles).length;
256
284
  }
257
285
 
258
- async addReplicator(replicator: EchoReplicator): Promise<void> {
286
+ get handles(): Readonly<Record<DocumentId, DocHandle<any>>> {
287
+ return this._repo.handles;
288
+ }
289
+
290
+ async addReplicator(ctx: Context, replicator: AutomergeReplicator): Promise<void> {
259
291
  invariant(this.isOpen, 'AutomergeHost is not open');
260
- await this._echoNetworkAdapter.addReplicator(replicator);
292
+ await this._echoNetworkAdapter.addReplicator(ctx, replicator);
261
293
  }
262
294
 
263
- async removeReplicator(replicator: EchoReplicator): Promise<void> {
295
+ async removeReplicator(replicator: AutomergeReplicator): Promise<void> {
264
296
  invariant(this.isOpen, 'AutomergeHost is not open');
265
297
  await this._echoNetworkAdapter.removeReplicator(replicator);
266
298
  }
@@ -276,7 +308,22 @@ export class AutomergeHost extends Resource {
276
308
  handle = this._repo.handles[documentId as DocumentId];
277
309
  }
278
310
  if (!handle) {
279
- handle = await this._repo.find(documentId as DocumentId, FIND_PARAMS);
311
+ if (!opts?.fetchFromNetwork) {
312
+ handle = await this._repo.find(documentId as DocumentId, FIND_PARAMS);
313
+ } else {
314
+ try {
315
+ handle = await this._repo.find(documentId as DocumentId, {
316
+ allowableStates: ['ready', 'requesting', 'unavailable'],
317
+ });
318
+ if (handle.state === 'requesting' || handle.state === 'unavailable') {
319
+ this._documentsToRequest.add(handle.documentId);
320
+ this._sharePolicyChangedTask!.schedule();
321
+ }
322
+ } catch (err) {
323
+ log.error('failed to load document', { documentId, err });
324
+ throw err;
325
+ }
326
+ }
280
327
  }
281
328
 
282
329
  // `whenReady` creates a timeout so we guard it with an if to skip it if the handle is already ready.
@@ -291,7 +338,7 @@ export class AutomergeHost extends Resource {
291
338
  return handle;
292
339
  }
293
340
 
294
- async exportDoc(ctx: Context, id: AnyDocumentId): Promise<Uint8Array> {
341
+ async exportDoc(id: AnyDocumentId): Promise<Uint8Array> {
295
342
  invariant(this.isOpen, 'AutomergeHost is not open');
296
343
  const documentId = interpretAsDocumentId(id);
297
344
 
@@ -302,11 +349,11 @@ export class AutomergeHost extends Resource {
302
349
  /**
303
350
  * Create new persisted document.
304
351
  */
305
- createDoc<T>(initialValue?: T | Doc<T> | Uint8Array, opts?: CreateDocOptions): DocHandle<T> {
352
+ async createDoc<T>(initialValue?: T | Doc<T> | Uint8Array, opts?: CreateDocOptions): Promise<DocHandle<T>> {
306
353
  invariant(this.isOpen, 'AutomergeHost is not open');
307
354
  if (opts?.preserveHistory) {
308
355
  if (initialValue instanceof Uint8Array) {
309
- return this._repo.import(initialValue);
356
+ return this._repo.import(initialValue, { docId: opts?.documentId });
310
357
  }
311
358
 
312
359
  if (!isAutomerge(initialValue)) {
@@ -314,17 +361,26 @@ export class AutomergeHost extends Resource {
314
361
  }
315
362
 
316
363
  // TODO(dmaretskyi): There's a more efficient way.
317
- return this._repo.import(save(initialValue as Doc<T>));
364
+ const handle = this._repo.import(save(initialValue as Doc<T>), { docId: opts?.documentId });
365
+ this._createdDocuments.add(handle.documentId);
366
+ this._sharePolicyChangedTask!.schedule();
367
+ return handle as DocHandle<T>;
318
368
  } else {
319
369
  if (initialValue instanceof Uint8Array) {
320
370
  throw new Error('Cannot create document from Uint8Array without preserving history');
321
371
  }
322
372
 
323
- return this._repo.create(initialValue);
373
+ if (opts?.documentId) {
374
+ throw new Error('Cannot prefil document id when not importing an existing doc');
375
+ }
376
+ const handle = await this._repo.create2<T>(initialValue);
377
+ this._createdDocuments.add(handle.documentId);
378
+ this._sharePolicyChangedTask!.schedule();
379
+ return handle;
324
380
  }
325
381
  }
326
382
 
327
- async waitUntilHeadsReplicated(heads: DocHeadsList): Promise<void> {
383
+ async waitUntilHeadsReplicated(ctx: Context, heads: DocHeadsList): Promise<void> {
328
384
  invariant(this.isOpen, 'AutomergeHost is not open');
329
385
  const entries = heads.entries;
330
386
  if (!entries?.length) {
@@ -343,7 +399,7 @@ export class AutomergeHost extends Resource {
343
399
  if (headsToWait.length > 0) {
344
400
  await Promise.all(
345
401
  headsToWait.map(async (entry) => {
346
- const handle = await this.loadDoc<DatabaseDirectory>(Context.default(), entry.documentId as DocumentId);
402
+ const handle = await this.loadDoc<DatabaseDirectory>(ctx, entry.documentId as DocumentId);
347
403
  await waitForHeads(handle, entry.heads!);
348
404
  }),
349
405
  );
@@ -373,28 +429,42 @@ export class AutomergeHost extends Resource {
373
429
  log('done re-indexing heads');
374
430
  }
375
431
 
376
- // TODO(dmaretskyi): Share based on HALO permissions and space affinity.
377
- // Hosts, running in the worker, don't share documents unless requested by other peers.
378
- // NOTE: If both peers return sharePolicy=false the replication will not happen
379
- // https://github.com/automerge/automerge-repo/pull/292
380
- private async _sharePolicy(peerId: PeerId, documentId?: DocumentId): Promise<boolean> {
381
- if (peerId.startsWith('client-')) {
382
- return false; // Only send docs to clients if they are requested.
383
- }
432
+ private readonly _shareConfig = {
433
+ access: async (peerId: PeerId, documentId: DocumentId): Promise<boolean> => {
434
+ return true;
435
+ },
384
436
 
385
- if (!documentId) {
386
- return false;
387
- }
437
+ // TODO(dmaretskyi): Share based on HALO permissions and space affinity.
438
+ // Hosts, running in the worker, don't share documents unless requested by other peers.
439
+ // NOTE: If both peers return sharePolicy=false the replication will not happen
440
+ // https://github.com/automerge/automerge-repo/pull/292
441
+ // Called for all loaded documents so they could be advertised to the sync server.
442
+ announce: async (peerId: PeerId, documentId?: DocumentId): Promise<boolean> => {
443
+ if (!documentId) {
444
+ return false;
445
+ }
388
446
 
389
- const peerMetadata = this.repo.peerMetadataByPeerId[peerId];
390
- if (isEchoPeerMetadata(peerMetadata)) {
391
- return this._echoNetworkAdapter.shouldAdvertise(peerId, { documentId });
392
- }
447
+ if (OPTIMIZED_SHARE_POLICY) {
448
+ if (
449
+ !this._createdDocuments.has(documentId) &&
450
+ !this._documentsToSync.has(documentId) &&
451
+ !this._documentsToRequest.has(documentId)
452
+ ) {
453
+ // Skip advertising documents that don't need to be synced.
454
+ return false;
455
+ }
456
+ }
393
457
 
394
- return false;
395
- }
458
+ const peerMetadata = this._repo.peerMetadataByPeerId[peerId];
459
+ if (isEchoPeerMetadata(peerMetadata)) {
460
+ return this._echoNetworkAdapter.shouldAdvertise(peerId, { documentId });
461
+ }
462
+
463
+ return false;
464
+ },
465
+ };
396
466
 
397
- private async _beforeSave({ path, batch }: BeforeSaveParams): Promise<void> {
467
+ private async _beforeSave({ path, batch }: BeforeSaveProps): Promise<void> {
398
468
  const handle = this._repo.handles[path[0] as DocumentId];
399
469
  if (!handle || !handle.isReady()) {
400
470
  return;
@@ -406,14 +476,6 @@ export class AutomergeHost extends Resource {
406
476
 
407
477
  const heads = getHeads(doc);
408
478
  this._headsStore.setHeads(handle.documentId, heads, batch);
409
-
410
- const spaceKey = DatabaseDirectory.getSpaceKey(doc) ?? undefined;
411
- const objectIds = Object.keys(doc.objects ?? {});
412
- const encodedIds = objectIds.map((objectId) =>
413
- objectPointerCodec.encode({ documentId: handle.documentId, objectId, spaceKey }),
414
- );
415
- const idToLastHash = new Map(encodedIds.map((id) => [id, heads]));
416
- this._indexMetadataStore.markDirty(idToLastHash, batch);
417
479
  }
418
480
 
419
481
  private _shouldSyncCollection(collectionId: string, peerId: PeerId): boolean {
@@ -433,7 +495,6 @@ export class AutomergeHost extends Resource {
433
495
  return undefined;
434
496
  }
435
497
 
436
- this._indexMetadataStore.notifyMarkedDirty();
437
498
  const documentId = path[0] as DocumentId;
438
499
  const handle = this._repo.handles[documentId];
439
500
  if (!handle || !handle.isReady()) {
@@ -451,12 +512,7 @@ export class AutomergeHost extends Resource {
451
512
  this.documentsSaved.emit();
452
513
  }
453
514
 
454
- @trace.info({ depth: null })
455
- private _automergePeers(): PeerId[] {
456
- return this._repo.peers;
457
- }
458
-
459
- private async _isDocumentInRemoteCollection(params: RemoteDocumentExistenceCheckParams): Promise<boolean> {
515
+ private async _isDocumentInRemoteCollection(params: RemoteDocumentExistenceCheckProps): Promise<boolean> {
460
516
  for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
461
517
  const remoteCollections = this._collectionSynchronizer.getRemoteCollectionStates(collectionId);
462
518
  const remotePeerDocs = remoteCollections.get(params.peerId as PeerId)?.documents;
@@ -494,8 +550,8 @@ export class AutomergeHost extends Resource {
494
550
  /**
495
551
  * Flush documents to disk.
496
552
  */
497
- @trace.span({ showInBrowserTimeline: true })
498
- async flush({ documentIds }: FlushRequest = {}): Promise<void> {
553
+ @trace.span({ showInBrowserTimeline: true, showInRemoteTracing: false })
554
+ async flush(ctx: Context, { documentIds }: FlushRequest = {}): Promise<void> {
499
555
  // Note: Sync protocol for client and services ensures that all handles should have all changes.
500
556
 
501
557
  const loadedDocuments = (documentIds ?? Object.keys(this._repo.handles)).filter(
@@ -505,6 +561,10 @@ export class AutomergeHost extends Resource {
505
561
  },
506
562
  );
507
563
  await this._repo.flush(loadedDocuments);
564
+
565
+ // Ensure that document verions have propagated accross the system.
566
+ // This is important for the case where we are doing flush and then waiting for sync to happen.
567
+ await this._onHeadsChangedTask?.runBlocking();
508
568
  }
509
569
 
510
570
  async getHeads(documentIds: DocumentId[]): Promise<(Heads | undefined)[]> {
@@ -530,6 +590,13 @@ export class AutomergeHost extends Resource {
530
590
  return result;
531
591
  }
532
592
 
593
+ /**
594
+ * Iterate over all document heads stored on disk.
595
+ */
596
+ listDocumentHeads(): AsyncGenerator<{ documentId: DocumentId; heads: Heads }> {
597
+ return this._headsStore.iterateAll();
598
+ }
599
+
533
600
  //
534
601
  // Collection sync.
535
602
  //
@@ -630,7 +697,7 @@ export class AutomergeHost extends Resource {
630
697
  this._syncTask?.schedule();
631
698
  }
632
699
 
633
- private async _handleCollectionSync(collectionId: string, peerId: PeerId) {
700
+ private async _handleCollectionSync(ctx: Context, collectionId: string, peerId: PeerId) {
634
701
  const localState = this._collectionSynchronizer.getLocalCollectionState(collectionId);
635
702
  const remoteState = this._collectionSynchronizer.getRemoteCollectionStates(collectionId).get(peerId);
636
703
 
@@ -648,7 +715,7 @@ export class AutomergeHost extends Resource {
648
715
  const bundleSyncEnabled = this._echoNetworkAdapter.bundleSyncEnabledForPeer(peerId);
649
716
  if (bundleSyncEnabled && missingOnRemote.length >= BUNDLE_SYNC_THRESHOLD) {
650
717
  log('pushing bundle', { amount: missingOnRemote.length });
651
- const { syncInteractively } = await this._pushInBundles(peerId, missingOnRemote);
718
+ const { syncInteractively } = await this._pushInBundles(ctx, peerId, missingOnRemote);
652
719
  toReplicateWithoutBatching.push(...syncInteractively);
653
720
  } else {
654
721
  log.verbose('failed to push bundle, replicating interactively', {
@@ -660,7 +727,7 @@ export class AutomergeHost extends Resource {
660
727
  }
661
728
  if (bundleSyncEnabled && missingOnLocal.length >= BUNDLE_SYNC_THRESHOLD) {
662
729
  log('pulling bundle', { amount: missingOnLocal.length });
663
- const { syncInteractively } = await this._pullInBundles(peerId, missingOnLocal);
730
+ const { syncInteractively } = await this._pullInBundles(ctx, peerId, missingOnLocal);
664
731
  toReplicateWithoutBatching.push(...syncInteractively);
665
732
  } else {
666
733
  log.verbose('failed to pull bundle, replicating interactively', {
@@ -684,13 +751,16 @@ export class AutomergeHost extends Resource {
684
751
 
685
752
  // Load the documents so they will start syncing.
686
753
  for (const documentId of toReplicateWithoutBatching) {
754
+ // Unless we track the document in "to sync" list, it will not be advertised.
755
+ this._documentsToSync!.add(documentId);
687
756
  this._repo.findWithProgress(documentId);
688
757
  }
758
+ this._sharePolicyChangedTask!.schedule();
689
759
  }
690
760
 
691
761
  // TODO(mykola): Add retries of batches https://gist.github.com/mykola-vrmchk/fde270259e9209fcbf1331e5abbf12cf
692
- // TODO(mykola): Use effect to retry batches.
693
762
  private async _pushInBundles(
763
+ ctx: Context,
694
764
  peerId: PeerId,
695
765
  documentIds: DocumentId[],
696
766
  ): Promise<{ syncInteractively: DocumentId[] }> {
@@ -705,7 +775,7 @@ export class AutomergeHost extends Resource {
705
775
  if (bundle.length === 0) {
706
776
  return;
707
777
  }
708
- await this._pushBundle(peerId, bundle).catch((err) => {
778
+ await this._pushBundle(ctx, peerId, bundle).catch((err) => {
709
779
  log.warn('failed to push bundle, replicating interactively', { peerId, bundle, err });
710
780
  syncInteractively.push(...bundle);
711
781
  });
@@ -716,7 +786,7 @@ export class AutomergeHost extends Resource {
716
786
  return { syncInteractively };
717
787
  }
718
788
 
719
- private async _pushBundle(peerId: PeerId, documentIds: DocumentId[]): Promise<void> {
789
+ private async _pushBundle(ctx: Context, peerId: PeerId, documentIds: DocumentId[]): Promise<void> {
720
790
  if (this._ctx.disposed) {
721
791
  return;
722
792
  }
@@ -739,10 +809,11 @@ export class AutomergeHost extends Resource {
739
809
  };
740
810
  });
741
811
 
742
- await this._echoNetworkAdapter.pushBundle(peerId, docs.filter(isNonNullable));
812
+ await this._echoNetworkAdapter.pushBundle(ctx, peerId, docs.filter(isNonNullable));
743
813
  }
744
814
 
745
815
  private async _pullInBundles(
816
+ ctx: Context,
746
817
  peerId: PeerId,
747
818
  documentIds: DocumentId[],
748
819
  ): Promise<{ syncInteractively: DocumentId[] }> {
@@ -758,7 +829,7 @@ export class AutomergeHost extends Resource {
758
829
  if (bundle.length === 0) {
759
830
  return;
760
831
  }
761
- const result = await this._pullBundle(peerId, bundle).catch((err) => {
832
+ const result = await this._pullBundle(ctx, peerId, bundle).catch((err) => {
762
833
  log.warn('failed to pull bundle, replicating interactively', { peerId, bundle, err });
763
834
  syncInteractively.push(...bundle);
764
835
  });
@@ -778,6 +849,7 @@ export class AutomergeHost extends Resource {
778
849
  }
779
850
 
780
851
  private async _pullBundle(
852
+ ctx: Context,
781
853
  peerId: PeerId,
782
854
  documentIds: DocumentId[],
783
855
  ): Promise<{ docsToImport: Record<DocumentId, Uint8Array> } | undefined> {
@@ -786,7 +858,7 @@ export class AutomergeHost extends Resource {
786
858
  }
787
859
  // NOTE: We are expecting that documents that are being pulled are not present locally, so we are pulling all changes.
788
860
  const docHeads = Object.fromEntries(documentIds.map((documentId) => [documentId, []]));
789
- const bundle = await this._echoNetworkAdapter.pullBundle(peerId, docHeads);
861
+ const bundle = await this._echoNetworkAdapter.pullBundle(ctx, peerId, docHeads);
790
862
  return { docsToImport: bundle };
791
863
  }
792
864
 
@@ -795,10 +867,13 @@ export class AutomergeHost extends Resource {
795
867
 
796
868
  for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {
797
869
  const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);
870
+ if (!state) {
871
+ continue;
872
+ }
798
873
  let newState: CollectionState | undefined;
799
874
 
800
875
  for (const [documentId, heads] of docHeads) {
801
- if (state?.documents[documentId]) {
876
+ if (documentId in state.documents) {
802
877
  if (!newState) {
803
878
  newState = structuredClone(state);
804
879
  }