@dxos/echo-pipeline 0.6.3-main.9e4e207 → 0.6.3-next.2f65b78

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 (62) hide show
  1. package/dist/lib/browser/{chunk-PEE7MYCZ.mjs → chunk-UJQ5VS5V.mjs} +1790 -3268
  2. package/dist/lib/browser/chunk-UJQ5VS5V.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +1049 -12
  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 +2 -224
  7. package/dist/lib/browser/testing/index.mjs.map +4 -4
  8. package/dist/lib/node/{chunk-RLTLWNAY.cjs → chunk-RH6TDRML.cjs} +783 -2233
  9. package/dist/lib/node/chunk-RH6TDRML.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +1056 -37
  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 +13 -238
  14. package/dist/lib/node/testing/index.cjs.map +4 -4
  15. package/dist/types/src/automerge/automerge-host.d.ts +2 -29
  16. package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
  17. package/dist/types/src/automerge/echo-network-adapter.d.ts +2 -9
  18. package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
  19. package/dist/types/src/automerge/echo-replicator.d.ts +0 -7
  20. package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
  21. package/dist/types/src/automerge/heads-store.d.ts +1 -1
  22. package/dist/types/src/automerge/heads-store.d.ts.map +1 -1
  23. package/dist/types/src/automerge/index.d.ts +0 -2
  24. package/dist/types/src/automerge/index.d.ts.map +1 -1
  25. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +1 -3
  26. package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
  27. package/dist/types/src/automerge/mesh-echo-replicator.d.ts +2 -2
  28. package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
  29. package/dist/types/src/db-host/data-service.d.ts +1 -2
  30. package/dist/types/src/db-host/data-service.d.ts.map +1 -1
  31. package/dist/types/src/testing/index.d.ts +0 -1
  32. package/dist/types/src/testing/index.d.ts.map +1 -1
  33. package/package.json +33 -33
  34. package/src/automerge/automerge-host.test.ts +14 -76
  35. package/src/automerge/automerge-host.ts +30 -217
  36. package/src/automerge/automerge-repo.test.ts +1 -2
  37. package/src/automerge/echo-network-adapter.test.ts +1 -5
  38. package/src/automerge/echo-network-adapter.ts +4 -69
  39. package/src/automerge/echo-replicator.ts +0 -9
  40. package/src/automerge/heads-store.ts +9 -6
  41. package/src/automerge/index.ts +0 -2
  42. package/src/automerge/mesh-echo-replicator-connection.ts +1 -6
  43. package/src/automerge/mesh-echo-replicator.ts +7 -28
  44. package/src/db-host/data-service.ts +12 -26
  45. package/src/testing/index.ts +0 -1
  46. package/dist/lib/browser/chunk-PEE7MYCZ.mjs.map +0 -7
  47. package/dist/lib/node/chunk-RLTLWNAY.cjs.map +0 -7
  48. package/dist/types/src/automerge/collection-synchronizer.d.ts +0 -61
  49. package/dist/types/src/automerge/collection-synchronizer.d.ts.map +0 -1
  50. package/dist/types/src/automerge/collection-synchronizer.test.d.ts +0 -2
  51. package/dist/types/src/automerge/collection-synchronizer.test.d.ts.map +0 -1
  52. package/dist/types/src/automerge/network-protocol.d.ts +0 -31
  53. package/dist/types/src/automerge/network-protocol.d.ts.map +0 -1
  54. package/dist/types/src/automerge/space-collection.d.ts +0 -4
  55. package/dist/types/src/automerge/space-collection.d.ts.map +0 -1
  56. package/dist/types/src/testing/test-replicator.d.ts +0 -46
  57. package/dist/types/src/testing/test-replicator.d.ts.map +0 -1
  58. package/src/automerge/collection-synchronizer.test.ts +0 -91
  59. package/src/automerge/collection-synchronizer.ts +0 -204
  60. package/src/automerge/network-protocol.ts +0 -45
  61. package/src/automerge/space-collection.ts +0 -14
  62. package/src/testing/test-replicator.ts +0 -194
@@ -1,31 +0,0 @@
1
- import type { Message, PeerId } from '@dxos/automerge/automerge-repo';
2
- export declare const MESSAGE_TYPE_COLLECTION_QUERY = "collection-query";
3
- export type CollectionQueryMessage = {
4
- type: typeof MESSAGE_TYPE_COLLECTION_QUERY;
5
- senderId: PeerId;
6
- targetId: PeerId;
7
- collectionId: string;
8
- /**
9
- * Identifier of the current state.
10
- * Remote peer will skip sending the state if it has the same tag.
11
- */
12
- stateTag?: string;
13
- };
14
- export declare const isCollectionQueryMessage: (message: Message) => message is CollectionQueryMessage;
15
- export declare const MESSAGE_TYPE_COLLECTION_STATE = "collection-state";
16
- export type CollectionStateMessage = {
17
- type: typeof MESSAGE_TYPE_COLLECTION_STATE;
18
- senderId: PeerId;
19
- targetId: PeerId;
20
- collectionId: string;
21
- /**
22
- * State representation is implementation-defined.
23
- */
24
- state?: unknown;
25
- /**
26
- * Identifier of the current state.
27
- */
28
- stateTag?: string;
29
- };
30
- export declare const isCollectionStateMessage: (message: Message) => message is CollectionStateMessage;
31
- //# sourceMappingURL=network-protocol.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"network-protocol.d.ts","sourceRoot":"","sources":["../../../../src/automerge/network-protocol.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AAEtE,eAAO,MAAM,6BAA6B,qBAAqB,CAAC;AAEhE,MAAM,MAAM,sBAAsB,GAAG;IACnC,IAAI,EAAE,OAAO,6BAA6B,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,MAAM,wBAAwB,YAAa,OAAO,sCACT,CAAC;AAEjD,eAAO,MAAM,6BAA6B,qBAAqB,CAAC;AAEhE,MAAM,MAAM,sBAAsB,GAAG;IACnC,IAAI,EAAE,OAAO,6BAA6B,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,MAAM,wBAAwB,YAAa,OAAO,sCACT,CAAC"}
@@ -1,4 +0,0 @@
1
- import { SpaceId } from '@dxos/keys';
2
- export declare const deriveCollectionIdFromSpaceId: (spaceId: SpaceId) => string;
3
- export declare const getSpaceIdFromCollectionId: (collectionId: string) => SpaceId;
4
- //# sourceMappingURL=space-collection.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"space-collection.d.ts","sourceRoot":"","sources":["../../../../src/automerge/space-collection.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,eAAO,MAAM,6BAA6B,YAAa,OAAO,KAAG,MAA4B,CAAC;AAE9F,eAAO,MAAM,0BAA0B,iBAAkB,MAAM,KAAG,OAIjE,CAAC"}
@@ -1,46 +0,0 @@
1
- import { type Message } from '@dxos/automerge/automerge-repo';
2
- import { type Context, Resource } from '@dxos/context';
3
- import { type AutomergeReplicatorFactory } from '@dxos/teleport-extension-automerge-replicator';
4
- import type { EchoReplicator, EchoReplicatorContext, ReplicatorConnection, ShouldAdvertiseParams, ShouldSyncCollectionParams } from '../automerge';
5
- export type TestReplicatorNetworkOptions = {
6
- latency?: number;
7
- };
8
- export declare class TestReplicationNetwork extends Resource {
9
- private readonly _replicators;
10
- private readonly _latency?;
11
- constructor(options?: TestReplicatorNetworkOptions);
12
- protected _close(ctx: Context): Promise<void>;
13
- createReplicator(): Promise<TestReplicator>;
14
- private _connectReplicator;
15
- private _disconnectReplicator;
16
- private _createConnectionPair;
17
- }
18
- type TestReplicatorParams = {
19
- onConnect: () => Promise<void>;
20
- onDisconnect: () => Promise<void>;
21
- };
22
- export declare class TestReplicator implements EchoReplicator {
23
- private readonly _params;
24
- constructor(_params: TestReplicatorParams);
25
- connected: boolean;
26
- context: EchoReplicatorContext | undefined;
27
- connections: Set<TestReplicatorConnection>;
28
- connect(context: EchoReplicatorContext): Promise<void>;
29
- disconnect(): Promise<void>;
30
- addConnection(connection: TestReplicatorConnection): Promise<void>;
31
- removeConnection(connection: TestReplicatorConnection): Promise<void>;
32
- }
33
- export declare class TestReplicatorConnection implements ReplicatorConnection {
34
- readonly peerId: string;
35
- readonly readable: ReadableStream<Message>;
36
- readonly writable: WritableStream<Message>;
37
- otherSide: TestReplicatorConnection | undefined;
38
- owningReplicator: TestReplicator | undefined;
39
- constructor(peerId: string, readable: ReadableStream<Message>, writable: WritableStream<Message>);
40
- shouldAdvertise(params: ShouldAdvertiseParams): Promise<boolean>;
41
- shouldSyncCollection(params: ShouldSyncCollectionParams): boolean;
42
- }
43
- export declare const testAutomergeReplicatorFactory: AutomergeReplicatorFactory;
44
- export declare const brokenAutomergeReplicatorFactory: AutomergeReplicatorFactory;
45
- export {};
46
- //# sourceMappingURL=test-replicator.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"test-replicator.d.ts","sourceRoot":"","sources":["../../../../src/testing/test-replicator.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,EAAE,KAAK,OAAO,EAAkB,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGvE,OAAO,EAAuB,KAAK,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAErH,OAAO,KAAK,EACV,cAAc,EACd,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACrB,0BAA0B,EAC3B,MAAM,cAAc,CAAC;AAEtB,MAAM,MAAM,4BAA4B,GAAG;IACzC,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,qBAAa,sBAAuB,SAAQ,QAAQ;IAClD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA6B;IAC1D,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAqB;gBAEnC,OAAO,GAAE,4BAAiC;cAK7B,MAAM,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAStD,gBAAgB,IAAI,OAAO,CAAC,cAAc,CAAC;YAgBnC,kBAAkB;YAelB,qBAAqB;IAOnC,OAAO,CAAC,qBAAqB;CAoC9B;AAED,KAAK,oBAAoB,GAAG;IAC1B,SAAS,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/B,YAAY,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACnC,CAAC;AAEF,qBAAa,cAAe,YAAW,cAAc;IACvC,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,oBAAoB;IAEnD,SAAS,UAAS;IAClB,OAAO,EAAE,qBAAqB,GAAG,SAAS,CAAa;IACvD,WAAW,gCAAuC;IAEnD,OAAO,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAOtD,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAM3B,aAAa,CAAC,UAAU,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;IAMlE,gBAAgB,CAAC,UAAU,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAK5E;AAED,qBAAa,wBAAyB,YAAW,oBAAoB;aAKjD,MAAM,EAAE,MAAM;aACd,QAAQ,EAAE,cAAc,CAAC,OAAO,CAAC;aACjC,QAAQ,EAAE,cAAc,CAAC,OAAO,CAAC;IAN5C,SAAS,EAAE,wBAAwB,GAAG,SAAS,CAAa;IAC5D,gBAAgB,EAAE,cAAc,GAAG,SAAS,CAAa;gBAG9C,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,cAAc,CAAC,OAAO,CAAC,EACjC,QAAQ,EAAE,cAAc,CAAC,OAAO,CAAC;IAG7C,eAAe,CAAC,MAAM,EAAE,qBAAqB,GAAG,OAAO,CAAC,OAAO,CAAC;IAItE,oBAAoB,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO;CAGlE;AAED,eAAO,MAAM,8BAA8B,EAAE,0BAY5C,CAAC;AAEF,eAAO,MAAM,gCAAgC,EAAE,0BAK9C,CAAC"}
@@ -1,91 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { expect } from 'chai';
6
-
7
- import { sleep } from '@dxos/async';
8
- import type { PeerId } from '@dxos/automerge/automerge-repo';
9
- import { afterTest, describe, test } from '@dxos/test';
10
-
11
- import { CollectionSynchronizer, diffCollectionState, type CollectionState } from './collection-synchronizer';
12
-
13
- describe('CollectionSynchronizer', () => {
14
- test('sync two peers', async () => {
15
- const LATENCY = 10;
16
-
17
- const peerId1 = 'peer1' as PeerId;
18
- const peerId2 = 'peer2' as PeerId;
19
- const collectionId = 'collection-test';
20
-
21
- const peer1 = await new CollectionSynchronizer({
22
- queryCollectionState: (collectionId, peerId) =>
23
- queueMicrotask(async () => {
24
- await sleep(LATENCY);
25
- peer2.onCollectionStateQueried(collectionId, peerId);
26
- }),
27
- sendCollectionState: (collectionId, peerId, state) =>
28
- queueMicrotask(async () => {
29
- await sleep(LATENCY);
30
- peer2.onRemoteStateReceived(collectionId, peerId, structuredClone(state));
31
- }),
32
- shouldSyncCollection: () => true,
33
- }).open();
34
- afterTest(() => peer1.close());
35
- const peer2 = await new CollectionSynchronizer({
36
- queryCollectionState: (collectionId, peerId) =>
37
- queueMicrotask(async () => {
38
- await sleep(LATENCY);
39
- peer1.onCollectionStateQueried(collectionId, peerId);
40
- }),
41
- sendCollectionState: (collectionId, peerId, state) =>
42
- queueMicrotask(async () => {
43
- await sleep(LATENCY);
44
- peer1.onRemoteStateReceived(collectionId, peerId, structuredClone(state));
45
- }),
46
- shouldSyncCollection: () => true,
47
- }).open();
48
- afterTest(() => peer2.close());
49
-
50
- peer1.onConnectionOpen(peerId2);
51
- peer2.onConnectionOpen(peerId1);
52
-
53
- peer1.setLocalCollectionState(collectionId, STATE_1);
54
- peer2.setLocalCollectionState(collectionId, STATE_2);
55
-
56
- peer1.refreshCollection(collectionId);
57
- peer2.refreshCollection(collectionId);
58
-
59
- await Promise.all([
60
- peer1.remoteStateUpdated.waitFor((ev) => ev.collectionId === collectionId && ev.peerId === peerId2),
61
- peer2.remoteStateUpdated.waitFor((ev) => ev.collectionId === collectionId && ev.peerId === peerId1),
62
- ]);
63
-
64
- expect(peer1.getRemoteCollectionStates(collectionId).get(peerId2)).to.deep.equal(STATE_2);
65
- expect(peer2.getRemoteCollectionStates(collectionId).get(peerId1)).to.deep.equal(STATE_1);
66
- });
67
-
68
- test('diff collection state', () => {
69
- const diff = diffCollectionState(STATE_1, STATE_2);
70
-
71
- expect(diff).to.deep.equal({
72
- different: ['b', 'c', 'd'],
73
- });
74
- });
75
- });
76
-
77
- const STATE_1: CollectionState = {
78
- documents: {
79
- a: ['1'],
80
- b: ['2'],
81
- c: ['3'],
82
- },
83
- };
84
-
85
- const STATE_2: CollectionState = {
86
- documents: {
87
- a: ['1'],
88
- b: ['4'],
89
- d: ['3'],
90
- },
91
- };
@@ -1,204 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { asyncReturn, Event, scheduleTask, scheduleTaskInterval } from '@dxos/async';
6
- import { next as am } from '@dxos/automerge/automerge';
7
- import type { DocumentId, PeerId } from '@dxos/automerge/automerge-repo';
8
- import { Resource, type Context } from '@dxos/context';
9
- import { defaultMap } from '@dxos/util';
10
-
11
- const MIN_QUERY_INTERVAL = 5_000;
12
-
13
- const POLL_INTERVAL = 30_000;
14
-
15
- export type CollectionSynchronizerParams = {
16
- sendCollectionState: (collectionId: string, peerId: PeerId, state: CollectionState) => void;
17
- queryCollectionState: (collectionId: string, peerId: PeerId) => void;
18
- shouldSyncCollection: (collectionId: string, peerId: PeerId) => boolean;
19
- };
20
-
21
- /**
22
- * Implements collection sync protocol.
23
- */
24
- export class CollectionSynchronizer extends Resource {
25
- private readonly _sendCollectionState: CollectionSynchronizerParams['sendCollectionState'];
26
- private readonly _queryCollectionState: CollectionSynchronizerParams['queryCollectionState'];
27
- private readonly _shouldSyncCollection: CollectionSynchronizerParams['shouldSyncCollection'];
28
-
29
- /**
30
- * CollectionId -> State.
31
- */
32
- private readonly _perCollectionStates = new Map<string, PerCollectionState>();
33
-
34
- private readonly _connectedPeers = new Set<PeerId>();
35
-
36
- public readonly remoteStateUpdated = new Event<{ collectionId: string; peerId: PeerId }>();
37
-
38
- constructor(params: CollectionSynchronizerParams) {
39
- super();
40
- this._sendCollectionState = params.sendCollectionState;
41
- this._queryCollectionState = params.queryCollectionState;
42
- this._shouldSyncCollection = params.shouldSyncCollection;
43
- }
44
-
45
- protected override async _open(ctx: Context): Promise<void> {
46
- scheduleTaskInterval(
47
- this._ctx,
48
- async () => {
49
- for (const collectionId of this._perCollectionStates.keys()) {
50
- this.refreshCollection(collectionId);
51
- await asyncReturn();
52
- }
53
- },
54
- POLL_INTERVAL,
55
- );
56
- }
57
-
58
- getRegisteredCollectionIds(): string[] {
59
- return [...this._perCollectionStates.keys()];
60
- }
61
-
62
- getLocalCollectionState(collectionId: string): CollectionState | undefined {
63
- return this._getPerCollectionState(collectionId).localState;
64
- }
65
-
66
- setLocalCollectionState(collectionId: string, state: CollectionState) {
67
- this._getPerCollectionState(collectionId).localState = state;
68
-
69
- queueMicrotask(async () => {
70
- if (!this._ctx.disposed) {
71
- this._refreshInterestedPeers(collectionId);
72
- this.refreshCollection(collectionId);
73
- }
74
- });
75
- }
76
-
77
- getRemoteCollectionStates(collectionId: string): ReadonlyMap<PeerId, CollectionState> {
78
- return this._getPerCollectionState(collectionId).remoteStates;
79
- }
80
-
81
- refreshCollection(collectionId: string) {
82
- let scheduleAnotherRefresh = false;
83
- const state = this._getPerCollectionState(collectionId);
84
- for (const peerId of this._connectedPeers) {
85
- if (state.interestedPeers.has(peerId)) {
86
- const lastQueried = state.lastQueried.get(peerId) ?? 0;
87
- if (Date.now() - lastQueried > MIN_QUERY_INTERVAL) {
88
- state.lastQueried.set(peerId, Date.now());
89
- this._queryCollectionState(collectionId, peerId);
90
- } else {
91
- scheduleAnotherRefresh = true;
92
- }
93
- }
94
- }
95
- if (scheduleAnotherRefresh) {
96
- scheduleTask(this._ctx, () => this.refreshCollection(collectionId), MIN_QUERY_INTERVAL);
97
- }
98
- }
99
-
100
- /**
101
- * Callback when a connection to a peer is established.
102
- */
103
- onConnectionOpen(peerId: PeerId) {
104
- this._connectedPeers.add(peerId);
105
-
106
- queueMicrotask(async () => {
107
- if (this._ctx.disposed) {
108
- return;
109
- }
110
- for (const [collectionId, state] of this._perCollectionStates.entries()) {
111
- if (this._shouldSyncCollection(collectionId, peerId)) {
112
- state.interestedPeers.add(peerId);
113
- state.lastQueried.set(peerId, Date.now());
114
- this._queryCollectionState(collectionId, peerId);
115
- }
116
- }
117
- });
118
- }
119
-
120
- /**
121
- * Callback when a connection to a peer is closed.
122
- */
123
- onConnectionClosed(peerId: PeerId) {
124
- this._connectedPeers.delete(peerId);
125
-
126
- for (const perCollectionState of this._perCollectionStates.values()) {
127
- perCollectionState.remoteStates.delete(peerId);
128
- }
129
- }
130
-
131
- /**
132
- * Callback when a peer queries the state of a collection.
133
- */
134
- onCollectionStateQueried(collectionId: string, peerId: PeerId) {
135
- const perCollectionState = this._getPerCollectionState(collectionId);
136
-
137
- if (perCollectionState.localState) {
138
- this._sendCollectionState(collectionId, peerId, perCollectionState.localState);
139
- }
140
- }
141
-
142
- /**
143
- * Callback when a peer sends the state of a collection.
144
- */
145
- onRemoteStateReceived(collectionId: string, peerId: PeerId, state: CollectionState) {
146
- const perCollectionState = this._getPerCollectionState(collectionId);
147
- perCollectionState.remoteStates.set(peerId, state);
148
- this.remoteStateUpdated.emit({ peerId, collectionId });
149
- }
150
-
151
- private _getPerCollectionState(collectionId: string): PerCollectionState {
152
- return defaultMap(this._perCollectionStates, collectionId, () => ({
153
- localState: undefined,
154
- remoteStates: new Map(),
155
- interestedPeers: new Set(),
156
- lastQueried: new Map(),
157
- }));
158
- }
159
-
160
- private _refreshInterestedPeers(collectionId: string) {
161
- for (const peerId of this._connectedPeers) {
162
- if (this._shouldSyncCollection(collectionId, peerId)) {
163
- this._getPerCollectionState(collectionId).interestedPeers.add(peerId);
164
- } else {
165
- this._getPerCollectionState(collectionId).interestedPeers.delete(peerId);
166
- }
167
- }
168
- }
169
- }
170
-
171
- type PerCollectionState = {
172
- localState?: CollectionState;
173
- remoteStates: Map<PeerId, CollectionState>;
174
- interestedPeers: Set<PeerId>;
175
- lastQueried: Map<PeerId, number>;
176
- };
177
-
178
- export type CollectionState = {
179
- /**
180
- * DocumentId -> Heads.
181
- */
182
- documents: Record<string, string[]>;
183
- };
184
-
185
- export type CollectionStateDiff = {
186
- different: DocumentId[];
187
- };
188
-
189
- export const diffCollectionState = (local: CollectionState, remote: CollectionState): CollectionStateDiff => {
190
- const allDocuments = new Set<DocumentId>([...Object.keys(local.documents), ...Object.keys(remote.documents)] as any);
191
-
192
- const different: DocumentId[] = [];
193
- for (const documentId of allDocuments) {
194
- if (
195
- !local.documents[documentId] ||
196
- !remote.documents[documentId] ||
197
- !am.equals(local.documents[documentId], remote.documents[documentId])
198
- ) {
199
- different.push(documentId as DocumentId);
200
- }
201
- }
202
-
203
- return { different };
204
- };
@@ -1,45 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import type { Message, PeerId } from '@dxos/automerge/automerge-repo';
6
-
7
- export const MESSAGE_TYPE_COLLECTION_QUERY = 'collection-query';
8
-
9
- export type CollectionQueryMessage = {
10
- type: typeof MESSAGE_TYPE_COLLECTION_QUERY;
11
- senderId: PeerId;
12
- targetId: PeerId;
13
- collectionId: string;
14
-
15
- /**
16
- * Identifier of the current state.
17
- * Remote peer will skip sending the state if it has the same tag.
18
- */
19
- stateTag?: string;
20
- };
21
-
22
- export const isCollectionQueryMessage = (message: Message): message is CollectionQueryMessage =>
23
- message.type === MESSAGE_TYPE_COLLECTION_QUERY;
24
-
25
- export const MESSAGE_TYPE_COLLECTION_STATE = 'collection-state';
26
-
27
- export type CollectionStateMessage = {
28
- type: typeof MESSAGE_TYPE_COLLECTION_STATE;
29
- senderId: PeerId;
30
- targetId: PeerId;
31
- collectionId: string;
32
-
33
- /**
34
- * State representation is implementation-defined.
35
- */
36
- state?: unknown;
37
-
38
- /**
39
- * Identifier of the current state.
40
- */
41
- stateTag?: string;
42
- };
43
-
44
- export const isCollectionStateMessage = (message: Message): message is CollectionStateMessage =>
45
- message.type === MESSAGE_TYPE_COLLECTION_STATE;
@@ -1,14 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { invariant } from '@dxos/invariant';
6
- import { SpaceId } from '@dxos/keys';
7
-
8
- export const deriveCollectionIdFromSpaceId = (spaceId: SpaceId): string => `space:${spaceId}`;
9
-
10
- export const getSpaceIdFromCollectionId = (collectionId: string): SpaceId => {
11
- const spaceId = collectionId.replace(/^space:/, '');
12
- invariant(SpaceId.isValid(spaceId));
13
- return spaceId;
14
- };
@@ -1,194 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { sleep, synchronized } from '@dxos/async';
6
- import { type Message } from '@dxos/automerge/automerge-repo';
7
- import { type Context, LifecycleState, Resource } from '@dxos/context';
8
- import { invariant } from '@dxos/invariant';
9
- import { log } from '@dxos/log';
10
- import { AutomergeReplicator, type AutomergeReplicatorFactory } from '@dxos/teleport-extension-automerge-replicator';
11
-
12
- import type {
13
- EchoReplicator,
14
- EchoReplicatorContext,
15
- ReplicatorConnection,
16
- ShouldAdvertiseParams,
17
- ShouldSyncCollectionParams,
18
- } from '../automerge';
19
-
20
- export type TestReplicatorNetworkOptions = {
21
- latency?: number;
22
- };
23
-
24
- export class TestReplicationNetwork extends Resource {
25
- private readonly _replicators = new Set<TestReplicator>();
26
- private readonly _latency?: number = undefined;
27
-
28
- constructor(options: TestReplicatorNetworkOptions = {}) {
29
- super();
30
- this._latency = options.latency;
31
- }
32
-
33
- protected override async _close(ctx: Context): Promise<void> {
34
- for (const replicator of this._replicators) {
35
- for (const connection of replicator.connections) {
36
- void connection.writable.abort();
37
- void connection.readable.cancel();
38
- }
39
- }
40
- }
41
-
42
- async createReplicator(): Promise<TestReplicator> {
43
- const replicator = new TestReplicator({
44
- onConnect: async () => {
45
- invariant(this._lifecycleState === LifecycleState.OPEN);
46
- await this._connectReplicator(replicator);
47
- },
48
- onDisconnect: async () => {
49
- invariant(this._lifecycleState === LifecycleState.OPEN);
50
- await this._disconnectReplicator(replicator);
51
- },
52
- });
53
- this._replicators.add(replicator);
54
- return replicator;
55
- }
56
-
57
- @synchronized
58
- private async _connectReplicator(replicator: TestReplicator) {
59
- for (const otherReplicator of this._replicators.values()) {
60
- if (otherReplicator === replicator || !otherReplicator.connected) {
61
- continue;
62
- }
63
- log('create connection', { from: replicator.context!.peerId, to: otherReplicator.context!.peerId });
64
- const [connection1, connection2] = this._createConnectionPair(
65
- replicator.context!.peerId,
66
- otherReplicator.context!.peerId,
67
- );
68
- await replicator.context!.onConnectionOpen(connection1);
69
- await otherReplicator.context!.onConnectionOpen(connection2);
70
- }
71
- }
72
-
73
- private async _disconnectReplicator(replicator: TestReplicator) {
74
- for (const connection of replicator.connections) {
75
- await replicator.context!.onConnectionClosed(connection);
76
- await connection.otherSide!.owningReplicator!.removeConnection(connection.otherSide!);
77
- }
78
- }
79
-
80
- private _createConnectionPair(peer1: string, peer2: string): [TestReplicatorConnection, TestReplicatorConnection] {
81
- const LOG = false;
82
-
83
- const forward = new TransformStream({
84
- transform: async (message, controller) => {
85
- if (LOG) {
86
- log.info('replicate', { from: peer1, to: peer2, message });
87
- }
88
-
89
- if (this._latency !== undefined) {
90
- await sleep(this._latency);
91
- }
92
-
93
- controller.enqueue(message);
94
- },
95
- });
96
- const backwards = new TransformStream({
97
- transform: async (message, controller) => {
98
- if (LOG) {
99
- log.info('replicate', { from: peer2, to: peer1, message });
100
- }
101
-
102
- if (this._latency !== undefined) {
103
- await sleep(this._latency);
104
- }
105
-
106
- controller.enqueue(message);
107
- },
108
- });
109
-
110
- const connection1 = new TestReplicatorConnection(peer2, backwards.readable, forward.writable);
111
- const connection2 = new TestReplicatorConnection(peer1, forward.readable, backwards.writable);
112
- connection1.otherSide = connection2;
113
- connection2.otherSide = connection1;
114
- return [connection1, connection2];
115
- }
116
- }
117
-
118
- type TestReplicatorParams = {
119
- onConnect: () => Promise<void>;
120
- onDisconnect: () => Promise<void>;
121
- };
122
-
123
- export class TestReplicator implements EchoReplicator {
124
- constructor(private readonly _params: TestReplicatorParams) {}
125
-
126
- public connected = false;
127
- public context: EchoReplicatorContext | undefined = undefined;
128
- public connections = new Set<TestReplicatorConnection>();
129
-
130
- async connect(context: EchoReplicatorContext): Promise<void> {
131
- log('connect', { peerId: context.peerId });
132
- this.context = context;
133
- this.connected = true;
134
- await this._params.onConnect();
135
- }
136
-
137
- async disconnect(): Promise<void> {
138
- log('disconnect', { peerId: this.context!.peerId });
139
- this.connected = false;
140
- await this._params.onDisconnect();
141
- }
142
-
143
- async addConnection(connection: TestReplicatorConnection): Promise<void> {
144
- connection.owningReplicator = this;
145
- this.connections.add(connection);
146
- this.context!.onConnectionOpen(connection);
147
- }
148
-
149
- async removeConnection(connection: TestReplicatorConnection): Promise<void> {
150
- connection.owningReplicator = undefined;
151
- this.context!.onConnectionClosed(connection);
152
- this.connections.delete(connection);
153
- }
154
- }
155
-
156
- export class TestReplicatorConnection implements ReplicatorConnection {
157
- public otherSide: TestReplicatorConnection | undefined = undefined;
158
- public owningReplicator: TestReplicator | undefined = undefined;
159
-
160
- constructor(
161
- public readonly peerId: string,
162
- public readonly readable: ReadableStream<Message>,
163
- public readonly writable: WritableStream<Message>,
164
- ) {}
165
-
166
- async shouldAdvertise(params: ShouldAdvertiseParams): Promise<boolean> {
167
- return true;
168
- }
169
-
170
- shouldSyncCollection(params: ShouldSyncCollectionParams): boolean {
171
- return true;
172
- }
173
- }
174
-
175
- export const testAutomergeReplicatorFactory: AutomergeReplicatorFactory = (params) => {
176
- return new AutomergeReplicator(
177
- {
178
- ...params[0],
179
- sendSyncRetryPolicy: {
180
- retryBackoff: 20,
181
- retriesBeforeBackoff: 2,
182
- maxRetries: 3,
183
- },
184
- },
185
- params[1],
186
- );
187
- };
188
-
189
- export const brokenAutomergeReplicatorFactory: AutomergeReplicatorFactory = (params) => {
190
- params[1]!.onSyncMessage = () => {
191
- throw new Error();
192
- };
193
- return testAutomergeReplicatorFactory(params);
194
- };