@party-stack/runtime 0.4.0 → 0.4.1
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/lib/coordinator/createPersistedCollectionCoordinator.d.ts +4 -2
- package/lib/coordinator/createPersistedCollectionCoordinator.d.ts.map +1 -1
- package/lib/coordinator/createPersistedCollectionCoordinator.js +491 -555
- package/lib/coordinator/createPersistedCollectionCoordinator.js.map +1 -1
- package/lib/coordinator/index.d.ts +2 -2
- package/lib/coordinator/index.js +2 -2
- package/lib/effection/index.d.ts +4 -2
- package/lib/effection/index.d.ts.map +1 -1
- package/lib/effection/index.js +25 -25
- package/lib/effection/index.js.map +1 -1
- package/lib/index.d.ts +11 -11
- package/lib/index.js +10 -9
- package/lib/memory/MemoryBlobBytesStore.d.ts +8 -6
- package/lib/memory/MemoryBlobBytesStore.d.ts.map +1 -1
- package/lib/memory/MemoryBlobBytesStore.js +22 -20
- package/lib/memory/MemoryBlobBytesStore.js.map +1 -1
- package/lib/types.d.ts +31 -29
- package/lib/types.d.ts.map +1 -1
- package/lib/types.js +0 -1
- package/lib/utils/BrowserAuthenticationCancelledError.d.ts +3 -1
- package/lib/utils/BrowserAuthenticationCancelledError.d.ts.map +1 -1
- package/lib/utils/BrowserAuthenticationCancelledError.js +10 -6
- package/lib/utils/BrowserAuthenticationCancelledError.js.map +1 -1
- package/lib/utils/createCollectionPersistence.d.ts +4 -2
- package/lib/utils/createCollectionPersistence.d.ts.map +1 -1
- package/lib/utils/createCollectionPersistence.js +20 -16
- package/lib/utils/createCollectionPersistence.js.map +1 -1
- package/lib/utils/createDefaultRuntime.d.ts +4 -1
- package/lib/utils/createDefaultRuntime.d.ts.map +1 -1
- package/lib/utils/createDefaultRuntime.js +15 -11
- package/lib/utils/createDefaultRuntime.js.map +1 -1
- package/lib/utils/createLocalCollection.d.ts +8 -6
- package/lib/utils/createLocalCollection.d.ts.map +1 -1
- package/lib/utils/createLocalCollection.js +19 -15
- package/lib/utils/createLocalCollection.js.map +1 -1
- package/lib/utils/defineRuntime.d.ts +3 -2
- package/lib/utils/defineRuntime.d.ts.map +1 -1
- package/lib/utils/defineRuntime.js +26 -30
- package/lib/utils/defineRuntime.js.map +1 -1
- package/package.json +8 -14
- package/lib/coordinator/index.d.ts.map +0 -1
- package/lib/coordinator/index.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/memory/MemoryBlobBytesStore.test.d.ts +0 -2
- package/lib/memory/MemoryBlobBytesStore.test.d.ts.map +0 -1
- package/lib/memory/MemoryBlobBytesStore.test.js +0 -12
- package/lib/memory/MemoryBlobBytesStore.test.js.map +0 -1
- package/lib/types.js.map +0 -1
- package/lib/utils/createLocalCollection.test.d.ts +0 -2
- package/lib/utils/createLocalCollection.test.d.ts.map +0 -1
- package/lib/utils/createLocalCollection.test.js +0 -748
- package/lib/utils/createLocalCollection.test.js.map +0 -1
- package/lib/utils/defineRuntime.test.d.ts +0 -2
- package/lib/utils/defineRuntime.test.d.ts.map +0 -1
- package/lib/utils/defineRuntime.test.js +0 -40
- package/lib/utils/defineRuntime.test.js.map +0 -1
|
@@ -1,563 +1,499 @@
|
|
|
1
|
-
import { isCoordinationHost
|
|
2
|
-
import {
|
|
1
|
+
import { isCoordinationHost } from "@party-stack/coordination";
|
|
2
|
+
import { SingleProcessCoordinator, safeRandomUUID, toPersistedCollectionDurabilityError, toTransportedLoadSubsetOptions } from "@tanstack/db-sqlite-persistence-core";
|
|
3
|
+
//#region src/coordinator/createPersistedCollectionCoordinator.ts
|
|
3
4
|
const PERSISTENCE_SERVICE = "party-stack.persistence.v1";
|
|
4
|
-
const MAX_DEDUPLICATION_ENTRIES =
|
|
5
|
-
const MAX_PENDING_RELAYS =
|
|
5
|
+
const MAX_DEDUPLICATION_ENTRIES = 1e3;
|
|
6
|
+
const MAX_PENDING_RELAYS = 1e3;
|
|
6
7
|
const MAX_COLLECTION_POSITIONS = 128;
|
|
7
|
-
const coordinatorCache = new WeakMap();
|
|
8
|
+
const coordinatorCache = /* @__PURE__ */ new WeakMap();
|
|
8
9
|
function isRecord(value) {
|
|
9
|
-
|
|
10
|
+
return typeof value === "object" && value !== null;
|
|
10
11
|
}
|
|
11
12
|
function relayKey(collectionId, message) {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
13
|
+
const payload = isRecord(message.payload) ? message.payload : {};
|
|
14
|
+
return JSON.stringify([
|
|
15
|
+
collectionId,
|
|
16
|
+
message.senderId,
|
|
17
|
+
payload.type,
|
|
18
|
+
payload.txId,
|
|
19
|
+
payload.resetEpoch,
|
|
20
|
+
payload.term,
|
|
21
|
+
payload.seq
|
|
22
|
+
]);
|
|
22
23
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
return created;
|
|
35
|
-
}
|
|
36
|
-
class CoordinationPersistenceShim {
|
|
37
|
-
coordination;
|
|
38
|
-
adapter;
|
|
39
|
-
nodeId = safeRandomUUID();
|
|
40
|
-
collectionAdapters = new Map();
|
|
41
|
-
collectionSubscriptions = new Map();
|
|
42
|
-
resumeChecks = new Map();
|
|
43
|
-
localMutationBursts = new Map();
|
|
44
|
-
stopResumeListeners;
|
|
45
|
-
checkingResume = false;
|
|
46
|
-
resumeRequested = false;
|
|
47
|
-
requestResumeCheck = () => {
|
|
48
|
-
this.resumeRequested = true;
|
|
49
|
-
if (this.checkingResume)
|
|
50
|
-
return;
|
|
51
|
-
this.checkingResume = true;
|
|
52
|
-
void (async () => {
|
|
53
|
-
try {
|
|
54
|
-
while (this.resumeRequested && this.resumeChecks.size > 0) {
|
|
55
|
-
this.resumeRequested = false;
|
|
56
|
-
await Promise.all([...this.resumeChecks.values()].flatMap((checks) => [...checks].map((check) => check())));
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
finally {
|
|
60
|
-
this.checkingResume = false;
|
|
61
|
-
this.resumeRequested = false;
|
|
62
|
-
}
|
|
63
|
-
})();
|
|
64
|
-
};
|
|
65
|
-
startResumeListeners() {
|
|
66
|
-
if (this.stopResumeListeners || typeof window === "undefined" || typeof document === "undefined")
|
|
67
|
-
return;
|
|
68
|
-
const page = window;
|
|
69
|
-
const visibility = document;
|
|
70
|
-
const onVisible = () => {
|
|
71
|
-
if (visibility.visibilityState === "visible")
|
|
72
|
-
this.requestResumeCheck();
|
|
73
|
-
};
|
|
74
|
-
page.addEventListener("pageshow", this.requestResumeCheck);
|
|
75
|
-
page.addEventListener("focus", onVisible);
|
|
76
|
-
visibility.addEventListener("visibilitychange", onVisible);
|
|
77
|
-
this.stopResumeListeners = () => {
|
|
78
|
-
page.removeEventListener("pageshow", this.requestResumeCheck);
|
|
79
|
-
page.removeEventListener("focus", onVisible);
|
|
80
|
-
visibility.removeEventListener("visibilitychange", onVisible);
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
setAdapterForCollection(collectionId, adapter) {
|
|
84
|
-
this.collectionAdapters.set(collectionId, adapter);
|
|
85
|
-
this.positions.delete(collectionId);
|
|
86
|
-
}
|
|
87
|
-
adapterForCollection(collectionId, schemaVersion) {
|
|
88
|
-
const adapter = this.collectionAdapters.get(collectionId) ?? this.adapter;
|
|
89
|
-
if (schemaVersion !== undefined && this.schemaVersion(adapter) !== schemaVersion) {
|
|
90
|
-
throw new Error(`Persistence schema mismatch for collection "${collectionId}". Reload the coordination host before writing through another schema version.`);
|
|
91
|
-
}
|
|
92
|
-
return adapter;
|
|
93
|
-
}
|
|
94
|
-
schemaVersion(adapter) {
|
|
95
|
-
return "schemaVersion" in adapter && typeof adapter.schemaVersion === "number"
|
|
96
|
-
? adapter.schemaVersion
|
|
97
|
-
: undefined;
|
|
98
|
-
}
|
|
99
|
-
positions = new Map();
|
|
100
|
-
appliedEnvelopes = new Map();
|
|
101
|
-
relayedMessages = new Set();
|
|
102
|
-
service;
|
|
103
|
-
server;
|
|
104
|
-
pendingRelays = 0;
|
|
105
|
-
remoteSubsets = new SingleProcessCoordinator();
|
|
106
|
-
acquisitionIds = new WeakMap();
|
|
107
|
-
remoteAcquisitions = new Map();
|
|
108
|
-
constructor(coordination, adapter) {
|
|
109
|
-
this.coordination = coordination;
|
|
110
|
-
this.adapter = adapter;
|
|
111
|
-
this.service = coordination.service(PERSISTENCE_SERVICE);
|
|
112
|
-
this.server = isCoordinationHost(coordination)
|
|
113
|
-
? coordination.serve(PERSISTENCE_SERVICE, {
|
|
114
|
-
ensureLeadership: () => Promise.resolve(),
|
|
115
|
-
ensureRemoteSubset: async (input) => {
|
|
116
|
-
let options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
|
|
117
|
-
if (!options) {
|
|
118
|
-
options = input.options;
|
|
119
|
-
this.remoteAcquisitions.set(input.acquisitionId, {
|
|
120
|
-
collectionId: input.collectionId,
|
|
121
|
-
options,
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
try {
|
|
125
|
-
await this.remoteSubsets.requestEnsureRemoteSubset(input.collectionId, options);
|
|
126
|
-
}
|
|
127
|
-
catch (error) {
|
|
128
|
-
// Owner invocation transfers a lease even if loading fails.
|
|
129
|
-
// Release it before dropping our strong reference to its options.
|
|
130
|
-
if (this.remoteAcquisitions.get(input.acquisitionId)?.options === options) {
|
|
131
|
-
this.remoteAcquisitions.delete(input.acquisitionId);
|
|
132
|
-
await this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options)
|
|
133
|
-
.catch(() => undefined);
|
|
134
|
-
}
|
|
135
|
-
throw error;
|
|
136
|
-
}
|
|
137
|
-
},
|
|
138
|
-
releaseRemoteSubset: (input) => {
|
|
139
|
-
const options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
|
|
140
|
-
this.remoteAcquisitions.delete(input.acquisitionId);
|
|
141
|
-
return options
|
|
142
|
-
? this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options)
|
|
143
|
-
: Promise.resolve();
|
|
144
|
-
},
|
|
145
|
-
applyCommittedTx: (input) => this.applyCommittedTx(input),
|
|
146
|
-
ensurePersistedIndex: (input) => this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(input.collectionId, input.signature, input.spec),
|
|
147
|
-
applyLocalMutations: (input) => this.applyMutations(input),
|
|
148
|
-
pullSince: (input) => this.handlePullSince(input),
|
|
149
|
-
relayMessage: (input) => this.relayMessage(input),
|
|
150
|
-
})
|
|
151
|
-
: undefined;
|
|
152
|
-
}
|
|
153
|
-
getNodeId() {
|
|
154
|
-
return this.nodeId;
|
|
155
|
-
}
|
|
156
|
-
subscribe(collectionId, callback) {
|
|
157
|
-
let active = true;
|
|
158
|
-
let observed;
|
|
159
|
-
const unsubscribe = this.service.events.subscribe("message", (event) => {
|
|
160
|
-
if (!active)
|
|
161
|
-
return;
|
|
162
|
-
if (event.collectionId === collectionId) {
|
|
163
|
-
const payload = event.message.payload;
|
|
164
|
-
const burst = this.localMutationBursts.get(collectionId);
|
|
165
|
-
if (burst && isRecord(payload) && payload.type === "tx:committed" &&
|
|
166
|
-
typeof payload.txId === "string" && !burst.pending.has(payload.txId)) {
|
|
167
|
-
burst.needsReload = true;
|
|
168
|
-
}
|
|
169
|
-
if (isRecord(payload) && payload.type === "tx:committed" &&
|
|
170
|
-
typeof payload.term === "number" && typeof payload.seq === "number" &&
|
|
171
|
-
typeof payload.latestRowVersion === "number" &&
|
|
172
|
-
(!observed || payload.term > observed.latestTerm ||
|
|
173
|
-
(payload.term === observed.latestTerm && payload.seq > observed.latestSeq))) {
|
|
174
|
-
observed = { latestTerm: payload.term, latestSeq: payload.seq, latestRowVersion: payload.latestRowVersion };
|
|
175
|
-
}
|
|
176
|
-
callback(event.message);
|
|
177
|
-
}
|
|
178
|
-
});
|
|
179
|
-
const checkResume = async (force = false) => {
|
|
180
|
-
try {
|
|
181
|
-
if (!active)
|
|
182
|
-
return;
|
|
183
|
-
const adapter = this.adapterForCollection(collectionId);
|
|
184
|
-
const current = await adapter.getStreamPosition?.(collectionId);
|
|
185
|
-
if (!active)
|
|
186
|
-
return;
|
|
187
|
-
if (!force && current && observed && current.latestTerm === observed.latestTerm &&
|
|
188
|
-
current.latestSeq === observed.latestSeq && current.latestRowVersion === observed.latestRowVersion)
|
|
189
|
-
return;
|
|
190
|
-
// A local reset notification makes upstream reload active subsets atomically.
|
|
191
|
-
// No storage reset or broadcast is performed. Before our first notification,
|
|
192
|
-
// the hydration position is unknown, so a resume conservatively reloads once.
|
|
193
|
-
callback({
|
|
194
|
-
v: 1, dbName: this.coordinationScope(), collectionId,
|
|
195
|
-
senderId: `resume:${this.nodeId}`, ts: Date.now(),
|
|
196
|
-
payload: { type: "collection:reset", schemaVersion: this.schemaVersion(adapter) ?? 1, resetEpoch: 0 },
|
|
197
|
-
});
|
|
198
|
-
observed = current;
|
|
199
|
-
}
|
|
200
|
-
catch (error) {
|
|
201
|
-
if (active)
|
|
202
|
-
console.warn(`Failed to refresh resumed collection "${collectionId}".`, error);
|
|
203
|
-
}
|
|
204
|
-
};
|
|
205
|
-
const checks = this.resumeChecks.get(collectionId) ?? new Set();
|
|
206
|
-
checks.add(checkResume);
|
|
207
|
-
this.resumeChecks.set(collectionId, checks);
|
|
208
|
-
this.startResumeListeners();
|
|
209
|
-
this.collectionSubscriptions.set(collectionId, (this.collectionSubscriptions.get(collectionId) ?? 0) + 1);
|
|
210
|
-
return () => {
|
|
211
|
-
if (!active)
|
|
212
|
-
return;
|
|
213
|
-
active = false;
|
|
214
|
-
checks.delete(checkResume);
|
|
215
|
-
if (checks.size === 0) {
|
|
216
|
-
this.resumeChecks.delete(collectionId);
|
|
217
|
-
const burst = this.localMutationBursts.get(collectionId);
|
|
218
|
-
if (burst?.timer !== undefined)
|
|
219
|
-
clearTimeout(burst.timer);
|
|
220
|
-
this.localMutationBursts.delete(collectionId);
|
|
221
|
-
}
|
|
222
|
-
if (this.resumeChecks.size === 0) {
|
|
223
|
-
this.stopResumeListeners?.();
|
|
224
|
-
this.stopResumeListeners = undefined;
|
|
225
|
-
}
|
|
226
|
-
try {
|
|
227
|
-
unsubscribe();
|
|
228
|
-
}
|
|
229
|
-
finally {
|
|
230
|
-
const remaining = this.collectionSubscriptions.get(collectionId) - 1;
|
|
231
|
-
if (remaining > 0) {
|
|
232
|
-
this.collectionSubscriptions.set(collectionId, remaining);
|
|
233
|
-
}
|
|
234
|
-
else {
|
|
235
|
-
this.collectionSubscriptions.delete(collectionId);
|
|
236
|
-
this.collectionAdapters.delete(collectionId);
|
|
237
|
-
this.positions.delete(collectionId);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
}
|
|
242
|
-
publish(collectionId, message) {
|
|
243
|
-
if (this.server && isCoordinationHost(this.coordination) && this.coordination.isLeader) {
|
|
244
|
-
this.publishMessage({
|
|
245
|
-
collectionId,
|
|
246
|
-
message,
|
|
247
|
-
});
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
if (this.pendingRelays >= MAX_PENDING_RELAYS) {
|
|
251
|
-
console.warn(`Dropping persistence relay for "${collectionId}" because the pending relay limit was reached.`);
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
this.pendingRelays += 1;
|
|
255
|
-
void this.service.methods
|
|
256
|
-
.relayMessage({
|
|
257
|
-
collectionId,
|
|
258
|
-
message,
|
|
259
|
-
})
|
|
260
|
-
.catch((error) => {
|
|
261
|
-
console.warn(`Failed to relay persistence message for "${collectionId}".`, error);
|
|
262
|
-
})
|
|
263
|
-
.finally(() => {
|
|
264
|
-
this.pendingRelays -= 1;
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
isLeader() {
|
|
268
|
-
return isCoordinationHost(this.coordination) && this.coordination.isLeader;
|
|
269
|
-
}
|
|
270
|
-
ensureLeadership() {
|
|
271
|
-
return this.service.methods.ensureLeadership({
|
|
272
|
-
collectionId: "*",
|
|
273
|
-
});
|
|
274
|
-
}
|
|
275
|
-
requestEnsureRemoteSubset(collectionId, options) {
|
|
276
|
-
let collectionIds = this.acquisitionIds.get(options);
|
|
277
|
-
if (!collectionIds) {
|
|
278
|
-
collectionIds = new Map();
|
|
279
|
-
this.acquisitionIds.set(options, collectionIds);
|
|
280
|
-
}
|
|
281
|
-
let acquisitionId = collectionIds.get(collectionId);
|
|
282
|
-
if (!acquisitionId) {
|
|
283
|
-
acquisitionId = safeRandomUUID();
|
|
284
|
-
collectionIds.set(collectionId, acquisitionId);
|
|
285
|
-
}
|
|
286
|
-
return this.service.methods.ensureRemoteSubset({
|
|
287
|
-
collectionId,
|
|
288
|
-
options: toTransportedLoadSubsetOptions(options),
|
|
289
|
-
acquisitionId,
|
|
290
|
-
});
|
|
291
|
-
}
|
|
292
|
-
requestReleaseRemoteSubset(collectionId, options) {
|
|
293
|
-
const collectionIds = this.acquisitionIds.get(options);
|
|
294
|
-
const acquisitionId = collectionIds?.get(collectionId);
|
|
295
|
-
if (!acquisitionId)
|
|
296
|
-
return Promise.resolve();
|
|
297
|
-
collectionIds.delete(collectionId);
|
|
298
|
-
if (collectionIds.size === 0)
|
|
299
|
-
this.acquisitionIds.delete(options);
|
|
300
|
-
return this.service.methods.releaseRemoteSubset({ collectionId, options: {}, acquisitionId });
|
|
301
|
-
}
|
|
302
|
-
registerRemoteSubsetOwner(collectionId, owner) {
|
|
303
|
-
const unregister = this.remoteSubsets.registerRemoteSubsetOwner(collectionId, owner);
|
|
304
|
-
let registered = true;
|
|
305
|
-
return () => {
|
|
306
|
-
if (!registered)
|
|
307
|
-
return;
|
|
308
|
-
registered = false;
|
|
309
|
-
unregister();
|
|
310
|
-
for (const [id, acquisition] of this.remoteAcquisitions) {
|
|
311
|
-
if (acquisition.collectionId === collectionId)
|
|
312
|
-
this.remoteAcquisitions.delete(id);
|
|
313
|
-
}
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
requestApplyCommittedTx(collectionId, tx, scopedAdapter) {
|
|
317
|
-
return this.isLeader()
|
|
318
|
-
? this.applyCommittedTx({ collectionId, tx }, scopedAdapter)
|
|
319
|
-
: this.service.methods.applyCommittedTx({
|
|
320
|
-
collectionId,
|
|
321
|
-
tx,
|
|
322
|
-
schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??
|
|
323
|
-
this.schemaVersion(this.adapterForCollection(collectionId)),
|
|
324
|
-
});
|
|
325
|
-
}
|
|
326
|
-
async applyCommittedTx({ collectionId, tx, schemaVersion }, scopedAdapter) {
|
|
327
|
-
try {
|
|
328
|
-
await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(collectionId, tx);
|
|
329
|
-
}
|
|
330
|
-
catch (error) {
|
|
331
|
-
throw toPersistedCollectionDurabilityError(collectionId, error);
|
|
332
|
-
}
|
|
333
|
-
this.positions.delete(collectionId);
|
|
334
|
-
return {
|
|
335
|
-
type: "rpc:applyCommittedTx:res",
|
|
336
|
-
rpcId: safeRandomUUID(),
|
|
337
|
-
ok: true,
|
|
338
|
-
term: tx.term,
|
|
339
|
-
seq: tx.seq,
|
|
340
|
-
latestRowVersion: tx.rowVersion,
|
|
341
|
-
};
|
|
342
|
-
}
|
|
343
|
-
requestEnsurePersistedIndex(collectionId, signature, spec, scopedAdapter, localEnsureCompleted) {
|
|
344
|
-
if (this.isLeader()) {
|
|
345
|
-
return localEnsureCompleted
|
|
346
|
-
? Promise.resolve()
|
|
347
|
-
: (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(collectionId, signature, spec);
|
|
348
|
-
}
|
|
349
|
-
return this.service.methods.ensurePersistedIndex({
|
|
350
|
-
collectionId,
|
|
351
|
-
signature,
|
|
352
|
-
spec,
|
|
353
|
-
schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??
|
|
354
|
-
this.schemaVersion(this.adapterForCollection(collectionId)),
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
async requestApplyLocalMutations(collectionId, mutations) {
|
|
358
|
-
const envelopeId = safeRandomUUID();
|
|
359
|
-
const burst = this.resumeChecks.has(collectionId)
|
|
360
|
-
? this.localMutationBursts.get(collectionId) ?? { pending: new Set(), needsReload: false, timer: undefined }
|
|
361
|
-
: undefined;
|
|
362
|
-
if (burst) {
|
|
363
|
-
if (burst.timer !== undefined)
|
|
364
|
-
clearTimeout(burst.timer);
|
|
365
|
-
if (burst.pending.size > 0)
|
|
366
|
-
burst.needsReload = true;
|
|
367
|
-
burst.pending.add(envelopeId);
|
|
368
|
-
this.localMutationBursts.set(collectionId, burst);
|
|
369
|
-
}
|
|
370
|
-
try {
|
|
371
|
-
return await this.service.methods.applyLocalMutations({
|
|
372
|
-
collectionId,
|
|
373
|
-
rpcId: safeRandomUUID(),
|
|
374
|
-
envelopeId,
|
|
375
|
-
schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),
|
|
376
|
-
mutations,
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
finally {
|
|
380
|
-
burst?.pending.delete(envelopeId);
|
|
381
|
-
if (burst && burst.pending.size === 0 && this.localMutationBursts.get(collectionId) === burst) {
|
|
382
|
-
// Upstream advances its observed sequence from local RPC acknowledgements
|
|
383
|
-
// before queued commit messages can run. Reconcile overlapping foreign
|
|
384
|
-
// commits after the local mutation burst, without changing RPC positions.
|
|
385
|
-
burst.timer = setTimeout(() => {
|
|
386
|
-
if (this.localMutationBursts.get(collectionId) !== burst)
|
|
387
|
-
return;
|
|
388
|
-
this.localMutationBursts.delete(collectionId);
|
|
389
|
-
if (burst.needsReload) {
|
|
390
|
-
for (const check of this.resumeChecks.get(collectionId) ?? [])
|
|
391
|
-
void check(true);
|
|
392
|
-
}
|
|
393
|
-
}, 0);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
pullSince(collectionId, fromRowVersion) {
|
|
398
|
-
return this.service.methods.pullSince({
|
|
399
|
-
collectionId,
|
|
400
|
-
rpcId: safeRandomUUID(),
|
|
401
|
-
fromRowVersion,
|
|
402
|
-
schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
relayMessage(input) {
|
|
406
|
-
const key = relayKey(input.collectionId, input.message);
|
|
407
|
-
if (this.relayedMessages.has(key)) {
|
|
408
|
-
return Promise.resolve();
|
|
409
|
-
}
|
|
410
|
-
this.relayedMessages.add(key);
|
|
411
|
-
if (this.relayedMessages.size > MAX_DEDUPLICATION_ENTRIES) {
|
|
412
|
-
const oldest = this.relayedMessages.values().next().value;
|
|
413
|
-
if (oldest) {
|
|
414
|
-
this.relayedMessages.delete(oldest);
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
this.publishMessage(input);
|
|
418
|
-
return Promise.resolve();
|
|
419
|
-
}
|
|
420
|
-
publishMessage(input) {
|
|
421
|
-
this.server?.events.publish("message", input);
|
|
422
|
-
}
|
|
423
|
-
async position(collectionId) {
|
|
424
|
-
let position = this.positions.get(collectionId);
|
|
425
|
-
if (!position) {
|
|
426
|
-
const adapter = this.adapterForCollection(collectionId);
|
|
427
|
-
position = Promise.resolve(adapter.getStreamPosition
|
|
428
|
-
? adapter.getStreamPosition(collectionId)
|
|
429
|
-
: adapter.loadResumeSnapshot(collectionId, { includeRows: false })).then((current) => ({
|
|
430
|
-
term: (current?.latestTerm ?? 0) + 1,
|
|
431
|
-
seq: current?.latestSeq ?? 0,
|
|
432
|
-
rowVersion: current?.latestRowVersion ?? 0,
|
|
433
|
-
}));
|
|
434
|
-
}
|
|
435
|
-
this.positions.delete(collectionId);
|
|
436
|
-
this.positions.set(collectionId, position);
|
|
437
|
-
while (this.positions.size > MAX_COLLECTION_POSITIONS) {
|
|
438
|
-
const oldest = this.positions.keys().next().value;
|
|
439
|
-
if (oldest !== undefined)
|
|
440
|
-
this.positions.delete(oldest);
|
|
441
|
-
}
|
|
442
|
-
void position.catch(() => {
|
|
443
|
-
if (this.positions.get(collectionId) === position)
|
|
444
|
-
this.positions.delete(collectionId);
|
|
445
|
-
});
|
|
446
|
-
return position;
|
|
447
|
-
}
|
|
448
|
-
async applyMutations(input) {
|
|
449
|
-
const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
|
|
450
|
-
const envelopeKey = JSON.stringify([input.collectionId, input.envelopeId]);
|
|
451
|
-
const previous = this.appliedEnvelopes.get(envelopeKey);
|
|
452
|
-
if (previous) {
|
|
453
|
-
return {
|
|
454
|
-
...previous,
|
|
455
|
-
rpcId: input.rpcId,
|
|
456
|
-
};
|
|
457
|
-
}
|
|
458
|
-
const position = await this.position(input.collectionId);
|
|
459
|
-
const nextPosition = { ...position, seq: position.seq + 1, rowVersion: position.rowVersion + 1 };
|
|
460
|
-
const txId = input.envelopeId;
|
|
461
|
-
await adapter.applyCommittedTx(input.collectionId, {
|
|
462
|
-
txId,
|
|
463
|
-
term: nextPosition.term,
|
|
464
|
-
seq: nextPosition.seq,
|
|
465
|
-
rowVersion: nextPosition.rowVersion,
|
|
466
|
-
mutations: input.mutations.map(({ mutationId, ...mutation }) => {
|
|
467
|
-
void mutationId;
|
|
468
|
-
return mutation;
|
|
469
|
-
}),
|
|
470
|
-
});
|
|
471
|
-
Object.assign(position, nextPosition);
|
|
472
|
-
const committed = {
|
|
473
|
-
v: 1,
|
|
474
|
-
dbName: this.coordinationScope(),
|
|
475
|
-
collectionId: input.collectionId,
|
|
476
|
-
senderId: this.nodeId,
|
|
477
|
-
ts: Date.now(),
|
|
478
|
-
payload: {
|
|
479
|
-
type: "tx:committed",
|
|
480
|
-
term: position.term,
|
|
481
|
-
seq: position.seq,
|
|
482
|
-
txId,
|
|
483
|
-
latestRowVersion: position.rowVersion,
|
|
484
|
-
requiresFullReload: false,
|
|
485
|
-
changedRows: input.mutations
|
|
486
|
-
.filter((mutation) => mutation.type !== "delete")
|
|
487
|
-
.map((mutation) => ({
|
|
488
|
-
key: mutation.key,
|
|
489
|
-
value: mutation.value,
|
|
490
|
-
})),
|
|
491
|
-
deletedKeys: input.mutations
|
|
492
|
-
.filter((mutation) => mutation.type === "delete")
|
|
493
|
-
.map((mutation) => mutation.key),
|
|
494
|
-
rowMetadataMutations: input.mutations.flatMap((mutation) => mutation.type !== "delete" &&
|
|
495
|
-
(mutation.metadataChanged || mutation.metadata !== undefined)
|
|
496
|
-
? [
|
|
497
|
-
mutation.metadata === undefined
|
|
498
|
-
? { type: "delete", key: mutation.key }
|
|
499
|
-
: { type: "set", key: mutation.key, value: mutation.metadata },
|
|
500
|
-
]
|
|
501
|
-
: []),
|
|
502
|
-
},
|
|
503
|
-
};
|
|
504
|
-
this.publishMessage({
|
|
505
|
-
collectionId: input.collectionId,
|
|
506
|
-
message: committed,
|
|
507
|
-
});
|
|
508
|
-
const response = {
|
|
509
|
-
type: "rpc:applyLocalMutations:res",
|
|
510
|
-
rpcId: input.rpcId,
|
|
511
|
-
ok: true,
|
|
512
|
-
term: position.term,
|
|
513
|
-
seq: position.seq,
|
|
514
|
-
latestRowVersion: position.rowVersion,
|
|
515
|
-
acceptedMutationIds: input.mutations.map((mutation) => mutation.mutationId),
|
|
516
|
-
};
|
|
517
|
-
this.appliedEnvelopes.set(envelopeKey, response);
|
|
518
|
-
if (this.appliedEnvelopes.size > MAX_DEDUPLICATION_ENTRIES) {
|
|
519
|
-
const oldest = this.appliedEnvelopes.keys().next().value;
|
|
520
|
-
if (oldest) {
|
|
521
|
-
this.appliedEnvelopes.delete(oldest);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
return response;
|
|
525
|
-
}
|
|
526
|
-
async handlePullSince(input) {
|
|
527
|
-
const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
|
|
528
|
-
const current = await adapter.getStreamPosition?.(input.collectionId);
|
|
529
|
-
const position = current
|
|
530
|
-
? { term: current.latestTerm, seq: current.latestSeq, rowVersion: current.latestRowVersion }
|
|
531
|
-
: await this.position(input.collectionId);
|
|
532
|
-
const result = await adapter.pullSince?.(input.collectionId, input.fromRowVersion);
|
|
533
|
-
if (!result || result.requiresFullReload) {
|
|
534
|
-
return {
|
|
535
|
-
type: "rpc:pullSince:res",
|
|
536
|
-
rpcId: input.rpcId,
|
|
537
|
-
ok: true,
|
|
538
|
-
latestTerm: result?.latestTerm ?? position.term,
|
|
539
|
-
latestSeq: result?.latestSeq ?? position.seq,
|
|
540
|
-
latestRowVersion: result?.latestRowVersion ?? position.rowVersion,
|
|
541
|
-
requiresFullReload: true,
|
|
542
|
-
};
|
|
543
|
-
}
|
|
544
|
-
return {
|
|
545
|
-
type: "rpc:pullSince:res",
|
|
546
|
-
rpcId: input.rpcId,
|
|
547
|
-
ok: true,
|
|
548
|
-
latestTerm: result?.latestTerm ?? position.term,
|
|
549
|
-
latestSeq: result?.latestSeq ?? position.seq,
|
|
550
|
-
latestRowVersion: result.latestRowVersion,
|
|
551
|
-
requiresFullReload: false,
|
|
552
|
-
changedKeys: result.changedKeys,
|
|
553
|
-
deletedKeys: result.deletedKeys,
|
|
554
|
-
deltas: result.deltas,
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
coordinationScope() {
|
|
558
|
-
return "scope" in this.coordination && typeof this.coordination.scope === "string"
|
|
559
|
-
? this.coordination.scope
|
|
560
|
-
: "party-stack";
|
|
561
|
-
}
|
|
24
|
+
function createPersistedCollectionCoordinator(coordination, adapter) {
|
|
25
|
+
let adapters = coordinatorCache.get(coordination);
|
|
26
|
+
if (!adapters) {
|
|
27
|
+
adapters = /* @__PURE__ */ new WeakMap();
|
|
28
|
+
coordinatorCache.set(coordination, adapters);
|
|
29
|
+
}
|
|
30
|
+
const existing = adapters.get(adapter);
|
|
31
|
+
if (existing) return existing;
|
|
32
|
+
const created = new CoordinationPersistenceShim(coordination, adapter);
|
|
33
|
+
adapters.set(adapter, created);
|
|
34
|
+
return created;
|
|
562
35
|
}
|
|
36
|
+
var CoordinationPersistenceShim = class {
|
|
37
|
+
coordination;
|
|
38
|
+
adapter;
|
|
39
|
+
nodeId = safeRandomUUID();
|
|
40
|
+
collectionAdapters = /* @__PURE__ */ new Map();
|
|
41
|
+
collectionSubscriptions = /* @__PURE__ */ new Map();
|
|
42
|
+
resumeChecks = /* @__PURE__ */ new Map();
|
|
43
|
+
localMutationBursts = /* @__PURE__ */ new Map();
|
|
44
|
+
stopResumeListeners;
|
|
45
|
+
checkingResume = false;
|
|
46
|
+
resumeRequested = false;
|
|
47
|
+
requestResumeCheck = () => {
|
|
48
|
+
this.resumeRequested = true;
|
|
49
|
+
if (this.checkingResume) return;
|
|
50
|
+
this.checkingResume = true;
|
|
51
|
+
(async () => {
|
|
52
|
+
try {
|
|
53
|
+
while (this.resumeRequested && this.resumeChecks.size > 0) {
|
|
54
|
+
this.resumeRequested = false;
|
|
55
|
+
await Promise.all([...this.resumeChecks.values()].flatMap((checks) => [...checks].map((check) => check())));
|
|
56
|
+
}
|
|
57
|
+
} finally {
|
|
58
|
+
this.checkingResume = false;
|
|
59
|
+
this.resumeRequested = false;
|
|
60
|
+
}
|
|
61
|
+
})();
|
|
62
|
+
};
|
|
63
|
+
startResumeListeners() {
|
|
64
|
+
if (this.stopResumeListeners || typeof window === "undefined" || typeof document === "undefined") return;
|
|
65
|
+
const page = window;
|
|
66
|
+
const visibility = document;
|
|
67
|
+
const onVisible = () => {
|
|
68
|
+
if (visibility.visibilityState === "visible") this.requestResumeCheck();
|
|
69
|
+
};
|
|
70
|
+
page.addEventListener("pageshow", this.requestResumeCheck);
|
|
71
|
+
page.addEventListener("focus", onVisible);
|
|
72
|
+
visibility.addEventListener("visibilitychange", onVisible);
|
|
73
|
+
this.stopResumeListeners = () => {
|
|
74
|
+
page.removeEventListener("pageshow", this.requestResumeCheck);
|
|
75
|
+
page.removeEventListener("focus", onVisible);
|
|
76
|
+
visibility.removeEventListener("visibilitychange", onVisible);
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
setAdapterForCollection(collectionId, adapter) {
|
|
80
|
+
this.collectionAdapters.set(collectionId, adapter);
|
|
81
|
+
this.positions.delete(collectionId);
|
|
82
|
+
}
|
|
83
|
+
adapterForCollection(collectionId, schemaVersion) {
|
|
84
|
+
const adapter = this.collectionAdapters.get(collectionId) ?? this.adapter;
|
|
85
|
+
if (schemaVersion !== void 0 && this.schemaVersion(adapter) !== schemaVersion) throw new Error(`Persistence schema mismatch for collection "${collectionId}". Reload the coordination host before writing through another schema version.`);
|
|
86
|
+
return adapter;
|
|
87
|
+
}
|
|
88
|
+
schemaVersion(adapter) {
|
|
89
|
+
return "schemaVersion" in adapter && typeof adapter.schemaVersion === "number" ? adapter.schemaVersion : void 0;
|
|
90
|
+
}
|
|
91
|
+
positions = /* @__PURE__ */ new Map();
|
|
92
|
+
appliedEnvelopes = /* @__PURE__ */ new Map();
|
|
93
|
+
relayedMessages = /* @__PURE__ */ new Set();
|
|
94
|
+
service;
|
|
95
|
+
server;
|
|
96
|
+
pendingRelays = 0;
|
|
97
|
+
remoteSubsets = new SingleProcessCoordinator();
|
|
98
|
+
acquisitionIds = /* @__PURE__ */ new WeakMap();
|
|
99
|
+
remoteAcquisitions = /* @__PURE__ */ new Map();
|
|
100
|
+
constructor(coordination, adapter) {
|
|
101
|
+
this.coordination = coordination;
|
|
102
|
+
this.adapter = adapter;
|
|
103
|
+
this.service = coordination.service(PERSISTENCE_SERVICE);
|
|
104
|
+
this.server = isCoordinationHost(coordination) ? coordination.serve(PERSISTENCE_SERVICE, {
|
|
105
|
+
ensureLeadership: () => Promise.resolve(),
|
|
106
|
+
ensureRemoteSubset: async (input) => {
|
|
107
|
+
let options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
|
|
108
|
+
if (!options) {
|
|
109
|
+
options = input.options;
|
|
110
|
+
this.remoteAcquisitions.set(input.acquisitionId, {
|
|
111
|
+
collectionId: input.collectionId,
|
|
112
|
+
options
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
await this.remoteSubsets.requestEnsureRemoteSubset(input.collectionId, options);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (this.remoteAcquisitions.get(input.acquisitionId)?.options === options) {
|
|
119
|
+
this.remoteAcquisitions.delete(input.acquisitionId);
|
|
120
|
+
await this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options).catch(() => void 0);
|
|
121
|
+
}
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
releaseRemoteSubset: (input) => {
|
|
126
|
+
const options = this.remoteAcquisitions.get(input.acquisitionId)?.options;
|
|
127
|
+
this.remoteAcquisitions.delete(input.acquisitionId);
|
|
128
|
+
return options ? this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options) : Promise.resolve();
|
|
129
|
+
},
|
|
130
|
+
applyCommittedTx: (input) => this.applyCommittedTx(input),
|
|
131
|
+
ensurePersistedIndex: (input) => this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(input.collectionId, input.signature, input.spec),
|
|
132
|
+
applyLocalMutations: (input) => this.applyMutations(input),
|
|
133
|
+
pullSince: (input) => this.handlePullSince(input),
|
|
134
|
+
relayMessage: (input) => this.relayMessage(input)
|
|
135
|
+
}) : void 0;
|
|
136
|
+
}
|
|
137
|
+
getNodeId() {
|
|
138
|
+
return this.nodeId;
|
|
139
|
+
}
|
|
140
|
+
subscribe(collectionId, callback) {
|
|
141
|
+
let active = true;
|
|
142
|
+
let observed;
|
|
143
|
+
const unsubscribe = this.service.events.subscribe("message", (event) => {
|
|
144
|
+
if (!active) return;
|
|
145
|
+
if (event.collectionId === collectionId) {
|
|
146
|
+
const payload = event.message.payload;
|
|
147
|
+
const burst = this.localMutationBursts.get(collectionId);
|
|
148
|
+
if (burst && isRecord(payload) && payload.type === "tx:committed" && typeof payload.txId === "string" && !burst.pending.has(payload.txId)) burst.needsReload = true;
|
|
149
|
+
if (isRecord(payload) && payload.type === "tx:committed" && typeof payload.term === "number" && typeof payload.seq === "number" && typeof payload.latestRowVersion === "number" && (!observed || payload.term > observed.latestTerm || payload.term === observed.latestTerm && payload.seq > observed.latestSeq)) observed = {
|
|
150
|
+
latestTerm: payload.term,
|
|
151
|
+
latestSeq: payload.seq,
|
|
152
|
+
latestRowVersion: payload.latestRowVersion
|
|
153
|
+
};
|
|
154
|
+
callback(event.message);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
const checkResume = async (force = false) => {
|
|
158
|
+
try {
|
|
159
|
+
if (!active) return;
|
|
160
|
+
const adapter = this.adapterForCollection(collectionId);
|
|
161
|
+
const current = await adapter.getStreamPosition?.(collectionId);
|
|
162
|
+
if (!active) return;
|
|
163
|
+
if (!force && current && observed && current.latestTerm === observed.latestTerm && current.latestSeq === observed.latestSeq && current.latestRowVersion === observed.latestRowVersion) return;
|
|
164
|
+
callback({
|
|
165
|
+
v: 1,
|
|
166
|
+
dbName: this.coordinationScope(),
|
|
167
|
+
collectionId,
|
|
168
|
+
senderId: `resume:${this.nodeId}`,
|
|
169
|
+
ts: Date.now(),
|
|
170
|
+
payload: {
|
|
171
|
+
type: "collection:reset",
|
|
172
|
+
schemaVersion: this.schemaVersion(adapter) ?? 1,
|
|
173
|
+
resetEpoch: 0
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
observed = current;
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if (active) console.warn(`Failed to refresh resumed collection "${collectionId}".`, error);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
const checks = this.resumeChecks.get(collectionId) ?? /* @__PURE__ */ new Set();
|
|
182
|
+
checks.add(checkResume);
|
|
183
|
+
this.resumeChecks.set(collectionId, checks);
|
|
184
|
+
this.startResumeListeners();
|
|
185
|
+
this.collectionSubscriptions.set(collectionId, (this.collectionSubscriptions.get(collectionId) ?? 0) + 1);
|
|
186
|
+
return () => {
|
|
187
|
+
if (!active) return;
|
|
188
|
+
active = false;
|
|
189
|
+
checks.delete(checkResume);
|
|
190
|
+
if (checks.size === 0) {
|
|
191
|
+
this.resumeChecks.delete(collectionId);
|
|
192
|
+
const burst = this.localMutationBursts.get(collectionId);
|
|
193
|
+
if (burst?.timer !== void 0) clearTimeout(burst.timer);
|
|
194
|
+
this.localMutationBursts.delete(collectionId);
|
|
195
|
+
}
|
|
196
|
+
if (this.resumeChecks.size === 0) {
|
|
197
|
+
this.stopResumeListeners?.();
|
|
198
|
+
this.stopResumeListeners = void 0;
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
unsubscribe();
|
|
202
|
+
} finally {
|
|
203
|
+
const remaining = this.collectionSubscriptions.get(collectionId) - 1;
|
|
204
|
+
if (remaining > 0) this.collectionSubscriptions.set(collectionId, remaining);
|
|
205
|
+
else {
|
|
206
|
+
this.collectionSubscriptions.delete(collectionId);
|
|
207
|
+
this.collectionAdapters.delete(collectionId);
|
|
208
|
+
this.positions.delete(collectionId);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
publish(collectionId, message) {
|
|
214
|
+
if (this.server && isCoordinationHost(this.coordination) && this.coordination.isLeader) {
|
|
215
|
+
this.publishMessage({
|
|
216
|
+
collectionId,
|
|
217
|
+
message
|
|
218
|
+
});
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (this.pendingRelays >= MAX_PENDING_RELAYS) {
|
|
222
|
+
console.warn(`Dropping persistence relay for "${collectionId}" because the pending relay limit was reached.`);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
this.pendingRelays += 1;
|
|
226
|
+
this.service.methods.relayMessage({
|
|
227
|
+
collectionId,
|
|
228
|
+
message
|
|
229
|
+
}).catch((error) => {
|
|
230
|
+
console.warn(`Failed to relay persistence message for "${collectionId}".`, error);
|
|
231
|
+
}).finally(() => {
|
|
232
|
+
this.pendingRelays -= 1;
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
isLeader() {
|
|
236
|
+
return isCoordinationHost(this.coordination) && this.coordination.isLeader;
|
|
237
|
+
}
|
|
238
|
+
ensureLeadership() {
|
|
239
|
+
return this.service.methods.ensureLeadership({ collectionId: "*" });
|
|
240
|
+
}
|
|
241
|
+
requestEnsureRemoteSubset(collectionId, options) {
|
|
242
|
+
let collectionIds = this.acquisitionIds.get(options);
|
|
243
|
+
if (!collectionIds) {
|
|
244
|
+
collectionIds = /* @__PURE__ */ new Map();
|
|
245
|
+
this.acquisitionIds.set(options, collectionIds);
|
|
246
|
+
}
|
|
247
|
+
let acquisitionId = collectionIds.get(collectionId);
|
|
248
|
+
if (!acquisitionId) {
|
|
249
|
+
acquisitionId = safeRandomUUID();
|
|
250
|
+
collectionIds.set(collectionId, acquisitionId);
|
|
251
|
+
}
|
|
252
|
+
return this.service.methods.ensureRemoteSubset({
|
|
253
|
+
collectionId,
|
|
254
|
+
options: toTransportedLoadSubsetOptions(options),
|
|
255
|
+
acquisitionId
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
requestReleaseRemoteSubset(collectionId, options) {
|
|
259
|
+
const collectionIds = this.acquisitionIds.get(options);
|
|
260
|
+
const acquisitionId = collectionIds?.get(collectionId);
|
|
261
|
+
if (!acquisitionId) return Promise.resolve();
|
|
262
|
+
collectionIds.delete(collectionId);
|
|
263
|
+
if (collectionIds.size === 0) this.acquisitionIds.delete(options);
|
|
264
|
+
return this.service.methods.releaseRemoteSubset({
|
|
265
|
+
collectionId,
|
|
266
|
+
options: {},
|
|
267
|
+
acquisitionId
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
registerRemoteSubsetOwner(collectionId, owner) {
|
|
271
|
+
const unregister = this.remoteSubsets.registerRemoteSubsetOwner(collectionId, owner);
|
|
272
|
+
let registered = true;
|
|
273
|
+
return () => {
|
|
274
|
+
if (!registered) return;
|
|
275
|
+
registered = false;
|
|
276
|
+
unregister();
|
|
277
|
+
for (const [id, acquisition] of this.remoteAcquisitions) if (acquisition.collectionId === collectionId) this.remoteAcquisitions.delete(id);
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
requestApplyCommittedTx(collectionId, tx, scopedAdapter) {
|
|
281
|
+
return this.isLeader() ? this.applyCommittedTx({
|
|
282
|
+
collectionId,
|
|
283
|
+
tx
|
|
284
|
+
}, scopedAdapter) : this.service.methods.applyCommittedTx({
|
|
285
|
+
collectionId,
|
|
286
|
+
tx,
|
|
287
|
+
schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ?? this.schemaVersion(this.adapterForCollection(collectionId))
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
async applyCommittedTx({ collectionId, tx, schemaVersion }, scopedAdapter) {
|
|
291
|
+
try {
|
|
292
|
+
await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(collectionId, tx);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
throw toPersistedCollectionDurabilityError(collectionId, error);
|
|
295
|
+
}
|
|
296
|
+
this.positions.delete(collectionId);
|
|
297
|
+
return {
|
|
298
|
+
type: "rpc:applyCommittedTx:res",
|
|
299
|
+
rpcId: safeRandomUUID(),
|
|
300
|
+
ok: true,
|
|
301
|
+
term: tx.term,
|
|
302
|
+
seq: tx.seq,
|
|
303
|
+
latestRowVersion: tx.rowVersion
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
requestEnsurePersistedIndex(collectionId, signature, spec, scopedAdapter, localEnsureCompleted) {
|
|
307
|
+
if (this.isLeader()) return localEnsureCompleted ? Promise.resolve() : (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(collectionId, signature, spec);
|
|
308
|
+
return this.service.methods.ensurePersistedIndex({
|
|
309
|
+
collectionId,
|
|
310
|
+
signature,
|
|
311
|
+
spec,
|
|
312
|
+
schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ?? this.schemaVersion(this.adapterForCollection(collectionId))
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
async requestApplyLocalMutations(collectionId, mutations) {
|
|
316
|
+
const envelopeId = safeRandomUUID();
|
|
317
|
+
const burst = this.resumeChecks.has(collectionId) ? this.localMutationBursts.get(collectionId) ?? {
|
|
318
|
+
pending: /* @__PURE__ */ new Set(),
|
|
319
|
+
needsReload: false,
|
|
320
|
+
timer: void 0
|
|
321
|
+
} : void 0;
|
|
322
|
+
if (burst) {
|
|
323
|
+
if (burst.timer !== void 0) clearTimeout(burst.timer);
|
|
324
|
+
if (burst.pending.size > 0) burst.needsReload = true;
|
|
325
|
+
burst.pending.add(envelopeId);
|
|
326
|
+
this.localMutationBursts.set(collectionId, burst);
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
return await this.service.methods.applyLocalMutations({
|
|
330
|
+
collectionId,
|
|
331
|
+
rpcId: safeRandomUUID(),
|
|
332
|
+
envelopeId,
|
|
333
|
+
schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),
|
|
334
|
+
mutations
|
|
335
|
+
});
|
|
336
|
+
} finally {
|
|
337
|
+
burst?.pending.delete(envelopeId);
|
|
338
|
+
if (burst && burst.pending.size === 0 && this.localMutationBursts.get(collectionId) === burst) burst.timer = setTimeout(() => {
|
|
339
|
+
if (this.localMutationBursts.get(collectionId) !== burst) return;
|
|
340
|
+
this.localMutationBursts.delete(collectionId);
|
|
341
|
+
if (burst.needsReload) for (const check of this.resumeChecks.get(collectionId) ?? []) check(true);
|
|
342
|
+
}, 0);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
pullSince(collectionId, fromRowVersion) {
|
|
346
|
+
return this.service.methods.pullSince({
|
|
347
|
+
collectionId,
|
|
348
|
+
rpcId: safeRandomUUID(),
|
|
349
|
+
fromRowVersion,
|
|
350
|
+
schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId))
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
relayMessage(input) {
|
|
354
|
+
const key = relayKey(input.collectionId, input.message);
|
|
355
|
+
if (this.relayedMessages.has(key)) return Promise.resolve();
|
|
356
|
+
this.relayedMessages.add(key);
|
|
357
|
+
if (this.relayedMessages.size > MAX_DEDUPLICATION_ENTRIES) {
|
|
358
|
+
const oldest = this.relayedMessages.values().next().value;
|
|
359
|
+
if (oldest) this.relayedMessages.delete(oldest);
|
|
360
|
+
}
|
|
361
|
+
this.publishMessage(input);
|
|
362
|
+
return Promise.resolve();
|
|
363
|
+
}
|
|
364
|
+
publishMessage(input) {
|
|
365
|
+
this.server?.events.publish("message", input);
|
|
366
|
+
}
|
|
367
|
+
async position(collectionId) {
|
|
368
|
+
let position = this.positions.get(collectionId);
|
|
369
|
+
if (!position) {
|
|
370
|
+
const adapter = this.adapterForCollection(collectionId);
|
|
371
|
+
position = Promise.resolve(adapter.getStreamPosition ? adapter.getStreamPosition(collectionId) : adapter.loadResumeSnapshot(collectionId, { includeRows: false })).then((current) => ({
|
|
372
|
+
term: (current?.latestTerm ?? 0) + 1,
|
|
373
|
+
seq: current?.latestSeq ?? 0,
|
|
374
|
+
rowVersion: current?.latestRowVersion ?? 0
|
|
375
|
+
}));
|
|
376
|
+
}
|
|
377
|
+
this.positions.delete(collectionId);
|
|
378
|
+
this.positions.set(collectionId, position);
|
|
379
|
+
while (this.positions.size > MAX_COLLECTION_POSITIONS) {
|
|
380
|
+
const oldest = this.positions.keys().next().value;
|
|
381
|
+
if (oldest !== void 0) this.positions.delete(oldest);
|
|
382
|
+
}
|
|
383
|
+
position.catch(() => {
|
|
384
|
+
if (this.positions.get(collectionId) === position) this.positions.delete(collectionId);
|
|
385
|
+
});
|
|
386
|
+
return position;
|
|
387
|
+
}
|
|
388
|
+
async applyMutations(input) {
|
|
389
|
+
const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
|
|
390
|
+
const envelopeKey = JSON.stringify([input.collectionId, input.envelopeId]);
|
|
391
|
+
const previous = this.appliedEnvelopes.get(envelopeKey);
|
|
392
|
+
if (previous) return {
|
|
393
|
+
...previous,
|
|
394
|
+
rpcId: input.rpcId
|
|
395
|
+
};
|
|
396
|
+
const position = await this.position(input.collectionId);
|
|
397
|
+
const nextPosition = {
|
|
398
|
+
...position,
|
|
399
|
+
seq: position.seq + 1,
|
|
400
|
+
rowVersion: position.rowVersion + 1
|
|
401
|
+
};
|
|
402
|
+
const txId = input.envelopeId;
|
|
403
|
+
await adapter.applyCommittedTx(input.collectionId, {
|
|
404
|
+
txId,
|
|
405
|
+
term: nextPosition.term,
|
|
406
|
+
seq: nextPosition.seq,
|
|
407
|
+
rowVersion: nextPosition.rowVersion,
|
|
408
|
+
mutations: input.mutations.map(({ mutationId, ...mutation }) => {
|
|
409
|
+
return mutation;
|
|
410
|
+
})
|
|
411
|
+
});
|
|
412
|
+
Object.assign(position, nextPosition);
|
|
413
|
+
const committed = {
|
|
414
|
+
v: 1,
|
|
415
|
+
dbName: this.coordinationScope(),
|
|
416
|
+
collectionId: input.collectionId,
|
|
417
|
+
senderId: this.nodeId,
|
|
418
|
+
ts: Date.now(),
|
|
419
|
+
payload: {
|
|
420
|
+
type: "tx:committed",
|
|
421
|
+
term: position.term,
|
|
422
|
+
seq: position.seq,
|
|
423
|
+
txId,
|
|
424
|
+
latestRowVersion: position.rowVersion,
|
|
425
|
+
requiresFullReload: false,
|
|
426
|
+
changedRows: input.mutations.filter((mutation) => mutation.type !== "delete").map((mutation) => ({
|
|
427
|
+
key: mutation.key,
|
|
428
|
+
value: mutation.value
|
|
429
|
+
})),
|
|
430
|
+
deletedKeys: input.mutations.filter((mutation) => mutation.type === "delete").map((mutation) => mutation.key),
|
|
431
|
+
rowMetadataMutations: input.mutations.flatMap((mutation) => mutation.type !== "delete" && (mutation.metadataChanged || mutation.metadata !== void 0) ? [mutation.metadata === void 0 ? {
|
|
432
|
+
type: "delete",
|
|
433
|
+
key: mutation.key
|
|
434
|
+
} : {
|
|
435
|
+
type: "set",
|
|
436
|
+
key: mutation.key,
|
|
437
|
+
value: mutation.metadata
|
|
438
|
+
}] : [])
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
this.publishMessage({
|
|
442
|
+
collectionId: input.collectionId,
|
|
443
|
+
message: committed
|
|
444
|
+
});
|
|
445
|
+
const response = {
|
|
446
|
+
type: "rpc:applyLocalMutations:res",
|
|
447
|
+
rpcId: input.rpcId,
|
|
448
|
+
ok: true,
|
|
449
|
+
term: position.term,
|
|
450
|
+
seq: position.seq,
|
|
451
|
+
latestRowVersion: position.rowVersion,
|
|
452
|
+
acceptedMutationIds: input.mutations.map((mutation) => mutation.mutationId)
|
|
453
|
+
};
|
|
454
|
+
this.appliedEnvelopes.set(envelopeKey, response);
|
|
455
|
+
if (this.appliedEnvelopes.size > MAX_DEDUPLICATION_ENTRIES) {
|
|
456
|
+
const oldest = this.appliedEnvelopes.keys().next().value;
|
|
457
|
+
if (oldest) this.appliedEnvelopes.delete(oldest);
|
|
458
|
+
}
|
|
459
|
+
return response;
|
|
460
|
+
}
|
|
461
|
+
async handlePullSince(input) {
|
|
462
|
+
const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
|
|
463
|
+
const current = await adapter.getStreamPosition?.(input.collectionId);
|
|
464
|
+
const position = current ? {
|
|
465
|
+
term: current.latestTerm,
|
|
466
|
+
seq: current.latestSeq,
|
|
467
|
+
rowVersion: current.latestRowVersion
|
|
468
|
+
} : await this.position(input.collectionId);
|
|
469
|
+
const result = await adapter.pullSince?.(input.collectionId, input.fromRowVersion);
|
|
470
|
+
if (!result || result.requiresFullReload) return {
|
|
471
|
+
type: "rpc:pullSince:res",
|
|
472
|
+
rpcId: input.rpcId,
|
|
473
|
+
ok: true,
|
|
474
|
+
latestTerm: result?.latestTerm ?? position.term,
|
|
475
|
+
latestSeq: result?.latestSeq ?? position.seq,
|
|
476
|
+
latestRowVersion: result?.latestRowVersion ?? position.rowVersion,
|
|
477
|
+
requiresFullReload: true
|
|
478
|
+
};
|
|
479
|
+
return {
|
|
480
|
+
type: "rpc:pullSince:res",
|
|
481
|
+
rpcId: input.rpcId,
|
|
482
|
+
ok: true,
|
|
483
|
+
latestTerm: result?.latestTerm ?? position.term,
|
|
484
|
+
latestSeq: result?.latestSeq ?? position.seq,
|
|
485
|
+
latestRowVersion: result.latestRowVersion,
|
|
486
|
+
requiresFullReload: false,
|
|
487
|
+
changedKeys: result.changedKeys,
|
|
488
|
+
deletedKeys: result.deletedKeys,
|
|
489
|
+
deltas: result.deltas
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
coordinationScope() {
|
|
493
|
+
return "scope" in this.coordination && typeof this.coordination.scope === "string" ? this.coordination.scope : "party-stack";
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
//#endregion
|
|
497
|
+
export { createPersistedCollectionCoordinator };
|
|
498
|
+
|
|
563
499
|
//# sourceMappingURL=createPersistedCollectionCoordinator.js.map
|