@party-stack/runtime 0.4.1 → 0.4.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"createPersistedCollectionCoordinator.d.ts","names":[],"sources":["../../src/coordinator/createPersistedCollectionCoordinator.ts"],"mappings":";;;wBA+IgB,qCACZ,cAAc,cACd,SAAS,qBACV"}
1
+ {"version":3,"file":"createPersistedCollectionCoordinator.d.ts","names":[],"sources":["../../src/coordinator/createPersistedCollectionCoordinator.ts"],"mappings":";;;wBAqJgB,qCACZ,cAAc,cACd,SAAS,qBACV"}
@@ -1,5 +1,5 @@
1
1
  import { isCoordinationHost } from "@party-stack/coordination";
2
- import { SingleProcessCoordinator, safeRandomUUID, toPersistedCollectionDurabilityError, toTransportedLoadSubsetOptions } from "@tanstack/db-sqlite-persistence-core";
2
+ import { SingleProcessCoordinator, eagerStorageTarget, managedStorageTarget, safeRandomUUID, toPersistedCollectionDurabilityError, toTransportedLoadSubsetOptions } from "@tanstack/db-sqlite-persistence-core";
3
3
  //#region src/coordinator/createPersistedCollectionCoordinator.ts
4
4
  const PERSISTENCE_SERVICE = "party-stack.persistence.v1";
5
5
  const MAX_DEDUPLICATION_ENTRIES = 1e3;
@@ -76,7 +76,9 @@ var CoordinationPersistenceShim = class {
76
76
  visibility.removeEventListener("visibilitychange", onVisible);
77
77
  };
78
78
  }
79
- setAdapterForCollection(collectionId, adapter) {
79
+ setAdapterForCollection(collectionId, adapter, cacheGenerationClaimId) {
80
+ if (cacheGenerationClaimId) this.claims.set(collectionId, cacheGenerationClaimId);
81
+ else this.claims.delete(collectionId);
80
82
  this.collectionAdapters.set(collectionId, adapter);
81
83
  this.positions.delete(collectionId);
82
84
  }
@@ -88,6 +90,11 @@ var CoordinationPersistenceShim = class {
88
90
  schemaVersion(adapter) {
89
91
  return "schemaVersion" in adapter && typeof adapter.schemaVersion === "number" ? adapter.schemaVersion : void 0;
90
92
  }
93
+ claims = /* @__PURE__ */ new Map();
94
+ storageTarget(collectionId, claimId = this.claims.get(collectionId)) {
95
+ if (claimId) this.claims.set(collectionId, claimId);
96
+ return claimId ? managedStorageTarget(collectionId, claimId) : eagerStorageTarget(collectionId);
97
+ }
91
98
  positions = /* @__PURE__ */ new Map();
92
99
  appliedEnvelopes = /* @__PURE__ */ new Map();
93
100
  relayedMessages = /* @__PURE__ */ new Set();
@@ -128,7 +135,7 @@ var CoordinationPersistenceShim = class {
128
135
  return options ? this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options) : Promise.resolve();
129
136
  },
130
137
  applyCommittedTx: (input) => this.applyCommittedTx(input),
131
- ensurePersistedIndex: (input) => this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(input.collectionId, input.signature, input.spec),
138
+ ensurePersistedIndex: (input) => this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(this.storageTarget(input.collectionId, input.cacheGenerationClaimId), input.signature, input.spec),
132
139
  applyLocalMutations: (input) => this.applyMutations(input),
133
140
  pullSince: (input) => this.handlePullSince(input),
134
141
  relayMessage: (input) => this.relayMessage(input)
@@ -158,7 +165,7 @@ var CoordinationPersistenceShim = class {
158
165
  try {
159
166
  if (!active) return;
160
167
  const adapter = this.adapterForCollection(collectionId);
161
- const current = await adapter.getStreamPosition?.(collectionId);
168
+ const current = await adapter.getStreamPosition?.(this.storageTarget(collectionId));
162
169
  if (!active) return;
163
170
  if (!force && current && observed && current.latestTerm === observed.latestTerm && current.latestSeq === observed.latestSeq && current.latestRowVersion === observed.latestRowVersion) return;
164
171
  callback({
@@ -205,6 +212,7 @@ var CoordinationPersistenceShim = class {
205
212
  else {
206
213
  this.collectionSubscriptions.delete(collectionId);
207
214
  this.collectionAdapters.delete(collectionId);
215
+ this.claims.delete(collectionId);
208
216
  this.positions.delete(collectionId);
209
217
  }
210
218
  }
@@ -289,7 +297,7 @@ var CoordinationPersistenceShim = class {
289
297
  }
290
298
  async applyCommittedTx({ collectionId, tx, schemaVersion }, scopedAdapter) {
291
299
  try {
292
- await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(collectionId, tx);
300
+ await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(this.storageTarget(collectionId, tx.cacheGenerationClaimId), tx);
293
301
  } catch (error) {
294
302
  throw toPersistedCollectionDurabilityError(collectionId, error);
295
303
  }
@@ -303,16 +311,17 @@ var CoordinationPersistenceShim = class {
303
311
  latestRowVersion: tx.rowVersion
304
312
  };
305
313
  }
306
- requestEnsurePersistedIndex(collectionId, signature, spec, scopedAdapter, localEnsureCompleted) {
307
- if (this.isLeader()) return localEnsureCompleted ? Promise.resolve() : (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(collectionId, signature, spec);
314
+ requestEnsurePersistedIndex(collectionId, signature, spec, scopedAdapter, localEnsureCompleted, cacheGenerationClaimId) {
315
+ if (this.isLeader()) return localEnsureCompleted ? Promise.resolve() : (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(this.storageTarget(collectionId, cacheGenerationClaimId), signature, spec);
308
316
  return this.service.methods.ensurePersistedIndex({
309
317
  collectionId,
310
318
  signature,
311
319
  spec,
320
+ cacheGenerationClaimId,
312
321
  schemaVersion: this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ?? this.schemaVersion(this.adapterForCollection(collectionId))
313
322
  });
314
323
  }
315
- async requestApplyLocalMutations(collectionId, mutations) {
324
+ async requestApplyLocalMutations(collectionId, mutations, cacheGenerationClaimId) {
316
325
  const envelopeId = safeRandomUUID();
317
326
  const burst = this.resumeChecks.has(collectionId) ? this.localMutationBursts.get(collectionId) ?? {
318
327
  pending: /* @__PURE__ */ new Set(),
@@ -331,7 +340,8 @@ var CoordinationPersistenceShim = class {
331
340
  rpcId: safeRandomUUID(),
332
341
  envelopeId,
333
342
  schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),
334
- mutations
343
+ mutations,
344
+ cacheGenerationClaimId
335
345
  });
336
346
  } finally {
337
347
  burst?.pending.delete(envelopeId);
@@ -342,13 +352,16 @@ var CoordinationPersistenceShim = class {
342
352
  }, 0);
343
353
  }
344
354
  }
345
- pullSince(collectionId, fromRowVersion) {
346
- return this.service.methods.pullSince({
355
+ pullSince(collectionId, fromRowVersion, scopedAdapter, cacheGenerationClaimId) {
356
+ this.storageTarget(collectionId, cacheGenerationClaimId);
357
+ const input = {
347
358
  collectionId,
348
359
  rpcId: safeRandomUUID(),
349
360
  fromRowVersion,
361
+ cacheGenerationClaimId,
350
362
  schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId))
351
- });
363
+ };
364
+ return scopedAdapter && this.isLeader() ? this.handlePullSince(input, scopedAdapter) : this.service.methods.pullSince(input);
352
365
  }
353
366
  relayMessage(input) {
354
367
  const key = relayKey(input.collectionId, input.message);
@@ -368,7 +381,7 @@ var CoordinationPersistenceShim = class {
368
381
  let position = this.positions.get(collectionId);
369
382
  if (!position) {
370
383
  const adapter = this.adapterForCollection(collectionId);
371
- position = Promise.resolve(adapter.getStreamPosition ? adapter.getStreamPosition(collectionId) : adapter.loadResumeSnapshot(collectionId, { includeRows: false })).then((current) => ({
384
+ position = Promise.resolve(adapter.getStreamPosition ? adapter.getStreamPosition(this.storageTarget(collectionId)) : adapter.loadResumeSnapshot(this.storageTarget(collectionId), { includeRows: false })).then((current) => ({
372
385
  term: (current?.latestTerm ?? 0) + 1,
373
386
  seq: current?.latestSeq ?? 0,
374
387
  rowVersion: current?.latestRowVersion ?? 0
@@ -393,6 +406,7 @@ var CoordinationPersistenceShim = class {
393
406
  ...previous,
394
407
  rpcId: input.rpcId
395
408
  };
409
+ this.storageTarget(input.collectionId, input.cacheGenerationClaimId);
396
410
  const position = await this.position(input.collectionId);
397
411
  const nextPosition = {
398
412
  ...position,
@@ -400,7 +414,8 @@ var CoordinationPersistenceShim = class {
400
414
  rowVersion: position.rowVersion + 1
401
415
  };
402
416
  const txId = input.envelopeId;
403
- await adapter.applyCommittedTx(input.collectionId, {
417
+ await adapter.applyCommittedTx(this.storageTarget(input.collectionId, input.cacheGenerationClaimId), {
418
+ cacheGenerationClaimId: input.cacheGenerationClaimId,
404
419
  txId,
405
420
  term: nextPosition.term,
406
421
  seq: nextPosition.seq,
@@ -458,15 +473,15 @@ var CoordinationPersistenceShim = class {
458
473
  }
459
474
  return response;
460
475
  }
461
- async handlePullSince(input) {
462
- const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);
463
- const current = await adapter.getStreamPosition?.(input.collectionId);
476
+ async handlePullSince(input, scopedAdapter) {
477
+ const adapter = scopedAdapter ?? this.adapterForCollection(input.collectionId, input.schemaVersion);
478
+ const current = await adapter.getStreamPosition?.(this.storageTarget(input.collectionId, input.cacheGenerationClaimId));
464
479
  const position = current ? {
465
480
  term: current.latestTerm,
466
481
  seq: current.latestSeq,
467
482
  rowVersion: current.latestRowVersion
468
483
  } : await this.position(input.collectionId);
469
- const result = await adapter.pullSince?.(input.collectionId, input.fromRowVersion);
484
+ const result = await adapter.pullSince?.(this.storageTarget(input.collectionId, input.cacheGenerationClaimId), input.fromRowVersion);
470
485
  if (!result || result.requiresFullReload) return {
471
486
  type: "rpc:pullSince:res",
472
487
  rpcId: input.rpcId,
@@ -1 +1 @@
1
- {"version":3,"file":"createPersistedCollectionCoordinator.js","names":[],"sources":["../../src/coordinator/createPersistedCollectionCoordinator.ts"],"sourcesContent":["import {\n isCoordinationHost,\n type Coordination,\n type CoordinationServiceClient,\n type CoordinationServiceServer,\n} from \"@party-stack/coordination\";\nimport {\n safeRandomUUID,\n SingleProcessCoordinator,\n toTransportedLoadSubsetOptions,\n toPersistedCollectionDurabilityError,\n} from \"@tanstack/db-sqlite-persistence-core\";\nimport type { LoadSubsetOptions } from \"@tanstack/db\";\nimport type {\n ApplyLocalMutationsResponse,\n ApplyCommittedTxResponse,\n HydrationPersistenceAdapter,\n PersistedCollectionCoordinator,\n PersistedIndexSpec,\n PersistedMutationEnvelope,\n PersistenceAdapter,\n PersistedTx,\n RemoteSubsetOwner,\n ProtocolEnvelope,\n PullSinceResponse,\n ReplayableTxDelta,\n} from \"@tanstack/db-sqlite-persistence-core\";\n\nconst PERSISTENCE_SERVICE = \"party-stack.persistence.v1\";\nconst MAX_DEDUPLICATION_ENTRIES = 1_000;\nconst MAX_PENDING_RELAYS = 1_000;\nconst MAX_COLLECTION_POSITIONS = 128;\n\ninterface CollectionPosition {\n term: number;\n seq: number;\n rowVersion: number;\n}\n\ninterface EnsureLeadershipInput {\n collectionId: string;\n}\n\ninterface EnsureRemoteSubsetInput {\n collectionId: string;\n options: LoadSubsetOptions;\n acquisitionId: string;\n}\n\ninterface ApplyCommittedTxInput {\n schemaVersion?: number;\n collectionId: string;\n tx: PersistedTx;\n}\n\ninterface EnsurePersistedIndexInput {\n schemaVersion?: number;\n collectionId: string;\n signature: string;\n spec: PersistedIndexSpec;\n}\n\ninterface ApplyLocalMutationsInput {\n schemaVersion?: number;\n collectionId: string;\n rpcId: string;\n envelopeId: string;\n mutations: PersistedMutationEnvelope[];\n}\n\ninterface PullSinceInput {\n schemaVersion?: number;\n collectionId: string;\n rpcId: string;\n fromRowVersion: number;\n}\n\ninterface RelayMessageInput {\n collectionId: string;\n message: ProtocolEnvelope<unknown>;\n}\n\ninterface PersistenceCoordinationService {\n methods: {\n ensureLeadership(input: EnsureLeadershipInput): Promise<void>;\n ensureRemoteSubset(input: EnsureRemoteSubsetInput): Promise<void>;\n releaseRemoteSubset(input: EnsureRemoteSubsetInput): Promise<void>;\n applyCommittedTx(input: ApplyCommittedTxInput): Promise<ApplyCommittedTxResponse>;\n ensurePersistedIndex(input: EnsurePersistedIndexInput): Promise<void>;\n applyLocalMutations(input: ApplyLocalMutationsInput): Promise<ApplyLocalMutationsResponse>;\n pullSince(input: PullSinceInput): Promise<PullSinceResponse>;\n relayMessage(input: RelayMessageInput): Promise<void>;\n };\n events: {\n message: RelayMessageInput;\n };\n}\n\ntype AdapterWithPullSince = PersistenceAdapter & {\n pullSince?: (\n collectionId: string,\n fromRowVersion: number\n ) => Promise<\n | {\n latestRowVersion: number;\n latestTerm?: number;\n latestSeq?: number;\n requiresFullReload: true;\n }\n | {\n latestRowVersion: number;\n latestTerm?: number;\n latestSeq?: number;\n requiresFullReload: false;\n changedKeys: Array<string | number>;\n deletedKeys: Array<string | number>;\n deltas?: Array<ReplayableTxDelta<Record<string, unknown>, string | number>>;\n }\n >;\n};\n\nconst coordinatorCache = new WeakMap<\n Coordination,\n WeakMap<PersistenceAdapter, PersistedCollectionCoordinator>\n>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction relayKey(collectionId: string, message: ProtocolEnvelope<unknown>): string {\n const payload = isRecord(message.payload) ? message.payload : {};\n return JSON.stringify([\n collectionId,\n message.senderId,\n payload.type,\n payload.txId,\n payload.resetEpoch,\n payload.term,\n payload.seq,\n ]);\n}\n\nexport function createPersistedCollectionCoordinator(\n coordination: Coordination,\n adapter: PersistenceAdapter\n): PersistedCollectionCoordinator {\n let adapters = coordinatorCache.get(coordination);\n if (!adapters) {\n adapters = new WeakMap();\n coordinatorCache.set(coordination, adapters);\n }\n const existing = adapters.get(adapter);\n if (existing) return existing;\n\n const created = new CoordinationPersistenceShim(coordination, adapter);\n adapters.set(adapter, created);\n return created;\n}\n\nclass CoordinationPersistenceShim implements PersistedCollectionCoordinator {\n private readonly nodeId = safeRandomUUID();\n private readonly collectionAdapters = new Map<string, AdapterWithPullSince>();\n private readonly collectionSubscriptions = new Map<string, number>();\n private readonly resumeChecks = new Map<string, Set<(force?: boolean) => Promise<void>>>();\n private readonly localMutationBursts = new Map<\n string,\n {\n pending: Set<string>;\n needsReload: boolean;\n timer?: ReturnType<typeof setTimeout>;\n }\n >();\n private stopResumeListeners: (() => void) | undefined;\n private checkingResume = false;\n private resumeRequested = false;\n\n private requestResumeCheck = (): void => {\n this.resumeRequested = true;\n if (this.checkingResume) return;\n this.checkingResume = true;\n void (async () => {\n try {\n while (this.resumeRequested && this.resumeChecks.size > 0) {\n this.resumeRequested = false;\n await Promise.all(\n [...this.resumeChecks.values()].flatMap((checks) =>\n [...checks].map((check) => check())\n )\n );\n }\n } finally {\n this.checkingResume = false;\n this.resumeRequested = false;\n }\n })();\n };\n\n private startResumeListeners(): void {\n if (this.stopResumeListeners || typeof window === \"undefined\" || typeof document === \"undefined\")\n return;\n const page = window;\n const visibility = document;\n const onVisible = () => {\n if (visibility.visibilityState === \"visible\") this.requestResumeCheck();\n };\n page.addEventListener(\"pageshow\", this.requestResumeCheck);\n page.addEventListener(\"focus\", onVisible);\n visibility.addEventListener(\"visibilitychange\", onVisible);\n this.stopResumeListeners = () => {\n page.removeEventListener(\"pageshow\", this.requestResumeCheck);\n page.removeEventListener(\"focus\", onVisible);\n visibility.removeEventListener(\"visibilitychange\", onVisible);\n };\n }\n\n setAdapterForCollection(collectionId: string, adapter: HydrationPersistenceAdapter): void {\n this.collectionAdapters.set(collectionId, adapter);\n this.positions.delete(collectionId);\n }\n\n private adapterForCollection(collectionId: string, schemaVersion?: number): AdapterWithPullSince {\n const adapter = this.collectionAdapters.get(collectionId) ?? this.adapter;\n if (schemaVersion !== undefined && this.schemaVersion(adapter) !== schemaVersion) {\n throw new Error(\n `Persistence schema mismatch for collection \"${collectionId}\". Reload the coordination host before writing through another schema version.`\n );\n }\n return adapter;\n }\n\n private schemaVersion(adapter: PersistenceAdapter): number | undefined {\n return \"schemaVersion\" in adapter && typeof adapter.schemaVersion === \"number\"\n ? adapter.schemaVersion\n : undefined;\n }\n private readonly positions = new Map<string, Promise<CollectionPosition>>();\n private readonly appliedEnvelopes = new Map<string, Extract<ApplyLocalMutationsResponse, { ok: true }>>();\n private readonly relayedMessages = new Set<string>();\n private readonly service: CoordinationServiceClient<PersistenceCoordinationService>;\n private readonly server: CoordinationServiceServer<PersistenceCoordinationService> | undefined;\n private pendingRelays = 0;\n private readonly remoteSubsets = new SingleProcessCoordinator();\n private readonly acquisitionIds = new WeakMap<LoadSubsetOptions, Map<string, string>>();\n private readonly remoteAcquisitions = new Map<\n string,\n {\n collectionId: string;\n options: LoadSubsetOptions;\n }\n >();\n\n constructor(\n private readonly coordination: Coordination,\n private readonly adapter: AdapterWithPullSince\n ) {\n this.service = coordination.service<PersistenceCoordinationService>(PERSISTENCE_SERVICE);\n this.server = isCoordinationHost(coordination)\n ? coordination.serve<PersistenceCoordinationService>(PERSISTENCE_SERVICE, {\n ensureLeadership: () => Promise.resolve(),\n ensureRemoteSubset: async (input) => {\n let options = this.remoteAcquisitions.get(input.acquisitionId)?.options;\n if (!options) {\n options = input.options;\n this.remoteAcquisitions.set(input.acquisitionId, {\n collectionId: input.collectionId,\n options,\n });\n }\n try {\n await this.remoteSubsets.requestEnsureRemoteSubset(input.collectionId, options);\n } catch (error) {\n // Owner invocation transfers a lease even if loading fails.\n // Release it before dropping our strong reference to its options.\n if (this.remoteAcquisitions.get(input.acquisitionId)?.options === options) {\n this.remoteAcquisitions.delete(input.acquisitionId);\n await this.remoteSubsets\n .requestReleaseRemoteSubset(input.collectionId, options)\n .catch(() => undefined);\n }\n throw error;\n }\n },\n releaseRemoteSubset: (input) => {\n const options = this.remoteAcquisitions.get(input.acquisitionId)?.options;\n this.remoteAcquisitions.delete(input.acquisitionId);\n return options\n ? this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options)\n : Promise.resolve();\n },\n applyCommittedTx: (input) => this.applyCommittedTx(input),\n ensurePersistedIndex: (input) =>\n this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(\n input.collectionId,\n input.signature,\n input.spec\n ),\n applyLocalMutations: (input) => this.applyMutations(input),\n pullSince: (input) => this.handlePullSince(input),\n relayMessage: (input) => this.relayMessage(input),\n })\n : undefined;\n }\n\n getNodeId(): string {\n return this.nodeId;\n }\n\n subscribe(collectionId: string, callback: (message: ProtocolEnvelope<unknown>) => void): () => void {\n let active = true;\n let observed: { latestTerm: number; latestSeq: number; latestRowVersion: number } | undefined;\n const unsubscribe = this.service.events.subscribe(\"message\", (event) => {\n if (!active) return;\n if (event.collectionId === collectionId) {\n const payload = event.message.payload;\n const burst = this.localMutationBursts.get(collectionId);\n if (\n burst &&\n isRecord(payload) &&\n payload.type === \"tx:committed\" &&\n typeof payload.txId === \"string\" &&\n !burst.pending.has(payload.txId)\n ) {\n burst.needsReload = true;\n }\n if (\n isRecord(payload) &&\n payload.type === \"tx:committed\" &&\n typeof payload.term === \"number\" &&\n typeof payload.seq === \"number\" &&\n typeof payload.latestRowVersion === \"number\" &&\n (!observed ||\n payload.term > observed.latestTerm ||\n (payload.term === observed.latestTerm && payload.seq > observed.latestSeq))\n ) {\n observed = {\n latestTerm: payload.term,\n latestSeq: payload.seq,\n latestRowVersion: payload.latestRowVersion,\n };\n }\n callback(event.message);\n }\n });\n const checkResume = async (force = false) => {\n try {\n if (!active) return;\n const adapter = this.adapterForCollection(collectionId);\n const current = await adapter.getStreamPosition?.(collectionId);\n if (!active) return;\n if (\n !force &&\n current &&\n observed &&\n current.latestTerm === observed.latestTerm &&\n current.latestSeq === observed.latestSeq &&\n current.latestRowVersion === observed.latestRowVersion\n )\n return;\n // A local reset notification makes upstream reload active subsets atomically.\n // No storage reset or broadcast is performed. Before our first notification,\n // the hydration position is unknown, so a resume conservatively reloads once.\n callback({\n v: 1,\n dbName: this.coordinationScope(),\n collectionId,\n senderId: `resume:${this.nodeId}`,\n ts: Date.now(),\n payload: {\n type: \"collection:reset\",\n schemaVersion: this.schemaVersion(adapter) ?? 1,\n resetEpoch: 0,\n },\n });\n observed = current;\n } catch (error) {\n if (active) console.warn(`Failed to refresh resumed collection \"${collectionId}\".`, error);\n }\n };\n const checks = this.resumeChecks.get(collectionId) ?? new Set();\n checks.add(checkResume);\n this.resumeChecks.set(collectionId, checks);\n this.startResumeListeners();\n this.collectionSubscriptions.set(\n collectionId,\n (this.collectionSubscriptions.get(collectionId) ?? 0) + 1\n );\n return () => {\n if (!active) return;\n active = false;\n checks.delete(checkResume);\n if (checks.size === 0) {\n this.resumeChecks.delete(collectionId);\n const burst = this.localMutationBursts.get(collectionId);\n if (burst?.timer !== undefined) clearTimeout(burst.timer);\n this.localMutationBursts.delete(collectionId);\n }\n if (this.resumeChecks.size === 0) {\n this.stopResumeListeners?.();\n this.stopResumeListeners = undefined;\n }\n try {\n unsubscribe();\n } finally {\n const remaining = this.collectionSubscriptions.get(collectionId)! - 1;\n if (remaining > 0) {\n this.collectionSubscriptions.set(collectionId, remaining);\n } else {\n this.collectionSubscriptions.delete(collectionId);\n this.collectionAdapters.delete(collectionId);\n this.positions.delete(collectionId);\n }\n }\n };\n }\n\n publish(collectionId: string, message: ProtocolEnvelope<unknown>): void {\n if (this.server && isCoordinationHost(this.coordination) && this.coordination.isLeader) {\n this.publishMessage({\n collectionId,\n message,\n });\n return;\n }\n if (this.pendingRelays >= MAX_PENDING_RELAYS) {\n console.warn(\n `Dropping persistence relay for \"${collectionId}\" because the pending relay limit was reached.`\n );\n return;\n }\n this.pendingRelays += 1;\n void this.service.methods\n .relayMessage({\n collectionId,\n message,\n })\n .catch((error: unknown) => {\n console.warn(`Failed to relay persistence message for \"${collectionId}\".`, error);\n })\n .finally(() => {\n this.pendingRelays -= 1;\n });\n }\n\n isLeader(): boolean {\n return isCoordinationHost(this.coordination) && this.coordination.isLeader;\n }\n\n ensureLeadership(): Promise<void> {\n return this.service.methods.ensureLeadership({\n collectionId: \"*\",\n });\n }\n\n requestEnsureRemoteSubset(collectionId: string, options: LoadSubsetOptions): Promise<void> {\n let collectionIds = this.acquisitionIds.get(options);\n if (!collectionIds) {\n collectionIds = new Map();\n this.acquisitionIds.set(options, collectionIds);\n }\n let acquisitionId = collectionIds.get(collectionId);\n if (!acquisitionId) {\n acquisitionId = safeRandomUUID();\n collectionIds.set(collectionId, acquisitionId);\n }\n return this.service.methods.ensureRemoteSubset({\n collectionId,\n options: toTransportedLoadSubsetOptions(options) as LoadSubsetOptions,\n acquisitionId,\n });\n }\n\n requestReleaseRemoteSubset(collectionId: string, options: LoadSubsetOptions): Promise<void> {\n const collectionIds = this.acquisitionIds.get(options);\n const acquisitionId = collectionIds?.get(collectionId);\n if (!acquisitionId) return Promise.resolve();\n collectionIds!.delete(collectionId);\n if (collectionIds!.size === 0) this.acquisitionIds.delete(options);\n return this.service.methods.releaseRemoteSubset({ collectionId, options: {}, acquisitionId });\n }\n\n registerRemoteSubsetOwner(collectionId: string, owner: RemoteSubsetOwner): () => void {\n const unregister = this.remoteSubsets.registerRemoteSubsetOwner(collectionId, owner);\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n unregister();\n for (const [id, acquisition] of this.remoteAcquisitions) {\n if (acquisition.collectionId === collectionId) this.remoteAcquisitions.delete(id);\n }\n };\n }\n\n requestApplyCommittedTx(\n collectionId: string,\n tx: PersistedTx,\n scopedAdapter?: HydrationPersistenceAdapter\n ): Promise<ApplyCommittedTxResponse> {\n return this.isLeader()\n ? this.applyCommittedTx({ collectionId, tx }, scopedAdapter)\n : this.service.methods.applyCommittedTx({\n collectionId,\n tx,\n schemaVersion:\n this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??\n this.schemaVersion(this.adapterForCollection(collectionId)),\n });\n }\n\n private async applyCommittedTx(\n { collectionId, tx, schemaVersion }: ApplyCommittedTxInput,\n scopedAdapter?: HydrationPersistenceAdapter\n ): Promise<ApplyCommittedTxResponse> {\n try {\n await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(\n collectionId,\n tx\n );\n } catch (error) {\n throw toPersistedCollectionDurabilityError(collectionId, error);\n }\n this.positions.delete(collectionId);\n return {\n type: \"rpc:applyCommittedTx:res\",\n rpcId: safeRandomUUID(),\n ok: true,\n term: tx.term,\n seq: tx.seq,\n latestRowVersion: tx.rowVersion,\n };\n }\n\n requestEnsurePersistedIndex(\n collectionId: string,\n signature: string,\n spec: PersistedIndexSpec,\n scopedAdapter?: HydrationPersistenceAdapter,\n localEnsureCompleted?: boolean\n ): Promise<void> {\n if (this.isLeader()) {\n return localEnsureCompleted\n ? Promise.resolve()\n : (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(\n collectionId,\n signature,\n spec\n );\n }\n return this.service.methods.ensurePersistedIndex({\n collectionId,\n signature,\n spec,\n schemaVersion:\n this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??\n this.schemaVersion(this.adapterForCollection(collectionId)),\n });\n }\n\n async requestApplyLocalMutations(\n collectionId: string,\n mutations: PersistedMutationEnvelope[]\n ): Promise<ApplyLocalMutationsResponse> {\n const envelopeId = safeRandomUUID();\n const burst = this.resumeChecks.has(collectionId)\n ? (this.localMutationBursts.get(collectionId) ?? {\n pending: new Set<string>(),\n needsReload: false,\n timer: undefined,\n })\n : undefined;\n if (burst) {\n if (burst.timer !== undefined) clearTimeout(burst.timer);\n if (burst.pending.size > 0) burst.needsReload = true;\n burst.pending.add(envelopeId);\n this.localMutationBursts.set(collectionId, burst);\n }\n try {\n return await this.service.methods.applyLocalMutations({\n collectionId,\n rpcId: safeRandomUUID(),\n envelopeId,\n schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),\n mutations,\n });\n } finally {\n burst?.pending.delete(envelopeId);\n if (burst && burst.pending.size === 0 && this.localMutationBursts.get(collectionId) === burst) {\n // Upstream advances its observed sequence from local RPC acknowledgements\n // before queued commit messages can run. Reconcile overlapping foreign\n // commits after the local mutation burst, without changing RPC positions.\n burst.timer = setTimeout(() => {\n if (this.localMutationBursts.get(collectionId) !== burst) return;\n this.localMutationBursts.delete(collectionId);\n if (burst.needsReload) {\n for (const check of this.resumeChecks.get(collectionId) ?? []) void check(true);\n }\n }, 0);\n }\n }\n }\n\n pullSince(collectionId: string, fromRowVersion: number): Promise<PullSinceResponse> {\n return this.service.methods.pullSince({\n collectionId,\n rpcId: safeRandomUUID(),\n fromRowVersion,\n schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),\n });\n }\n\n private relayMessage(input: RelayMessageInput): Promise<void> {\n const key = relayKey(input.collectionId, input.message);\n if (this.relayedMessages.has(key)) {\n return Promise.resolve();\n }\n this.relayedMessages.add(key);\n if (this.relayedMessages.size > MAX_DEDUPLICATION_ENTRIES) {\n const oldest = this.relayedMessages.values().next().value;\n if (oldest) {\n this.relayedMessages.delete(oldest);\n }\n }\n this.publishMessage(input);\n return Promise.resolve();\n }\n\n private publishMessage(input: RelayMessageInput): void {\n this.server?.events.publish(\"message\", input);\n }\n\n private async position(collectionId: string): Promise<CollectionPosition> {\n let position = this.positions.get(collectionId);\n if (!position) {\n const adapter = this.adapterForCollection(collectionId);\n position = Promise.resolve(\n adapter.getStreamPosition\n ? adapter.getStreamPosition(collectionId)\n : adapter.loadResumeSnapshot(collectionId, { includeRows: false })\n ).then((current) => ({\n term: (current?.latestTerm ?? 0) + 1,\n seq: current?.latestSeq ?? 0,\n rowVersion: current?.latestRowVersion ?? 0,\n }));\n }\n this.positions.delete(collectionId);\n this.positions.set(collectionId, position);\n while (this.positions.size > MAX_COLLECTION_POSITIONS) {\n const oldest = this.positions.keys().next().value;\n if (oldest !== undefined) this.positions.delete(oldest);\n }\n void position.catch(() => {\n if (this.positions.get(collectionId) === position) this.positions.delete(collectionId);\n });\n return position;\n }\n\n private async applyMutations(input: ApplyLocalMutationsInput): Promise<ApplyLocalMutationsResponse> {\n const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);\n const envelopeKey = JSON.stringify([input.collectionId, input.envelopeId]);\n const previous = this.appliedEnvelopes.get(envelopeKey);\n if (previous) {\n return {\n ...previous,\n rpcId: input.rpcId,\n };\n }\n\n const position = await this.position(input.collectionId);\n const nextPosition = { ...position, seq: position.seq + 1, rowVersion: position.rowVersion + 1 };\n const txId = input.envelopeId;\n await adapter.applyCommittedTx(input.collectionId, {\n txId,\n term: nextPosition.term,\n seq: nextPosition.seq,\n rowVersion: nextPosition.rowVersion,\n mutations: input.mutations.map(({ mutationId, ...mutation }) => {\n void mutationId;\n return mutation;\n }),\n });\n Object.assign(position, nextPosition);\n const committed: ProtocolEnvelope<unknown> = {\n v: 1,\n dbName: this.coordinationScope(),\n collectionId: input.collectionId,\n senderId: this.nodeId,\n ts: Date.now(),\n payload: {\n type: \"tx:committed\",\n term: position.term,\n seq: position.seq,\n txId,\n latestRowVersion: position.rowVersion,\n requiresFullReload: false,\n changedRows: input.mutations\n .filter((mutation) => mutation.type !== \"delete\")\n .map((mutation) => ({\n key: mutation.key,\n value: mutation.value,\n })),\n deletedKeys: input.mutations\n .filter((mutation) => mutation.type === \"delete\")\n .map((mutation) => mutation.key),\n rowMetadataMutations: input.mutations.flatMap((mutation) =>\n mutation.type !== \"delete\" &&\n (mutation.metadataChanged || mutation.metadata !== undefined)\n ? [\n mutation.metadata === undefined\n ? { type: \"delete\" as const, key: mutation.key }\n : { type: \"set\" as const, key: mutation.key, value: mutation.metadata },\n ]\n : []\n ),\n },\n };\n this.publishMessage({\n collectionId: input.collectionId,\n message: committed,\n });\n\n const response: Extract<ApplyLocalMutationsResponse, { ok: true }> = {\n type: \"rpc:applyLocalMutations:res\",\n rpcId: input.rpcId,\n ok: true,\n term: position.term,\n seq: position.seq,\n latestRowVersion: position.rowVersion,\n acceptedMutationIds: input.mutations.map((mutation) => mutation.mutationId),\n };\n this.appliedEnvelopes.set(envelopeKey, response);\n if (this.appliedEnvelopes.size > MAX_DEDUPLICATION_ENTRIES) {\n const oldest = this.appliedEnvelopes.keys().next().value;\n if (oldest) {\n this.appliedEnvelopes.delete(oldest);\n }\n }\n return response;\n }\n\n private async handlePullSince(input: PullSinceInput): Promise<PullSinceResponse> {\n const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);\n const current = await adapter.getStreamPosition?.(input.collectionId);\n const position = current\n ? { term: current.latestTerm, seq: current.latestSeq, rowVersion: current.latestRowVersion }\n : await this.position(input.collectionId);\n const result = await adapter.pullSince?.(input.collectionId, input.fromRowVersion);\n if (!result || result.requiresFullReload) {\n return {\n type: \"rpc:pullSince:res\",\n rpcId: input.rpcId,\n ok: true,\n latestTerm: result?.latestTerm ?? position.term,\n latestSeq: result?.latestSeq ?? position.seq,\n latestRowVersion: result?.latestRowVersion ?? position.rowVersion,\n requiresFullReload: true,\n };\n }\n return {\n type: \"rpc:pullSince:res\",\n rpcId: input.rpcId,\n ok: true,\n latestTerm: result?.latestTerm ?? position.term,\n latestSeq: result?.latestSeq ?? position.seq,\n latestRowVersion: result.latestRowVersion,\n requiresFullReload: false,\n changedKeys: result.changedKeys,\n deletedKeys: result.deletedKeys,\n deltas: result.deltas,\n };\n }\n\n private coordinationScope(): string {\n return \"scope\" in this.coordination && typeof this.coordination.scope === \"string\"\n ? this.coordination.scope\n : \"party-stack\";\n }\n}\n"],"mappings":";;;AA4BA,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAClC,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AA0FjC,MAAM,mCAAmB,IAAI,QAG3B;AAEF,SAAS,SAAS,OAAkD;CAChE,OAAO,OAAO,UAAU,YAAY,UAAU;AAClD;AAEA,SAAS,SAAS,cAAsB,SAA4C;CAChF,MAAM,UAAU,SAAS,QAAQ,OAAO,IAAI,QAAQ,UAAU,CAAC;CAC/D,OAAO,KAAK,UAAU;EAClB;EACA,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;CACZ,CAAC;AACL;AAEA,SAAgB,qCACZ,cACA,SAC8B;CAC9B,IAAI,WAAW,iBAAiB,IAAI,YAAY;CAChD,IAAI,CAAC,UAAU;EACX,2BAAW,IAAI,QAAQ;EACvB,iBAAiB,IAAI,cAAc,QAAQ;CAC/C;CACA,MAAM,WAAW,SAAS,IAAI,OAAO;CACrC,IAAI,UAAU,OAAO;CAErB,MAAM,UAAU,IAAI,4BAA4B,cAAc,OAAO;CACrE,SAAS,IAAI,SAAS,OAAO;CAC7B,OAAO;AACX;AAEA,IAAM,8BAAN,MAA4E;CA6FnD;CACA;CA7FrB,SAA0B,eAAe;CACzC,qCAAsC,IAAI,IA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B;CACV;AACJ"}
1
+ {"version":3,"file":"createPersistedCollectionCoordinator.js","names":[],"sources":["../../src/coordinator/createPersistedCollectionCoordinator.ts"],"sourcesContent":["import {\n isCoordinationHost,\n type Coordination,\n type CoordinationServiceClient,\n type CoordinationServiceServer,\n} from \"@party-stack/coordination\";\nimport {\n safeRandomUUID,\n eagerStorageTarget,\n managedStorageTarget,\n SingleProcessCoordinator,\n toTransportedLoadSubsetOptions,\n toPersistedCollectionDurabilityError,\n} from \"@tanstack/db-sqlite-persistence-core\";\nimport type { LoadSubsetOptions } from \"@tanstack/db\";\nimport type {\n ApplyLocalMutationsResponse,\n ApplyCommittedTxResponse,\n HydrationPersistenceAdapter,\n PersistedCollectionCoordinator,\n PersistedIndexSpec,\n PersistedMutationEnvelope,\n PersistenceAdapter,\n PersistedTx,\n RemoteSubsetOwner,\n ProtocolEnvelope,\n PullSinceResponse,\n ReplayableTxDelta,\n PersistedStorageTarget,\n} from \"@tanstack/db-sqlite-persistence-core\";\n\nconst PERSISTENCE_SERVICE = \"party-stack.persistence.v1\";\nconst MAX_DEDUPLICATION_ENTRIES = 1_000;\nconst MAX_PENDING_RELAYS = 1_000;\nconst MAX_COLLECTION_POSITIONS = 128;\n\ninterface CollectionPosition {\n term: number;\n seq: number;\n rowVersion: number;\n}\n\ninterface EnsureLeadershipInput {\n collectionId: string;\n}\n\ninterface EnsureRemoteSubsetInput {\n collectionId: string;\n options: LoadSubsetOptions;\n acquisitionId: string;\n}\n\ninterface ApplyCommittedTxInput {\n schemaVersion?: number;\n collectionId: string;\n tx: PersistedTx;\n}\n\ninterface EnsurePersistedIndexInput {\n cacheGenerationClaimId?: string;\n schemaVersion?: number;\n collectionId: string;\n signature: string;\n spec: PersistedIndexSpec;\n}\n\ninterface ApplyLocalMutationsInput {\n cacheGenerationClaimId?: string;\n schemaVersion?: number;\n collectionId: string;\n rpcId: string;\n envelopeId: string;\n mutations: PersistedMutationEnvelope[];\n}\n\ninterface PullSinceInput {\n cacheGenerationClaimId?: string;\n schemaVersion?: number;\n collectionId: string;\n rpcId: string;\n fromRowVersion: number;\n}\n\ninterface RelayMessageInput {\n collectionId: string;\n message: ProtocolEnvelope<unknown>;\n}\n\ninterface PersistenceCoordinationService {\n methods: {\n ensureLeadership(input: EnsureLeadershipInput): Promise<void>;\n ensureRemoteSubset(input: EnsureRemoteSubsetInput): Promise<void>;\n releaseRemoteSubset(input: EnsureRemoteSubsetInput): Promise<void>;\n applyCommittedTx(input: ApplyCommittedTxInput): Promise<ApplyCommittedTxResponse>;\n ensurePersistedIndex(input: EnsurePersistedIndexInput): Promise<void>;\n applyLocalMutations(input: ApplyLocalMutationsInput): Promise<ApplyLocalMutationsResponse>;\n pullSince(input: PullSinceInput): Promise<PullSinceResponse>;\n relayMessage(input: RelayMessageInput): Promise<void>;\n };\n events: {\n message: RelayMessageInput;\n };\n}\n\ntype AdapterWithPullSince = PersistenceAdapter & {\n pullSince?: (\n target: PersistedStorageTarget,\n fromRowVersion: number\n ) => Promise<\n | {\n latestRowVersion: number;\n latestTerm?: number;\n latestSeq?: number;\n requiresFullReload: true;\n }\n | {\n latestRowVersion: number;\n latestTerm?: number;\n latestSeq?: number;\n requiresFullReload: false;\n changedKeys: Array<string | number>;\n deletedKeys: Array<string | number>;\n deltas?: Array<ReplayableTxDelta<Record<string, unknown>, string | number>>;\n }\n >;\n};\n\nconst coordinatorCache = new WeakMap<\n Coordination,\n WeakMap<PersistenceAdapter, PersistedCollectionCoordinator>\n>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction relayKey(collectionId: string, message: ProtocolEnvelope<unknown>): string {\n const payload = isRecord(message.payload) ? message.payload : {};\n return JSON.stringify([\n collectionId,\n message.senderId,\n payload.type,\n payload.txId,\n payload.resetEpoch,\n payload.term,\n payload.seq,\n ]);\n}\n\nexport function createPersistedCollectionCoordinator(\n coordination: Coordination,\n adapter: PersistenceAdapter\n): PersistedCollectionCoordinator {\n let adapters = coordinatorCache.get(coordination);\n if (!adapters) {\n adapters = new WeakMap();\n coordinatorCache.set(coordination, adapters);\n }\n const existing = adapters.get(adapter);\n if (existing) return existing;\n\n const created = new CoordinationPersistenceShim(coordination, adapter);\n adapters.set(adapter, created);\n return created;\n}\n\nclass CoordinationPersistenceShim implements PersistedCollectionCoordinator {\n private readonly nodeId = safeRandomUUID();\n private readonly collectionAdapters = new Map<string, AdapterWithPullSince>();\n private readonly collectionSubscriptions = new Map<string, number>();\n private readonly resumeChecks = new Map<string, Set<(force?: boolean) => Promise<void>>>();\n private readonly localMutationBursts = new Map<\n string,\n {\n pending: Set<string>;\n needsReload: boolean;\n timer?: ReturnType<typeof setTimeout>;\n }\n >();\n private stopResumeListeners: (() => void) | undefined;\n private checkingResume = false;\n private resumeRequested = false;\n\n private requestResumeCheck = (): void => {\n this.resumeRequested = true;\n if (this.checkingResume) return;\n this.checkingResume = true;\n void (async () => {\n try {\n while (this.resumeRequested && this.resumeChecks.size > 0) {\n this.resumeRequested = false;\n await Promise.all(\n [...this.resumeChecks.values()].flatMap((checks) =>\n [...checks].map((check) => check())\n )\n );\n }\n } finally {\n this.checkingResume = false;\n this.resumeRequested = false;\n }\n })();\n };\n\n private startResumeListeners(): void {\n if (this.stopResumeListeners || typeof window === \"undefined\" || typeof document === \"undefined\")\n return;\n const page = window;\n const visibility = document;\n const onVisible = () => {\n if (visibility.visibilityState === \"visible\") this.requestResumeCheck();\n };\n page.addEventListener(\"pageshow\", this.requestResumeCheck);\n page.addEventListener(\"focus\", onVisible);\n visibility.addEventListener(\"visibilitychange\", onVisible);\n this.stopResumeListeners = () => {\n page.removeEventListener(\"pageshow\", this.requestResumeCheck);\n page.removeEventListener(\"focus\", onVisible);\n visibility.removeEventListener(\"visibilitychange\", onVisible);\n };\n }\n\n setAdapterForCollection(\n collectionId: string,\n adapter: HydrationPersistenceAdapter,\n cacheGenerationClaimId?: string\n ): void {\n if (cacheGenerationClaimId) this.claims.set(collectionId, cacheGenerationClaimId);\n else this.claims.delete(collectionId);\n this.collectionAdapters.set(collectionId, adapter);\n this.positions.delete(collectionId);\n }\n\n private adapterForCollection(collectionId: string, schemaVersion?: number): AdapterWithPullSince {\n const adapter = this.collectionAdapters.get(collectionId) ?? this.adapter;\n if (schemaVersion !== undefined && this.schemaVersion(adapter) !== schemaVersion) {\n throw new Error(\n `Persistence schema mismatch for collection \"${collectionId}\". Reload the coordination host before writing through another schema version.`\n );\n }\n return adapter;\n }\n\n private schemaVersion(adapter: PersistenceAdapter): number | undefined {\n return \"schemaVersion\" in adapter && typeof adapter.schemaVersion === \"number\"\n ? adapter.schemaVersion\n : undefined;\n }\n private readonly claims = new Map<string, string>();\n private storageTarget(\n collectionId: string,\n claimId = this.claims.get(collectionId)\n ): PersistedStorageTarget {\n if (claimId) this.claims.set(collectionId, claimId);\n return claimId ? managedStorageTarget(collectionId, claimId) : eagerStorageTarget(collectionId);\n }\n private readonly positions = new Map<string, Promise<CollectionPosition>>();\n private readonly appliedEnvelopes = new Map<string, Extract<ApplyLocalMutationsResponse, { ok: true }>>();\n private readonly relayedMessages = new Set<string>();\n private readonly service: CoordinationServiceClient<PersistenceCoordinationService>;\n private readonly server: CoordinationServiceServer<PersistenceCoordinationService> | undefined;\n private pendingRelays = 0;\n private readonly remoteSubsets = new SingleProcessCoordinator();\n private readonly acquisitionIds = new WeakMap<LoadSubsetOptions, Map<string, string>>();\n private readonly remoteAcquisitions = new Map<\n string,\n {\n collectionId: string;\n options: LoadSubsetOptions;\n }\n >();\n\n constructor(\n private readonly coordination: Coordination,\n private readonly adapter: AdapterWithPullSince\n ) {\n this.service = coordination.service<PersistenceCoordinationService>(PERSISTENCE_SERVICE);\n this.server = isCoordinationHost(coordination)\n ? coordination.serve<PersistenceCoordinationService>(PERSISTENCE_SERVICE, {\n ensureLeadership: () => Promise.resolve(),\n ensureRemoteSubset: async (input) => {\n let options = this.remoteAcquisitions.get(input.acquisitionId)?.options;\n if (!options) {\n options = input.options;\n this.remoteAcquisitions.set(input.acquisitionId, {\n collectionId: input.collectionId,\n options,\n });\n }\n try {\n await this.remoteSubsets.requestEnsureRemoteSubset(input.collectionId, options);\n } catch (error) {\n // Owner invocation transfers a lease even if loading fails.\n // Release it before dropping our strong reference to its options.\n if (this.remoteAcquisitions.get(input.acquisitionId)?.options === options) {\n this.remoteAcquisitions.delete(input.acquisitionId);\n await this.remoteSubsets\n .requestReleaseRemoteSubset(input.collectionId, options)\n .catch(() => undefined);\n }\n throw error;\n }\n },\n releaseRemoteSubset: (input) => {\n const options = this.remoteAcquisitions.get(input.acquisitionId)?.options;\n this.remoteAcquisitions.delete(input.acquisitionId);\n return options\n ? this.remoteSubsets.requestReleaseRemoteSubset(input.collectionId, options)\n : Promise.resolve();\n },\n applyCommittedTx: (input) => this.applyCommittedTx(input),\n ensurePersistedIndex: (input) =>\n this.adapterForCollection(input.collectionId, input.schemaVersion).ensureIndex(\n this.storageTarget(input.collectionId, input.cacheGenerationClaimId),\n input.signature,\n input.spec\n ),\n applyLocalMutations: (input) => this.applyMutations(input),\n pullSince: (input) => this.handlePullSince(input),\n relayMessage: (input) => this.relayMessage(input),\n })\n : undefined;\n }\n\n getNodeId(): string {\n return this.nodeId;\n }\n\n subscribe(collectionId: string, callback: (message: ProtocolEnvelope<unknown>) => void): () => void {\n let active = true;\n let observed: { latestTerm: number; latestSeq: number; latestRowVersion: number } | undefined;\n const unsubscribe = this.service.events.subscribe(\"message\", (event) => {\n if (!active) return;\n if (event.collectionId === collectionId) {\n const payload = event.message.payload;\n const burst = this.localMutationBursts.get(collectionId);\n if (\n burst &&\n isRecord(payload) &&\n payload.type === \"tx:committed\" &&\n typeof payload.txId === \"string\" &&\n !burst.pending.has(payload.txId)\n ) {\n burst.needsReload = true;\n }\n if (\n isRecord(payload) &&\n payload.type === \"tx:committed\" &&\n typeof payload.term === \"number\" &&\n typeof payload.seq === \"number\" &&\n typeof payload.latestRowVersion === \"number\" &&\n (!observed ||\n payload.term > observed.latestTerm ||\n (payload.term === observed.latestTerm && payload.seq > observed.latestSeq))\n ) {\n observed = {\n latestTerm: payload.term,\n latestSeq: payload.seq,\n latestRowVersion: payload.latestRowVersion,\n };\n }\n callback(event.message);\n }\n });\n const checkResume = async (force = false) => {\n try {\n if (!active) return;\n const adapter = this.adapterForCollection(collectionId);\n const current = await adapter.getStreamPosition?.(this.storageTarget(collectionId));\n if (!active) return;\n if (\n !force &&\n current &&\n observed &&\n current.latestTerm === observed.latestTerm &&\n current.latestSeq === observed.latestSeq &&\n current.latestRowVersion === observed.latestRowVersion\n )\n return;\n // A local reset notification makes upstream reload active subsets atomically.\n // No storage reset or broadcast is performed. Before our first notification,\n // the hydration position is unknown, so a resume conservatively reloads once.\n callback({\n v: 1,\n dbName: this.coordinationScope(),\n collectionId,\n senderId: `resume:${this.nodeId}`,\n ts: Date.now(),\n payload: {\n type: \"collection:reset\",\n schemaVersion: this.schemaVersion(adapter) ?? 1,\n resetEpoch: 0,\n },\n });\n observed = current;\n } catch (error) {\n if (active) console.warn(`Failed to refresh resumed collection \"${collectionId}\".`, error);\n }\n };\n const checks = this.resumeChecks.get(collectionId) ?? new Set();\n checks.add(checkResume);\n this.resumeChecks.set(collectionId, checks);\n this.startResumeListeners();\n this.collectionSubscriptions.set(\n collectionId,\n (this.collectionSubscriptions.get(collectionId) ?? 0) + 1\n );\n return () => {\n if (!active) return;\n active = false;\n checks.delete(checkResume);\n if (checks.size === 0) {\n this.resumeChecks.delete(collectionId);\n const burst = this.localMutationBursts.get(collectionId);\n if (burst?.timer !== undefined) clearTimeout(burst.timer);\n this.localMutationBursts.delete(collectionId);\n }\n if (this.resumeChecks.size === 0) {\n this.stopResumeListeners?.();\n this.stopResumeListeners = undefined;\n }\n try {\n unsubscribe();\n } finally {\n const remaining = this.collectionSubscriptions.get(collectionId)! - 1;\n if (remaining > 0) {\n this.collectionSubscriptions.set(collectionId, remaining);\n } else {\n this.collectionSubscriptions.delete(collectionId);\n this.collectionAdapters.delete(collectionId);\n this.claims.delete(collectionId);\n this.positions.delete(collectionId);\n }\n }\n };\n }\n\n publish(collectionId: string, message: ProtocolEnvelope<unknown>): void {\n if (this.server && isCoordinationHost(this.coordination) && this.coordination.isLeader) {\n this.publishMessage({\n collectionId,\n message,\n });\n return;\n }\n if (this.pendingRelays >= MAX_PENDING_RELAYS) {\n console.warn(\n `Dropping persistence relay for \"${collectionId}\" because the pending relay limit was reached.`\n );\n return;\n }\n this.pendingRelays += 1;\n void this.service.methods\n .relayMessage({\n collectionId,\n message,\n })\n .catch((error: unknown) => {\n console.warn(`Failed to relay persistence message for \"${collectionId}\".`, error);\n })\n .finally(() => {\n this.pendingRelays -= 1;\n });\n }\n\n isLeader(): boolean {\n return isCoordinationHost(this.coordination) && this.coordination.isLeader;\n }\n\n ensureLeadership(): Promise<void> {\n return this.service.methods.ensureLeadership({\n collectionId: \"*\",\n });\n }\n\n requestEnsureRemoteSubset(collectionId: string, options: LoadSubsetOptions): Promise<void> {\n let collectionIds = this.acquisitionIds.get(options);\n if (!collectionIds) {\n collectionIds = new Map();\n this.acquisitionIds.set(options, collectionIds);\n }\n let acquisitionId = collectionIds.get(collectionId);\n if (!acquisitionId) {\n acquisitionId = safeRandomUUID();\n collectionIds.set(collectionId, acquisitionId);\n }\n return this.service.methods.ensureRemoteSubset({\n collectionId,\n options: toTransportedLoadSubsetOptions(options) as LoadSubsetOptions,\n acquisitionId,\n });\n }\n\n requestReleaseRemoteSubset(collectionId: string, options: LoadSubsetOptions): Promise<void> {\n const collectionIds = this.acquisitionIds.get(options);\n const acquisitionId = collectionIds?.get(collectionId);\n if (!acquisitionId) return Promise.resolve();\n collectionIds!.delete(collectionId);\n if (collectionIds!.size === 0) this.acquisitionIds.delete(options);\n return this.service.methods.releaseRemoteSubset({ collectionId, options: {}, acquisitionId });\n }\n\n registerRemoteSubsetOwner(collectionId: string, owner: RemoteSubsetOwner): () => void {\n const unregister = this.remoteSubsets.registerRemoteSubsetOwner(collectionId, owner);\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n unregister();\n for (const [id, acquisition] of this.remoteAcquisitions) {\n if (acquisition.collectionId === collectionId) this.remoteAcquisitions.delete(id);\n }\n };\n }\n\n requestApplyCommittedTx(\n collectionId: string,\n tx: PersistedTx,\n scopedAdapter?: HydrationPersistenceAdapter\n ): Promise<ApplyCommittedTxResponse> {\n return this.isLeader()\n ? this.applyCommittedTx({ collectionId, tx }, scopedAdapter)\n : this.service.methods.applyCommittedTx({\n collectionId,\n tx,\n schemaVersion:\n this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??\n this.schemaVersion(this.adapterForCollection(collectionId)),\n });\n }\n\n private async applyCommittedTx(\n { collectionId, tx, schemaVersion }: ApplyCommittedTxInput,\n scopedAdapter?: HydrationPersistenceAdapter\n ): Promise<ApplyCommittedTxResponse> {\n try {\n await (scopedAdapter ?? this.adapterForCollection(collectionId, schemaVersion)).applyCommittedTx(\n this.storageTarget(collectionId, tx.cacheGenerationClaimId),\n tx\n );\n } catch (error) {\n throw toPersistedCollectionDurabilityError(collectionId, error);\n }\n this.positions.delete(collectionId);\n return {\n type: \"rpc:applyCommittedTx:res\",\n rpcId: safeRandomUUID(),\n ok: true,\n term: tx.term,\n seq: tx.seq,\n latestRowVersion: tx.rowVersion,\n };\n }\n\n requestEnsurePersistedIndex(\n collectionId: string,\n signature: string,\n spec: PersistedIndexSpec,\n scopedAdapter?: HydrationPersistenceAdapter,\n localEnsureCompleted?: boolean,\n cacheGenerationClaimId?: string\n ): Promise<void> {\n if (this.isLeader()) {\n return localEnsureCompleted\n ? Promise.resolve()\n : (scopedAdapter ?? this.adapterForCollection(collectionId)).ensureIndex(\n this.storageTarget(collectionId, cacheGenerationClaimId),\n signature,\n spec\n );\n }\n return this.service.methods.ensurePersistedIndex({\n collectionId,\n signature,\n spec,\n cacheGenerationClaimId,\n schemaVersion:\n this.schemaVersion(scopedAdapter ?? this.adapterForCollection(collectionId)) ??\n this.schemaVersion(this.adapterForCollection(collectionId)),\n });\n }\n\n async requestApplyLocalMutations(\n collectionId: string,\n mutations: PersistedMutationEnvelope[],\n cacheGenerationClaimId?: string\n ): Promise<ApplyLocalMutationsResponse> {\n const envelopeId = safeRandomUUID();\n const burst = this.resumeChecks.has(collectionId)\n ? (this.localMutationBursts.get(collectionId) ?? {\n pending: new Set<string>(),\n needsReload: false,\n timer: undefined,\n })\n : undefined;\n if (burst) {\n if (burst.timer !== undefined) clearTimeout(burst.timer);\n if (burst.pending.size > 0) burst.needsReload = true;\n burst.pending.add(envelopeId);\n this.localMutationBursts.set(collectionId, burst);\n }\n try {\n return await this.service.methods.applyLocalMutations({\n collectionId,\n rpcId: safeRandomUUID(),\n envelopeId,\n schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),\n mutations,\n cacheGenerationClaimId,\n });\n } finally {\n burst?.pending.delete(envelopeId);\n if (burst && burst.pending.size === 0 && this.localMutationBursts.get(collectionId) === burst) {\n // Upstream advances its observed sequence from local RPC acknowledgements\n // before queued commit messages can run. Reconcile overlapping foreign\n // commits after the local mutation burst, without changing RPC positions.\n burst.timer = setTimeout(() => {\n if (this.localMutationBursts.get(collectionId) !== burst) return;\n this.localMutationBursts.delete(collectionId);\n if (burst.needsReload) {\n for (const check of this.resumeChecks.get(collectionId) ?? []) void check(true);\n }\n }, 0);\n }\n }\n }\n\n pullSince(\n collectionId: string,\n fromRowVersion: number,\n scopedAdapter?: HydrationPersistenceAdapter,\n cacheGenerationClaimId?: string\n ): Promise<PullSinceResponse> {\n this.storageTarget(collectionId, cacheGenerationClaimId);\n const input = {\n collectionId,\n rpcId: safeRandomUUID(),\n fromRowVersion,\n cacheGenerationClaimId,\n schemaVersion: this.schemaVersion(this.adapterForCollection(collectionId)),\n };\n return scopedAdapter && this.isLeader()\n ? this.handlePullSince(input, scopedAdapter)\n : this.service.methods.pullSince(input);\n }\n\n private relayMessage(input: RelayMessageInput): Promise<void> {\n const key = relayKey(input.collectionId, input.message);\n if (this.relayedMessages.has(key)) {\n return Promise.resolve();\n }\n this.relayedMessages.add(key);\n if (this.relayedMessages.size > MAX_DEDUPLICATION_ENTRIES) {\n const oldest = this.relayedMessages.values().next().value;\n if (oldest) {\n this.relayedMessages.delete(oldest);\n }\n }\n this.publishMessage(input);\n return Promise.resolve();\n }\n\n private publishMessage(input: RelayMessageInput): void {\n this.server?.events.publish(\"message\", input);\n }\n\n private async position(collectionId: string): Promise<CollectionPosition> {\n let position = this.positions.get(collectionId);\n if (!position) {\n const adapter = this.adapterForCollection(collectionId);\n position = Promise.resolve(\n adapter.getStreamPosition\n ? adapter.getStreamPosition(this.storageTarget(collectionId))\n : adapter.loadResumeSnapshot(this.storageTarget(collectionId), { includeRows: false })\n ).then((current) => ({\n term: (current?.latestTerm ?? 0) + 1,\n seq: current?.latestSeq ?? 0,\n rowVersion: current?.latestRowVersion ?? 0,\n }));\n }\n this.positions.delete(collectionId);\n this.positions.set(collectionId, position);\n while (this.positions.size > MAX_COLLECTION_POSITIONS) {\n const oldest = this.positions.keys().next().value;\n if (oldest !== undefined) this.positions.delete(oldest);\n }\n void position.catch(() => {\n if (this.positions.get(collectionId) === position) this.positions.delete(collectionId);\n });\n return position;\n }\n\n private async applyMutations(input: ApplyLocalMutationsInput): Promise<ApplyLocalMutationsResponse> {\n const adapter = this.adapterForCollection(input.collectionId, input.schemaVersion);\n const envelopeKey = JSON.stringify([input.collectionId, input.envelopeId]);\n const previous = this.appliedEnvelopes.get(envelopeKey);\n if (previous) {\n return {\n ...previous,\n rpcId: input.rpcId,\n };\n }\n\n this.storageTarget(input.collectionId, input.cacheGenerationClaimId);\n const position = await this.position(input.collectionId);\n const nextPosition = { ...position, seq: position.seq + 1, rowVersion: position.rowVersion + 1 };\n const txId = input.envelopeId;\n await adapter.applyCommittedTx(this.storageTarget(input.collectionId, input.cacheGenerationClaimId), {\n cacheGenerationClaimId: input.cacheGenerationClaimId,\n txId,\n term: nextPosition.term,\n seq: nextPosition.seq,\n rowVersion: nextPosition.rowVersion,\n mutations: input.mutations.map(({ mutationId, ...mutation }) => {\n void mutationId;\n return mutation;\n }),\n });\n Object.assign(position, nextPosition);\n const committed: ProtocolEnvelope<unknown> = {\n v: 1,\n dbName: this.coordinationScope(),\n collectionId: input.collectionId,\n senderId: this.nodeId,\n ts: Date.now(),\n payload: {\n type: \"tx:committed\",\n term: position.term,\n seq: position.seq,\n txId,\n latestRowVersion: position.rowVersion,\n requiresFullReload: false,\n changedRows: input.mutations\n .filter((mutation) => mutation.type !== \"delete\")\n .map((mutation) => ({\n key: mutation.key,\n value: mutation.value,\n })),\n deletedKeys: input.mutations\n .filter((mutation) => mutation.type === \"delete\")\n .map((mutation) => mutation.key),\n rowMetadataMutations: input.mutations.flatMap((mutation) =>\n mutation.type !== \"delete\" &&\n (mutation.metadataChanged || mutation.metadata !== undefined)\n ? [\n mutation.metadata === undefined\n ? { type: \"delete\" as const, key: mutation.key }\n : { type: \"set\" as const, key: mutation.key, value: mutation.metadata },\n ]\n : []\n ),\n },\n };\n this.publishMessage({\n collectionId: input.collectionId,\n message: committed,\n });\n\n const response: Extract<ApplyLocalMutationsResponse, { ok: true }> = {\n type: \"rpc:applyLocalMutations:res\",\n rpcId: input.rpcId,\n ok: true,\n term: position.term,\n seq: position.seq,\n latestRowVersion: position.rowVersion,\n acceptedMutationIds: input.mutations.map((mutation) => mutation.mutationId),\n };\n this.appliedEnvelopes.set(envelopeKey, response);\n if (this.appliedEnvelopes.size > MAX_DEDUPLICATION_ENTRIES) {\n const oldest = this.appliedEnvelopes.keys().next().value;\n if (oldest) {\n this.appliedEnvelopes.delete(oldest);\n }\n }\n return response;\n }\n\n private async handlePullSince(\n input: PullSinceInput,\n scopedAdapter?: HydrationPersistenceAdapter\n ): Promise<PullSinceResponse> {\n const adapter: AdapterWithPullSince =\n scopedAdapter ?? this.adapterForCollection(input.collectionId, input.schemaVersion);\n const current = await adapter.getStreamPosition?.(\n this.storageTarget(input.collectionId, input.cacheGenerationClaimId)\n );\n const position = current\n ? { term: current.latestTerm, seq: current.latestSeq, rowVersion: current.latestRowVersion }\n : await this.position(input.collectionId);\n const result = await adapter.pullSince?.(\n this.storageTarget(input.collectionId, input.cacheGenerationClaimId),\n input.fromRowVersion\n );\n if (!result || result.requiresFullReload) {\n return {\n type: \"rpc:pullSince:res\",\n rpcId: input.rpcId,\n ok: true,\n latestTerm: result?.latestTerm ?? position.term,\n latestSeq: result?.latestSeq ?? position.seq,\n latestRowVersion: result?.latestRowVersion ?? position.rowVersion,\n requiresFullReload: true,\n };\n }\n return {\n type: \"rpc:pullSince:res\",\n rpcId: input.rpcId,\n ok: true,\n latestTerm: result?.latestTerm ?? position.term,\n latestSeq: result?.latestSeq ?? position.seq,\n latestRowVersion: result.latestRowVersion,\n requiresFullReload: false,\n changedKeys: result.changedKeys,\n deletedKeys: result.deletedKeys,\n deltas: result.deltas,\n };\n }\n\n private coordinationScope(): string {\n return \"scope\" in this.coordination && typeof this.coordination.scope === \"string\"\n ? this.coordination.scope\n : \"party-stack\";\n }\n}\n"],"mappings":";;;AA+BA,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAClC,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AA6FjC,MAAM,mCAAmB,IAAI,QAG3B;AAEF,SAAS,SAAS,OAAkD;CAChE,OAAO,OAAO,UAAU,YAAY,UAAU;AAClD;AAEA,SAAS,SAAS,cAAsB,SAA4C;CAChF,MAAM,UAAU,SAAS,QAAQ,OAAO,IAAI,QAAQ,UAAU,CAAC;CAC/D,OAAO,KAAK,UAAU;EAClB;EACA,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;EACR,QAAQ;CACZ,CAAC;AACL;AAEA,SAAgB,qCACZ,cACA,SAC8B;CAC9B,IAAI,WAAW,iBAAiB,IAAI,YAAY;CAChD,IAAI,CAAC,UAAU;EACX,2BAAW,IAAI,QAAQ;EACvB,iBAAiB,IAAI,cAAc,QAAQ;CAC/C;CACA,MAAM,WAAW,SAAS,IAAI,OAAO;CACrC,I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AI,QACA,KAAK,iBAAiB,OAAO,MAAM;EAE3C;EACA,OAAO;CACX;CAEA,MAAc,gBACV,OACA,eAC0B;EAC1B,MAAM,UACF,iBAAiB,KAAK,qBAAqB,MAAM,cAAc,MAAM,aAAa;EACtF,MAAM,UAAU,MAAM,QAAQ,oBAC1B,KAAK,cAAc,MAAM,cAAc,MAAM,sBAAsB,CACvE;EACA,MAAM,WAAW,UACX;GAAE,MAAM,QAAQ;GAAY,KAAK,QAAQ;GAAW,YAAY,QAAQ;EAAiB,IACzF,MAAM,KAAK,SAAS,MAAM,YAAY;EAC5C,MAAM,SAAS,MAAM,QAAQ,YACzB,KAAK,cAAc,MAAM,cAAc,MAAM,sBAAsB,GACnE,MAAM,cACV;EACA,IAAI,CAAC,UAAU,OAAO,oBAClB,OAAO;GACH,MAAM;GACN,OAAO,MAAM;GACb,IAAI;GACJ,YAAY,QAAQ,cAAc,SAAS;GAC3C,WAAW,QAAQ,aAAa,SAAS;GACzC,kBAAkB,QAAQ,oBAAoB,SAAS;GACvD,oBAAoB;EACxB;EAEJ,OAAO;GACH,MAAM;GACN,OAAO,MAAM;GACb,IAAI;GACJ,YAAY,QAAQ,cAAc,SAAS;GAC3C,WAAW,QAAQ,aAAa,SAAS;GACzC,kBAAkB,OAAO;GACzB,oBAAoB;GACpB,aAAa,OAAO;GACpB,aAAa,OAAO;GACpB,QAAQ,OAAO;EACnB;CACJ;CAEA,oBAAoC;EAChC,OAAO,WAAW,KAAK,gBAAgB,OAAO,KAAK,aAAa,UAAU,WACpE,KAAK,aAAa,QAClB;CACV;AACJ"}
@@ -1,2 +1 @@
1
- import { createPersistedCollectionCoordinator } from "./createPersistedCollectionCoordinator.js";
2
- export { createPersistedCollectionCoordinator };
1
+ export { createPersistedCollectionCoordinator } from "./createPersistedCollectionCoordinator.js";
@@ -5,4 +5,5 @@ type AsyncRuntimeAdapterProvider = (owner: string, namespace: string) => Promise
5
5
  export declare function defineRuntime(provider: SyncRuntimeAdapterProvider): SyncRuntimeAdapterProvider;
6
6
  export declare function defineRuntime(provider: AsyncRuntimeAdapterProvider): AsyncRuntimeAdapterProvider;
7
7
  //#endregion
8
+ export {};
8
9
  //# sourceMappingURL=defineRuntime.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@party-stack/runtime",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "files": [
5
5
  "lib"
6
6
  ],
@@ -20,14 +20,14 @@
20
20
  "@party-stack/coordination": "0.3.1"
21
21
  },
22
22
  "devDependencies": {
23
- "@tanstack/db": "0.12.1",
24
- "@tanstack/db-sqlite-persistence-core": "0.4.5",
23
+ "@tanstack/db": "0.14.0",
24
+ "@tanstack/db-sqlite-persistence-core": "0.4.9",
25
25
  "typescript": "~7.0.2",
26
- "vite-plus": "1.1.0",
27
- "@party-stack/build-config": "0.1.1"
26
+ "vite-plus": "1.2.0",
27
+ "@party-stack/build-config": "0.1.3"
28
28
  },
29
29
  "peerDependencies": {
30
- "@tanstack/db": "0.12.1",
31
- "@tanstack/db-sqlite-persistence-core": "0.4.5"
30
+ "@tanstack/db": "0.14.0",
31
+ "@tanstack/db-sqlite-persistence-core": "0.4.9"
32
32
  }
33
33
  }