@party-stack/runtime 0.3.7 → 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.
Files changed (57) hide show
  1. package/lib/coordinator/createPersistedCollectionCoordinator.d.ts +4 -2
  2. package/lib/coordinator/createPersistedCollectionCoordinator.d.ts.map +1 -1
  3. package/lib/coordinator/createPersistedCollectionCoordinator.js +492 -280
  4. package/lib/coordinator/createPersistedCollectionCoordinator.js.map +1 -1
  5. package/lib/coordinator/index.d.ts +2 -2
  6. package/lib/coordinator/index.js +2 -2
  7. package/lib/effection/index.d.ts +4 -2
  8. package/lib/effection/index.d.ts.map +1 -1
  9. package/lib/effection/index.js +25 -25
  10. package/lib/effection/index.js.map +1 -1
  11. package/lib/index.d.ts +11 -10
  12. package/lib/index.js +10 -8
  13. package/lib/memory/MemoryBlobBytesStore.d.ts +8 -6
  14. package/lib/memory/MemoryBlobBytesStore.d.ts.map +1 -1
  15. package/lib/memory/MemoryBlobBytesStore.js +22 -20
  16. package/lib/memory/MemoryBlobBytesStore.js.map +1 -1
  17. package/lib/types.d.ts +31 -29
  18. package/lib/types.d.ts.map +1 -1
  19. package/lib/types.js +0 -1
  20. package/lib/utils/BrowserAuthenticationCancelledError.d.ts +3 -1
  21. package/lib/utils/BrowserAuthenticationCancelledError.d.ts.map +1 -1
  22. package/lib/utils/BrowserAuthenticationCancelledError.js +10 -6
  23. package/lib/utils/BrowserAuthenticationCancelledError.js.map +1 -1
  24. package/lib/utils/createCollectionPersistence.d.ts +7 -0
  25. package/lib/utils/createCollectionPersistence.d.ts.map +1 -0
  26. package/lib/utils/createCollectionPersistence.js +24 -0
  27. package/lib/utils/createCollectionPersistence.js.map +1 -0
  28. package/lib/utils/createDefaultRuntime.d.ts +4 -1
  29. package/lib/utils/createDefaultRuntime.d.ts.map +1 -1
  30. package/lib/utils/createDefaultRuntime.js +15 -11
  31. package/lib/utils/createDefaultRuntime.js.map +1 -1
  32. package/lib/utils/createLocalCollection.d.ts +8 -6
  33. package/lib/utils/createLocalCollection.d.ts.map +1 -1
  34. package/lib/utils/createLocalCollection.js +19 -18
  35. package/lib/utils/createLocalCollection.js.map +1 -1
  36. package/lib/utils/defineRuntime.d.ts +3 -2
  37. package/lib/utils/defineRuntime.d.ts.map +1 -1
  38. package/lib/utils/defineRuntime.js +26 -30
  39. package/lib/utils/defineRuntime.js.map +1 -1
  40. package/package.json +12 -18
  41. package/lib/coordinator/index.d.ts.map +0 -1
  42. package/lib/coordinator/index.js.map +0 -1
  43. package/lib/index.d.ts.map +0 -1
  44. package/lib/index.js.map +0 -1
  45. package/lib/memory/MemoryBlobBytesStore.test.d.ts +0 -2
  46. package/lib/memory/MemoryBlobBytesStore.test.d.ts.map +0 -1
  47. package/lib/memory/MemoryBlobBytesStore.test.js +0 -12
  48. package/lib/memory/MemoryBlobBytesStore.test.js.map +0 -1
  49. package/lib/types.js.map +0 -1
  50. package/lib/utils/createLocalCollection.test.d.ts +0 -2
  51. package/lib/utils/createLocalCollection.test.d.ts.map +0 -1
  52. package/lib/utils/createLocalCollection.test.js +0 -237
  53. package/lib/utils/createLocalCollection.test.js.map +0 -1
  54. package/lib/utils/defineRuntime.test.d.ts +0 -2
  55. package/lib/utils/defineRuntime.test.d.ts.map +0 -1
  56. package/lib/utils/defineRuntime.test.js +0 -40
  57. package/lib/utils/defineRuntime.test.js.map +0 -1
@@ -1,287 +1,499 @@
1
- import { isCoordinationHost, } from "@party-stack/coordination";
2
- import { safeRandomUUID } from "@tanstack/db-sqlite-persistence-core";
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 = 1_000;
5
- const MAX_PENDING_RELAYS = 1_000;
6
- const coordinatorCache = new WeakMap();
5
+ const MAX_DEDUPLICATION_ENTRIES = 1e3;
6
+ const MAX_PENDING_RELAYS = 1e3;
7
+ const MAX_COLLECTION_POSITIONS = 128;
8
+ const coordinatorCache = /* @__PURE__ */ new WeakMap();
7
9
  function isRecord(value) {
8
- return (typeof value === "object" &&
9
- value !== null);
10
+ return typeof value === "object" && value !== null;
10
11
  }
11
12
  function relayKey(collectionId, message) {
12
- const payload = isRecord(message.payload)
13
- ? message.payload
14
- : {};
15
- return JSON.stringify([
16
- collectionId,
17
- message.senderId,
18
- payload.type,
19
- payload.txId,
20
- payload.resetEpoch,
21
- payload.term,
22
- payload.seq,
23
- ]);
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
+ ]);
24
23
  }
25
- export function createPersistedCollectionCoordinator(coordination, adapter) {
26
- let adapters = coordinatorCache.get(coordination);
27
- if (!adapters) {
28
- adapters = new WeakMap();
29
- coordinatorCache.set(coordination, adapters);
30
- }
31
- const existing = adapters.get(adapter);
32
- if (existing)
33
- return existing;
34
- const created = new CoordinationPersistenceShim(coordination, adapter);
35
- adapters.set(adapter, created);
36
- return created;
37
- }
38
- class CoordinationPersistenceShim {
39
- coordination;
40
- adapter;
41
- nodeId = safeRandomUUID();
42
- positions = new Map();
43
- appliedEnvelopes = new Map();
44
- relayedMessages = new Set();
45
- service;
46
- server;
47
- pendingRelays = 0;
48
- constructor(coordination, adapter) {
49
- this.coordination = coordination;
50
- this.adapter = adapter;
51
- this.service =
52
- coordination.service(PERSISTENCE_SERVICE);
53
- this.server = isCoordinationHost(coordination)
54
- ? coordination.serve(PERSISTENCE_SERVICE, {
55
- ensureLeadership: () => Promise.resolve(),
56
- ensureRemoteSubset: () => Promise.resolve(),
57
- ensurePersistedIndex: (input) => this.adapter.ensureIndex(input.collectionId, input.signature, input.spec),
58
- applyLocalMutations: (input) => this.applyMutations(input),
59
- pullSince: (input) => this.handlePullSince(input),
60
- relayMessage: (input) => this.relayMessage(input),
61
- })
62
- : undefined;
63
- }
64
- getNodeId() {
65
- return this.nodeId;
66
- }
67
- subscribe(collectionId, callback) {
68
- return this.service.events.subscribe("message", (event) => {
69
- if (event.collectionId ===
70
- collectionId) {
71
- callback(event.message);
72
- }
73
- });
74
- }
75
- publish(collectionId, message) {
76
- if (this.server &&
77
- isCoordinationHost(this.coordination) &&
78
- this.coordination.isLeader) {
79
- this.publishMessage({
80
- collectionId,
81
- message,
82
- });
83
- return;
84
- }
85
- if (this.pendingRelays >=
86
- MAX_PENDING_RELAYS) {
87
- console.warn(`Dropping persistence relay for "${collectionId}" because the pending relay limit was reached.`);
88
- return;
89
- }
90
- this.pendingRelays += 1;
91
- void this.service.methods
92
- .relayMessage({
93
- collectionId,
94
- message,
95
- })
96
- .catch((error) => {
97
- console.warn(`Failed to relay persistence message for "${collectionId}".`, error);
98
- })
99
- .finally(() => {
100
- this.pendingRelays -= 1;
101
- });
102
- }
103
- isLeader() {
104
- return (isCoordinationHost(this.coordination) &&
105
- this.coordination.isLeader);
106
- }
107
- ensureLeadership() {
108
- return this.service.methods.ensureLeadership({
109
- collectionId: "*",
110
- });
111
- }
112
- requestEnsureRemoteSubset(collectionId, options) {
113
- // TODO(upstream): Move this normalization into
114
- // @tanstack/db-sqlite-persistence-core so every cross-context
115
- // coordinator receives transport-safe subset options.
116
- const serializableOptions = { ...options };
117
- delete serializableOptions.subscription;
118
- delete serializableOptions.signal;
119
- return this.service.methods.ensureRemoteSubset({
120
- collectionId,
121
- options: serializableOptions,
122
- });
123
- }
124
- requestEnsurePersistedIndex(collectionId, signature, spec) {
125
- return this.service.methods.ensurePersistedIndex({
126
- collectionId,
127
- signature,
128
- spec,
129
- });
130
- }
131
- requestApplyLocalMutations(collectionId, mutations) {
132
- return this.service.methods.applyLocalMutations({
133
- collectionId,
134
- rpcId: safeRandomUUID(),
135
- envelopeId: safeRandomUUID(),
136
- mutations,
137
- });
138
- }
139
- pullSince(collectionId, fromRowVersion) {
140
- return this.service.methods.pullSince({
141
- collectionId,
142
- rpcId: safeRandomUUID(),
143
- fromRowVersion,
144
- });
145
- }
146
- relayMessage(input) {
147
- const key = relayKey(input.collectionId, input.message);
148
- if (this.relayedMessages.has(key)) {
149
- return Promise.resolve();
150
- }
151
- this.relayedMessages.add(key);
152
- if (this.relayedMessages.size >
153
- MAX_DEDUPLICATION_ENTRIES) {
154
- const oldest = this.relayedMessages.values().next()
155
- .value;
156
- if (oldest) {
157
- this.relayedMessages.delete(oldest);
158
- }
159
- }
160
- this.publishMessage(input);
161
- return Promise.resolve();
162
- }
163
- publishMessage(input) {
164
- this.server?.events.publish("message", input);
165
- }
166
- async position(collectionId) {
167
- let position = this.positions.get(collectionId);
168
- if (!position) {
169
- position = Promise.resolve(this.adapter.getStreamPosition?.(collectionId)).then((current) => ({
170
- term: (current?.latestTerm ?? 0) + 1,
171
- seq: current?.latestSeq ?? 0,
172
- rowVersion: current?.latestRowVersion ?? 0,
173
- }));
174
- this.positions.set(collectionId, position);
175
- }
176
- return position;
177
- }
178
- async applyMutations(input) {
179
- const previous = this.appliedEnvelopes.get(input.envelopeId);
180
- if (previous) {
181
- return {
182
- ...previous,
183
- rpcId: input.rpcId,
184
- };
185
- }
186
- const position = await this.position(input.collectionId);
187
- position.seq += 1;
188
- position.rowVersion += 1;
189
- const txId = input.envelopeId;
190
- await this.adapter.applyCommittedTx(input.collectionId, {
191
- txId,
192
- term: position.term,
193
- seq: position.seq,
194
- rowVersion: position.rowVersion,
195
- mutations: input.mutations.map((mutation) => ({
196
- type: mutation.type,
197
- key: mutation.key,
198
- value: mutation.value,
199
- })),
200
- });
201
- const committed = {
202
- v: 1,
203
- dbName: this.coordinationScope(),
204
- collectionId: input.collectionId,
205
- senderId: this.nodeId,
206
- ts: Date.now(),
207
- payload: {
208
- type: "tx:committed",
209
- term: position.term,
210
- seq: position.seq,
211
- txId,
212
- latestRowVersion: position.rowVersion,
213
- requiresFullReload: false,
214
- changedRows: input.mutations
215
- .filter((mutation) => mutation.type !==
216
- "delete")
217
- .map((mutation) => ({
218
- key: mutation.key,
219
- value: mutation.value,
220
- })),
221
- deletedKeys: input.mutations
222
- .filter((mutation) => mutation.type ===
223
- "delete")
224
- .map((mutation) => mutation.key),
225
- },
226
- };
227
- this.publishMessage({
228
- collectionId: input.collectionId,
229
- message: committed,
230
- });
231
- const response = {
232
- type: "rpc:applyLocalMutations:res",
233
- rpcId: input.rpcId,
234
- ok: true,
235
- term: position.term,
236
- seq: position.seq,
237
- latestRowVersion: position.rowVersion,
238
- acceptedMutationIds: input.mutations.map((mutation) => mutation.mutationId),
239
- };
240
- this.appliedEnvelopes.set(input.envelopeId, response);
241
- if (this.appliedEnvelopes.size >
242
- MAX_DEDUPLICATION_ENTRIES) {
243
- const oldest = this.appliedEnvelopes.keys().next()
244
- .value;
245
- if (oldest) {
246
- this.appliedEnvelopes.delete(oldest);
247
- }
248
- }
249
- return response;
250
- }
251
- async handlePullSince(input) {
252
- const position = await this.position(input.collectionId);
253
- const result = await this.adapter.pullSince?.(input.collectionId, input.fromRowVersion);
254
- if (!result || result.requiresFullReload) {
255
- return {
256
- type: "rpc:pullSince:res",
257
- rpcId: input.rpcId,
258
- ok: true,
259
- latestTerm: position.term,
260
- latestSeq: position.seq,
261
- latestRowVersion: result?.latestRowVersion ??
262
- position.rowVersion,
263
- requiresFullReload: true,
264
- };
265
- }
266
- return {
267
- type: "rpc:pullSince:res",
268
- rpcId: input.rpcId,
269
- ok: true,
270
- latestTerm: position.term,
271
- latestSeq: position.seq,
272
- latestRowVersion: result.latestRowVersion,
273
- requiresFullReload: false,
274
- changedKeys: result.changedKeys,
275
- deletedKeys: result.deletedKeys,
276
- deltas: result.deltas,
277
- };
278
- }
279
- coordinationScope() {
280
- return "scope" in this.coordination &&
281
- typeof this.coordination.scope ===
282
- "string"
283
- ? this.coordination.scope
284
- : "party-stack";
285
- }
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;
286
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
+
287
499
  //# sourceMappingURL=createPersistedCollectionCoordinator.js.map