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