@powersync/service-core 1.22.0 → 1.23.0

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 (113) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/api/RouteAPI.d.ts +2 -2
  3. package/dist/api/diagnostics.d.ts +12 -1
  4. package/dist/api/diagnostics.js +34 -22
  5. package/dist/api/diagnostics.js.map +1 -1
  6. package/dist/entry/commands/compact-action.js +1 -1
  7. package/dist/entry/commands/compact-action.js.map +1 -1
  8. package/dist/modules/AbstractModule.d.ts +6 -2
  9. package/dist/modules/AbstractModule.js.map +1 -1
  10. package/dist/replication/AbstractReplicator.d.ts +2 -2
  11. package/dist/replication/AbstractReplicator.js +24 -23
  12. package/dist/replication/AbstractReplicator.js.map +1 -1
  13. package/dist/replication/ReplicationModule.d.ts +3 -3
  14. package/dist/replication/ReplicationModule.js.map +1 -1
  15. package/dist/routes/configure-fastify.d.ts +12 -12
  16. package/dist/routes/endpoints/admin.d.ts +24 -24
  17. package/dist/routes/endpoints/admin.js +44 -34
  18. package/dist/routes/endpoints/admin.js.map +1 -1
  19. package/dist/routes/endpoints/checkpointing.js +1 -1
  20. package/dist/routes/endpoints/checkpointing.js.map +1 -1
  21. package/dist/routes/endpoints/socket-route.js +1 -1
  22. package/dist/routes/endpoints/socket-route.js.map +1 -1
  23. package/dist/routes/endpoints/sync-rules.js +22 -13
  24. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  25. package/dist/routes/endpoints/sync-stream.js +1 -1
  26. package/dist/routes/endpoints/sync-stream.js.map +1 -1
  27. package/dist/runner/teardown.js +8 -8
  28. package/dist/runner/teardown.js.map +1 -1
  29. package/dist/storage/BucketStorageBatch.d.ts +0 -6
  30. package/dist/storage/BucketStorageBatch.js.map +1 -1
  31. package/dist/storage/BucketStorageFactory.d.ts +22 -27
  32. package/dist/storage/BucketStorageFactory.js +4 -18
  33. package/dist/storage/BucketStorageFactory.js.map +1 -1
  34. package/dist/storage/ParsedSyncConfigSet.d.ts +23 -0
  35. package/dist/storage/ParsedSyncConfigSet.js +2 -0
  36. package/dist/storage/ParsedSyncConfigSet.js.map +1 -0
  37. package/dist/storage/PersistedReplicationStream.d.ts +32 -0
  38. package/dist/storage/PersistedReplicationStream.js +26 -0
  39. package/dist/storage/PersistedReplicationStream.js.map +1 -0
  40. package/dist/storage/PersistedSyncConfigContent.d.ts +60 -0
  41. package/dist/storage/PersistedSyncConfigContent.js +123 -0
  42. package/dist/storage/PersistedSyncConfigContent.js.map +1 -0
  43. package/dist/storage/PersistedSyncConfigStatus.d.ts +13 -0
  44. package/dist/storage/PersistedSyncConfigStatus.js +2 -0
  45. package/dist/storage/PersistedSyncConfigStatus.js.map +1 -0
  46. package/dist/storage/SourceTable.d.ts +9 -3
  47. package/dist/storage/SourceTable.js +13 -3
  48. package/dist/storage/SourceTable.js.map +1 -1
  49. package/dist/storage/SyncRulesBucketStorage.d.ts +59 -16
  50. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  51. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +117 -0
  52. package/dist/storage/implementation/BucketDefinitionMapping.js +277 -0
  53. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -0
  54. package/dist/storage/implementation/IncrementalReprocessingCompatibility.d.ts +6 -0
  55. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +31 -0
  56. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -0
  57. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.d.ts +17 -0
  58. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +62 -0
  59. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -0
  60. package/dist/storage/implementation/ReplicationStreamStorageIds.d.ts +15 -0
  61. package/dist/storage/implementation/ReplicationStreamStorageIds.js +20 -0
  62. package/dist/storage/implementation/ReplicationStreamStorageIds.js.map +1 -0
  63. package/dist/storage/storage-index.d.ts +8 -1
  64. package/dist/storage/storage-index.js +8 -1
  65. package/dist/storage/storage-index.js.map +1 -1
  66. package/dist/sync/sync.js +5 -0
  67. package/dist/sync/sync.js.map +1 -1
  68. package/dist/util/checkpointing.js +1 -1
  69. package/dist/util/checkpointing.js.map +1 -1
  70. package/dist/util/config/types.d.ts +1 -1
  71. package/dist/util/lsn.d.ts +4 -0
  72. package/dist/util/lsn.js +10 -0
  73. package/dist/util/lsn.js.map +1 -1
  74. package/package.json +6 -7
  75. package/src/api/RouteAPI.ts +2 -2
  76. package/src/api/diagnostics.ts +43 -26
  77. package/src/entry/commands/compact-action.ts +1 -1
  78. package/src/modules/AbstractModule.ts +6 -2
  79. package/src/replication/AbstractReplicator.ts +27 -26
  80. package/src/replication/ReplicationModule.ts +2 -3
  81. package/src/routes/endpoints/admin.ts +70 -49
  82. package/src/routes/endpoints/checkpointing.ts +1 -1
  83. package/src/routes/endpoints/socket-route.ts +1 -1
  84. package/src/routes/endpoints/sync-rules.ts +23 -13
  85. package/src/routes/endpoints/sync-stream.ts +1 -1
  86. package/src/runner/teardown.ts +8 -8
  87. package/src/storage/BucketStorageBatch.ts +0 -7
  88. package/src/storage/BucketStorageFactory.ts +30 -39
  89. package/src/storage/ParsedSyncConfigSet.ts +25 -0
  90. package/src/storage/PersistedReplicationStream.ts +55 -0
  91. package/src/storage/PersistedSyncConfigContent.ts +188 -0
  92. package/src/storage/PersistedSyncConfigStatus.ts +14 -0
  93. package/src/storage/SourceTable.ts +20 -3
  94. package/src/storage/SyncRulesBucketStorage.ts +64 -16
  95. package/src/storage/implementation/BucketDefinitionMapping.ts +436 -0
  96. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +41 -0
  97. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +109 -0
  98. package/src/storage/implementation/ReplicationStreamStorageIds.ts +21 -0
  99. package/src/storage/storage-index.ts +9 -1
  100. package/src/sync/sync.ts +5 -0
  101. package/src/util/checkpointing.ts +1 -1
  102. package/src/util/config/types.ts +1 -1
  103. package/src/util/lsn.ts +9 -0
  104. package/test/src/diagnostics.test.ts +61 -34
  105. package/test/src/module-loader.test.ts +33 -1
  106. package/test/src/routes/admin.test.ts +180 -18
  107. package/test/src/routes/mocks.ts +6 -2
  108. package/tsconfig.json +1 -4
  109. package/tsconfig.tsbuildinfo +1 -1
  110. package/dist/storage/PersistedSyncRulesContent.d.ts +0 -59
  111. package/dist/storage/PersistedSyncRulesContent.js +0 -100
  112. package/dist/storage/PersistedSyncRulesContent.js.map +0 -1
  113. package/src/storage/PersistedSyncRulesContent.ts +0 -174
@@ -0,0 +1,436 @@
1
+ import { ServiceAssertionError } from '@powersync/lib-services-framework';
2
+ import {
3
+ BucketDataSource,
4
+ BucketDefinitionId,
5
+ HashMap,
6
+ ParameterIndexId,
7
+ ParameterIndexLookupCreator,
8
+ ParameterLookupDefinitionId,
9
+ SerializedBucketDataSourceWithDataSources,
10
+ SerializedParameterIndexLookupCreator,
11
+ serializedStreamBucketDataSourceEquality,
12
+ serializedStreamParameterIndexLookupCreatorEquality,
13
+ SerializedSyncPlanV1,
14
+ SourceTableRef,
15
+ SyncConfigWithErrors
16
+ } from '@powersync/service-sync-rules';
17
+
18
+ export interface SerializedSyncConfigWithMapping {
19
+ plan: SerializedSyncPlanV1;
20
+ mapping: SingleSyncConfigBucketDefinitionMapping;
21
+ }
22
+
23
+ export type IncrementalMappingDefinitionType = 'bucket_data' | 'parameter_lookup';
24
+
25
+ export interface IncrementalMappingDefinitionChange {
26
+ type: IncrementalMappingDefinitionType;
27
+ name: string;
28
+ id: BucketDefinitionId | ParameterIndexId;
29
+ }
30
+
31
+ export interface IncrementalMappingChanges {
32
+ reusedDefinitions: IncrementalMappingDefinitionChange[];
33
+ addedDefinitions: IncrementalMappingDefinitionChange[];
34
+ }
35
+
36
+ export interface IncrementalMappingResult {
37
+ mapping: SingleSyncConfigBucketDefinitionMapping;
38
+ changes: IncrementalMappingChanges;
39
+ }
40
+ export interface SyncConfigWithMapping {
41
+ syncConfigId?: string;
42
+ syncConfig: SyncConfigWithErrors;
43
+ mapping: SingleSyncConfigBucketDefinitionMapping | null;
44
+ }
45
+
46
+ export interface SyncConfigWithRequiredMapping {
47
+ syncConfigId: string;
48
+ syncConfig: SyncConfigWithErrors;
49
+ mapping: SingleSyncConfigBucketDefinitionMapping;
50
+ }
51
+
52
+ export interface PersistedDefinitionMapping {
53
+ /**
54
+ * Map of uniqueName -> id, unique per replication stream.
55
+ */
56
+ definitions: Record<string, string>;
57
+ /**
58
+ * Map of (lookupName, queryId) -> id, unique per replication stream.
59
+ */
60
+ parameter_indexes: Record<string, string>;
61
+ }
62
+
63
+ /**
64
+ * Represents a mapping from bucket data sources and parameter lookup sources to stable IDs used for bucket definition and parameter index persistence.
65
+ *
66
+ * Usage is deliberately restricted: writer/batch paths resolve through their own parsed
67
+ * sync config set's mapping, and read paths resolve through the persisted
68
+ * {@link SingleSyncConfigBucketDefinitionMapping} of the single sync config they serve.
69
+ * Do not construct ad-hoc resolution paths from parsed sources.
70
+ */
71
+ export interface BucketDefinitionMapping {
72
+ /**
73
+ * Given a BucketDataSource within the associated SyncConfig(s), return the BucketDefinitionId, or throw if not found.
74
+ */
75
+ bucketSourceId(source: BucketDataSource): BucketDefinitionId;
76
+
77
+ parameterLookupId(source: ParameterIndexLookupCreator): ParameterIndexId;
78
+
79
+ allBucketDefinitionIds(): BucketDefinitionId[];
80
+
81
+ allParameterIndexIds(): ParameterIndexId[];
82
+
83
+ syncConfigIdsForSourceTable(
84
+ selectedSyncConfigIds: string[],
85
+ table: SourceTableRef,
86
+ bucketDataSourceIds: BucketDefinitionId[],
87
+ parameterLookupSourceIds: ParameterIndexId[]
88
+ ): string[];
89
+
90
+ snapshotBlockingSourceTablesFilter(syncConfigId: string): Record<string, unknown>;
91
+ }
92
+
93
+ /**
94
+ * A BucketDefinitionMapping associated with a single SyncConfig.
95
+ *
96
+ * Within a single SyncConfig, unique names are the persistence key for bucket definitions,
97
+ * so lookups here are name-based by design. MongoHydrationState and
98
+ * MultiSyncConfigBucketDefinitionMapping handle the mapping across multiple SyncConfigs in
99
+ * the same replication stream, where names are not unique.
100
+ */
101
+ export class SingleSyncConfigBucketDefinitionMapping implements BucketDefinitionMapping {
102
+ static fromPersistedMapping(mapping: PersistedDefinitionMapping): SingleSyncConfigBucketDefinitionMapping {
103
+ return new SingleSyncConfigBucketDefinitionMapping(mapping.definitions ?? {}, mapping.parameter_indexes ?? {});
104
+ }
105
+
106
+ static fromParsedSyncConfig(syncConfig: SyncConfigWithErrors): SingleSyncConfigBucketDefinitionMapping {
107
+ const definitionNames = syncConfig.config.bucketDataSources.map((source) => source.uniqueName).sort();
108
+ const parameterKeys = syncConfig.config.bucketParameterLookupSources
109
+ .map((source) => `${source.sourceId.lookupName}#${source.sourceId.queryId}`)
110
+ .sort();
111
+
112
+ const definitions: Record<string, BucketDefinitionId> = {};
113
+ const parameterLookups: Record<string, ParameterIndexId> = {};
114
+
115
+ for (const [index, uniqueName] of definitionNames.entries()) {
116
+ definitions[uniqueName] = (index + 1).toString(16);
117
+ }
118
+ for (const [index, key] of parameterKeys.entries()) {
119
+ parameterLookups[key] = (index + 1).toString(16);
120
+ }
121
+
122
+ return new SingleSyncConfigBucketDefinitionMapping(definitions, parameterLookups);
123
+ }
124
+
125
+ /**
126
+ *
127
+ * @param compatibleConfigs SyncConfigs with definitions that may be re-used
128
+ * @param newPlan
129
+ * @param reservedMappings _all_ mappings used currently and historically for the replication stream; used to construct new ids
130
+ * @returns
131
+ */
132
+ static constructIncrementalMappingFromSerializedPlans(
133
+ compatibleConfigs: SerializedSyncConfigWithMapping[],
134
+ newPlan: SerializedSyncPlanV1,
135
+ reservedMappings: SingleSyncConfigBucketDefinitionMapping[]
136
+ ): SingleSyncConfigBucketDefinitionMapping {
137
+ return this.constructIncrementalMappingWithChanges(compatibleConfigs, newPlan, reservedMappings).mapping;
138
+ }
139
+
140
+ static constructIncrementalMappingWithChanges(
141
+ compatibleConfigs: SerializedSyncConfigWithMapping[],
142
+ newPlan: SerializedSyncPlanV1,
143
+ reservedMappings: SingleSyncConfigBucketDefinitionMapping[]
144
+ ): IncrementalMappingResult {
145
+ let nextBucketDefinitionId =
146
+ reservedMappings
147
+ .map((mapping) => mapping.allBucketDefinitionIds())
148
+ .flat()
149
+ .reduce((maxId, id) => Math.max(maxId, parseInt(id, 16)), 0) + 1;
150
+ function generateNewBucketDefinitionId(): BucketDefinitionId {
151
+ const id = nextBucketDefinitionId.toString(16);
152
+ nextBucketDefinitionId++;
153
+ return id;
154
+ }
155
+ let nextParameterIndexId =
156
+ reservedMappings
157
+ .map((mapping) => mapping.allParameterIndexIds())
158
+ .flat()
159
+ .reduce((maxId, id) => Math.max(maxId, parseInt(id, 16)), 0) + 1;
160
+ function generateNewParameterIndexId(): ParameterIndexId {
161
+ const id = nextParameterIndexId.toString(16);
162
+ nextParameterIndexId++;
163
+ return id;
164
+ }
165
+
166
+ const definitions: Record<string, BucketDefinitionId> = {};
167
+ const parameterLookups: Record<string, ParameterIndexId> = {};
168
+ const changes: IncrementalMappingChanges = {
169
+ reusedDefinitions: [],
170
+ addedDefinitions: []
171
+ };
172
+ const compatibleBuckets = new HashMap<SerializedBucketDataSourceWithDataSources, BucketDefinitionId>(
173
+ serializedStreamBucketDataSourceEquality
174
+ );
175
+ const compatibleParameterLookups = new HashMap<SerializedParameterIndexLookupCreator, ParameterIndexId>(
176
+ serializedStreamParameterIndexLookupCreatorEquality
177
+ );
178
+
179
+ for (const config of compatibleConfigs) {
180
+ for (const bucket of config.plan.buckets) {
181
+ compatibleBuckets.putIfAbsent({ bucket, dataSources: config.plan.dataSources }, () =>
182
+ config.mapping.bucketSourceIdByName(bucket.uniqueName)
183
+ );
184
+ }
185
+
186
+ for (const parameterLookup of config.plan.parameterIndexes) {
187
+ compatibleParameterLookups.putIfAbsent(parameterLookup, () =>
188
+ config.mapping.parameterLookupIdByKey(parameterLookupKey(parameterLookup.lookupScope))
189
+ );
190
+ }
191
+ }
192
+
193
+ for (const bucket of newPlan.buckets) {
194
+ const compatibleId = compatibleBuckets.get({ bucket, dataSources: newPlan.dataSources });
195
+ const id = compatibleId ?? generateNewBucketDefinitionId();
196
+ definitions[bucket.uniqueName] = id;
197
+ const change: IncrementalMappingDefinitionChange = {
198
+ type: 'bucket_data',
199
+ name: bucket.uniqueName,
200
+ id
201
+ };
202
+ if (compatibleId == null) {
203
+ changes.addedDefinitions.push(change);
204
+ } else {
205
+ changes.reusedDefinitions.push(change);
206
+ }
207
+ }
208
+
209
+ for (const parameterLookup of newPlan.parameterIndexes) {
210
+ const compatibleId = compatibleParameterLookups.get(parameterLookup);
211
+ const id = compatibleId ?? generateNewParameterIndexId();
212
+ const key = parameterLookupKey(parameterLookup.lookupScope);
213
+ parameterLookups[key] = id;
214
+ const change: IncrementalMappingDefinitionChange = {
215
+ type: 'parameter_lookup',
216
+ name: key,
217
+ id
218
+ };
219
+ if (compatibleId == null) {
220
+ changes.addedDefinitions.push(change);
221
+ } else {
222
+ changes.reusedDefinitions.push(change);
223
+ }
224
+ }
225
+
226
+ return {
227
+ mapping: new SingleSyncConfigBucketDefinitionMapping(definitions, parameterLookups),
228
+ changes
229
+ };
230
+ }
231
+
232
+ constructor(
233
+ private definitions: Record<string, BucketDefinitionId> = {},
234
+ private parameterLookupMapping: Record<string, ParameterIndexId> = {}
235
+ ) {}
236
+
237
+ bucketSourceId(source: BucketDataSource): BucketDefinitionId {
238
+ return this.bucketSourceIdByName(source.uniqueName);
239
+ }
240
+
241
+ bucketSourceIdByName(uniqueName: string): BucketDefinitionId {
242
+ const defId = this.definitions[uniqueName];
243
+ if (defId == null) {
244
+ throw new ServiceAssertionError(`No mapping found for bucket source ${uniqueName}`);
245
+ }
246
+ return defId;
247
+ }
248
+
249
+ allBucketDefinitionIds(): BucketDefinitionId[] {
250
+ return Object.values(this.definitions);
251
+ }
252
+
253
+ bucketDefinitionEntries(): IncrementalMappingDefinitionChange[] {
254
+ return Object.entries(this.definitions).map(([name, id]) => ({
255
+ type: 'bucket_data',
256
+ name,
257
+ id
258
+ }));
259
+ }
260
+
261
+ allParameterIndexIds(): ParameterIndexId[] {
262
+ return Object.values(this.parameterLookupMapping);
263
+ }
264
+
265
+ parameterIndexEntries(): IncrementalMappingDefinitionChange[] {
266
+ return Object.entries(this.parameterLookupMapping).map(([name, id]) => ({
267
+ type: 'parameter_lookup',
268
+ name,
269
+ id
270
+ }));
271
+ }
272
+
273
+ allDefinitionEntries(): IncrementalMappingDefinitionChange[] {
274
+ return [...this.bucketDefinitionEntries(), ...this.parameterIndexEntries()];
275
+ }
276
+
277
+ parameterLookupId(source: ParameterIndexLookupCreator): ParameterIndexId {
278
+ return this.parameterLookupIdByKey(parameterLookupKey(source.sourceId));
279
+ }
280
+
281
+ parameterLookupIdByKey(key: string): ParameterIndexId {
282
+ const defId = this.parameterLookupMapping[key];
283
+ if (defId == null) {
284
+ throw new ServiceAssertionError(`No mapping found for parameter lookup source ${key}`);
285
+ }
286
+ return defId;
287
+ }
288
+
289
+ serialize(): PersistedDefinitionMapping {
290
+ return {
291
+ definitions: { ...this.definitions },
292
+ parameter_indexes: { ...this.parameterLookupMapping }
293
+ };
294
+ }
295
+
296
+ syncConfigIdsForSourceTable(
297
+ selectedSyncConfigIds: string[],
298
+ _table: SourceTableRef,
299
+ bucketDataSourceIds: BucketDefinitionId[],
300
+ parameterLookupSourceIds: ParameterIndexId[]
301
+ ): string[] {
302
+ return bucketDataSourceIds.length > 0 || parameterLookupSourceIds.length > 0 ? selectedSyncConfigIds : [];
303
+ }
304
+
305
+ snapshotBlockingSourceTablesFilter(_syncConfigId: string): Record<string, unknown> {
306
+ const clauses: Record<string, unknown>[] = [];
307
+ const bucketDataSourceIds = this.allBucketDefinitionIds();
308
+ if (bucketDataSourceIds.length > 0) {
309
+ clauses.push({ bucket_data_source_ids: { $in: bucketDataSourceIds } });
310
+ }
311
+ const parameterLookupSourceIds = this.allParameterIndexIds();
312
+ if (parameterLookupSourceIds.length > 0) {
313
+ clauses.push({ parameter_lookup_source_ids: { $in: parameterLookupSourceIds } });
314
+ }
315
+ if (clauses.length == 0) {
316
+ return {
317
+ snapshot_done: false,
318
+ _id: { $exists: false }
319
+ };
320
+ }
321
+ return {
322
+ snapshot_done: false,
323
+ $or: clauses
324
+ };
325
+ }
326
+ }
327
+
328
+ /**
329
+ * A BucketDefinitionMapping across all SyncConfigs of one parse of a replication stream.
330
+ *
331
+ * Source lookups are strictly identity-based: a source that did not come from the parse
332
+ * this mapping was constructed with is an error. Unique names are not unique across sync
333
+ * configs in a replication stream, so there is deliberately no name-based fallback.
334
+ */
335
+ export class MultiSyncConfigBucketDefinitionMapping implements BucketDefinitionMapping {
336
+ private bucketDataSourceMappings = new WeakMap<BucketDataSource, SingleSyncConfigBucketDefinitionMapping>();
337
+ private bucketDataSourceSyncConfigIdsById = new Map<BucketDefinitionId, Set<string>>();
338
+ private parameterLookupMappings = new WeakMap<ParameterIndexLookupCreator, SingleSyncConfigBucketDefinitionMapping>();
339
+ private parameterLookupSyncConfigIdsById = new Map<ParameterIndexId, Set<string>>();
340
+ private syncConfigsById = new Map<string, SyncConfigWithRequiredMapping>();
341
+ private mappings: SingleSyncConfigBucketDefinitionMapping[];
342
+
343
+ constructor(syncConfigs: SyncConfigWithRequiredMapping[]) {
344
+ this.mappings = syncConfigs.map((config) => config.mapping);
345
+
346
+ for (const config of syncConfigs) {
347
+ this.syncConfigsById.set(config.syncConfigId, config);
348
+ for (const source of config.syncConfig.config.bucketDataSources) {
349
+ this.bucketDataSourceMappings.set(source, config.mapping);
350
+ addSetEntry(this.bucketDataSourceSyncConfigIdsById, config.mapping.bucketSourceId(source), config.syncConfigId);
351
+ }
352
+ for (const source of config.syncConfig.config.bucketParameterLookupSources) {
353
+ this.parameterLookupMappings.set(source, config.mapping);
354
+ addSetEntry(
355
+ this.parameterLookupSyncConfigIdsById,
356
+ config.mapping.parameterLookupId(source),
357
+ config.syncConfigId
358
+ );
359
+ }
360
+ }
361
+ }
362
+
363
+ bucketSourceId(source: BucketDataSource): BucketDefinitionId {
364
+ const mapping = this.bucketDataSourceMappings.get(source);
365
+ if (mapping == null) {
366
+ throw new ServiceAssertionError(
367
+ `Bucket source ${source.uniqueName} is not associated with this parse of the sync configs`
368
+ );
369
+ }
370
+ return mapping.bucketSourceId(source);
371
+ }
372
+
373
+ allBucketDefinitionIds(): BucketDefinitionId[] {
374
+ return [...new Set(this.mappings.flatMap((mapping) => mapping.allBucketDefinitionIds()))];
375
+ }
376
+
377
+ parameterLookupId(source: ParameterIndexLookupCreator): ParameterIndexId {
378
+ const mapping = this.parameterLookupMappings.get(source);
379
+ if (mapping == null) {
380
+ throw new ServiceAssertionError(
381
+ `Parameter lookup source ${source.sourceId.lookupName}#${source.sourceId.queryId} is not associated with this parse of the sync configs`
382
+ );
383
+ }
384
+ return mapping.parameterLookupId(source);
385
+ }
386
+
387
+ allParameterIndexIds(): ParameterIndexId[] {
388
+ return [...new Set(this.mappings.flatMap((mapping) => mapping.allParameterIndexIds()))];
389
+ }
390
+
391
+ syncConfigIdsForSourceTable(
392
+ _selectedSyncConfigIds: string[],
393
+ table: SourceTableRef,
394
+ bucketDataSourceIds: BucketDefinitionId[],
395
+ parameterLookupSourceIds: ParameterIndexId[]
396
+ ): string[] {
397
+ const ids = new Set<string>();
398
+ for (const sourceId of bucketDataSourceIds) {
399
+ addAll(ids, this.bucketDataSourceSyncConfigIdsById.get(sourceId));
400
+ }
401
+ for (const sourceId of parameterLookupSourceIds) {
402
+ addAll(ids, this.parameterLookupSyncConfigIdsById.get(sourceId));
403
+ }
404
+ for (const [syncConfigId, config] of this.syncConfigsById) {
405
+ if (config.syncConfig.config.tableTriggersEvent(table)) {
406
+ ids.add(syncConfigId);
407
+ }
408
+ }
409
+ return [...ids];
410
+ }
411
+
412
+ snapshotBlockingSourceTablesFilter(syncConfigId: string): Record<string, unknown> {
413
+ const config = this.syncConfigsById.get(syncConfigId);
414
+ if (config == null) {
415
+ throw new ServiceAssertionError(`No mapping found for sync config ${syncConfigId}`);
416
+ }
417
+
418
+ return config.mapping.snapshotBlockingSourceTablesFilter(syncConfigId);
419
+ }
420
+ }
421
+
422
+ export function parameterLookupKey(id: ParameterLookupDefinitionId) {
423
+ return `${id.lookupName}#${id.queryId}`;
424
+ }
425
+
426
+ function addSetEntry<K, V>(map: Map<K, Set<V>>, key: K, value: V) {
427
+ const existing = map.get(key) ?? new Set<V>();
428
+ existing.add(value);
429
+ map.set(key, existing);
430
+ }
431
+
432
+ function addAll<T>(target: Set<T>, values: Iterable<T> | undefined) {
433
+ for (const value of values ?? []) {
434
+ target.add(value);
435
+ }
436
+ }
@@ -0,0 +1,41 @@
1
+ import { CompatibilityContext } from '@powersync/service-sync-rules';
2
+ import { Logger } from 'winston';
3
+ import { SerializedSyncPlan, UpdateSyncRulesOptions } from '../BucketStorageFactory.js';
4
+
5
+ /**
6
+ * Check if a sync config update can use incremental reprocessing.
7
+ */
8
+ export function isCompatible(
9
+ existingPlans: (SerializedSyncPlan | null)[],
10
+ updateConfig: UpdateSyncRulesOptions['config'],
11
+ logger: Logger
12
+ ): boolean {
13
+ if (updateConfig.plan == null) {
14
+ // Only support sync streams with serialized plans
15
+ logger.info(`Not using current sync streams - incremental reprocessing not supported`);
16
+ return false;
17
+ }
18
+
19
+ // We don't check the storage version here - that is checked upstream.
20
+ if (existingPlans.length == 0) {
21
+ // Could technically be compatible, but there is no reason to re-use this stream.
22
+ return false;
23
+ }
24
+
25
+ if (existingPlans.some((plan) => plan == null)) {
26
+ // Only support sync streams with serialized plans
27
+ logger.info(`Existing replication stream not using current sync streams - incremental reprocessing not supported`);
28
+ return false;
29
+ }
30
+
31
+ // Technically we can compare the serialized compatibility versions? But this does not add much overhead.
32
+ const first = existingPlans[0];
33
+ const streamCompatibility = CompatibilityContext.deserialize(first!.compatibility);
34
+ if (!streamCompatibility.equals(updateConfig.parsed.config.compatibility)) {
35
+ // Compatibility options must match
36
+ logger.info(`Compatibility options changed - incremental reprocessing not supported`);
37
+ return false;
38
+ }
39
+
40
+ return true;
41
+ }
@@ -0,0 +1,109 @@
1
+ import { BucketDataSource, ParameterIndexLookupCreator, SyncConfigWithErrors } from '@powersync/service-sync-rules';
2
+ import {
3
+ IncrementalMappingChanges,
4
+ IncrementalMappingDefinitionChange,
5
+ SingleSyncConfigBucketDefinitionMapping
6
+ } from './BucketDefinitionMapping.js';
7
+
8
+ export interface IncrementalDefinitionLogEntry extends IncrementalMappingDefinitionChange {
9
+ sourceTables?: string[];
10
+ }
11
+
12
+ export interface IncrementalSyncConfigUpdateLog {
13
+ reusedDefinitions: IncrementalDefinitionLogEntry[];
14
+ addedDefinitions: IncrementalDefinitionLogEntry[];
15
+ droppedDefinitions: IncrementalDefinitionLogEntry[];
16
+ }
17
+
18
+ export function formatIncrementalSyncConfigUpdateLog(log: IncrementalSyncConfigUpdateLog) {
19
+ return [
20
+ formatDefinitionSection('Reused definitions', log.reusedDefinitions),
21
+ formatDefinitionSection('New definitions', log.addedDefinitions, { includeSnapshotTables: true }),
22
+ formatDefinitionSection('Definitions to drop after switching', log.droppedDefinitions)
23
+ ].join('\n');
24
+ }
25
+
26
+ export function describeIncrementalSyncConfigUpdate(options: {
27
+ activeMappings: SingleSyncConfigBucketDefinitionMapping[];
28
+ newMapping: SingleSyncConfigBucketDefinitionMapping;
29
+ newSyncConfig: SyncConfigWithErrors;
30
+ mappingChanges: IncrementalMappingChanges;
31
+ }): IncrementalSyncConfigUpdateLog {
32
+ const { activeMappings, newMapping, newSyncConfig, mappingChanges } = options;
33
+ const newDefinitionKeys = new Set(newMapping.allDefinitionEntries().map(definitionKey));
34
+ const activeDefinitions = uniqueDefinitions(activeMappings.flatMap((mapping) => mapping.allDefinitionEntries()));
35
+
36
+ return {
37
+ reusedDefinitions: mappingChanges.reusedDefinitions,
38
+ addedDefinitions: mappingChanges.addedDefinitions.map((definition) => {
39
+ const sourceTables = sourceTablesForDefinition(newSyncConfig, newMapping, definition);
40
+ return {
41
+ ...definition,
42
+ sourceTables
43
+ };
44
+ }),
45
+ droppedDefinitions: activeDefinitions.filter((definition) => !newDefinitionKeys.has(definitionKey(definition)))
46
+ };
47
+ }
48
+
49
+ function sourceTablesForDefinition(
50
+ syncConfig: SyncConfigWithErrors,
51
+ mapping: SingleSyncConfigBucketDefinitionMapping,
52
+ definition: IncrementalMappingDefinitionChange
53
+ ) {
54
+ if (definition.type == 'bucket_data') {
55
+ return sourceTablesForSources(
56
+ syncConfig.config.bucketDataSources.filter((source) => mapping.bucketSourceId(source) == definition.id)
57
+ );
58
+ }
59
+
60
+ return sourceTablesForSources(
61
+ syncConfig.config.bucketParameterLookupSources.filter(
62
+ (source) => mapping.parameterLookupId(source) == definition.id
63
+ )
64
+ );
65
+ }
66
+
67
+ function sourceTablesForSources(sources: Array<BucketDataSource | ParameterIndexLookupCreator>) {
68
+ return uniqueSorted(sources.flatMap((source) => [...source.getSourceTables()].map((table) => table.tablePattern)));
69
+ }
70
+
71
+ function definitionKey(definition: IncrementalMappingDefinitionChange) {
72
+ return `${definition.type}:${definition.id}`;
73
+ }
74
+
75
+ function uniqueSorted(values: string[]) {
76
+ return [...new Set(values)].sort();
77
+ }
78
+
79
+ function uniqueDefinitions(definitions: IncrementalMappingDefinitionChange[]) {
80
+ const byKey = new Map<string, IncrementalMappingDefinitionChange>();
81
+ for (const definition of definitions) {
82
+ byKey.set(definitionKey(definition), definition);
83
+ }
84
+ return [...byKey.values()];
85
+ }
86
+
87
+ function formatDefinitionSection(
88
+ title: string,
89
+ definitions: IncrementalDefinitionLogEntry[],
90
+ options: { includeSnapshotTables?: boolean } = {}
91
+ ) {
92
+ if (definitions.length == 0) {
93
+ return `${title}: none`;
94
+ }
95
+
96
+ return [`${title}:`, ...definitions.map((definition) => ` - ${formatDefinition(definition, options)}`)].join('\n');
97
+ }
98
+
99
+ function formatDefinition(definition: IncrementalDefinitionLogEntry, options: { includeSnapshotTables?: boolean }) {
100
+ const details = [`type=${definition.type}`, `id=${definition.id}`, `name=${definition.name}`];
101
+ if (definition.sourceTables != null) {
102
+ details.push(`tables=${formatList(definition.sourceTables)}`);
103
+ }
104
+ return details.join(', ');
105
+ }
106
+
107
+ function formatList(values: string[]) {
108
+ return values.length == 0 ? 'none' : values.join(', ');
109
+ }
@@ -0,0 +1,21 @@
1
+ import { BucketDefinitionId, ParameterIndexId } from '@powersync/service-sync-rules';
2
+ import { SingleSyncConfigBucketDefinitionMapping } from './BucketDefinitionMapping.js';
3
+
4
+ /**
5
+ * Persisted storage ids for a replication stream, derived from the rule_mapping documents
6
+ * of all its sync configs.
7
+ *
8
+ * This requires no parsed sync configs, and deliberately does not resolve individual
9
+ * sources - use the parsed-set-bound {@link BucketDefinitionMapping} for that.
10
+ */
11
+ export class ReplicationStreamStorageIds {
12
+ constructor(private readonly mappings: SingleSyncConfigBucketDefinitionMapping[]) {}
13
+
14
+ get bucketDefinitionIds(): BucketDefinitionId[] {
15
+ return [...new Set(this.mappings.flatMap((mapping) => mapping.allBucketDefinitionIds()))];
16
+ }
17
+
18
+ get parameterIndexIds(): ParameterIndexId[] {
19
+ return [...new Set(this.mappings.flatMap((mapping) => mapping.allParameterIndexIds()))];
20
+ }
21
+ }
@@ -3,7 +3,10 @@ export * from './BucketStorage.js';
3
3
  export * from './BucketStorageBatch.js';
4
4
  export * from './BucketStorageFactory.js';
5
5
  export * from './ChecksumCache.js';
6
- export * from './PersistedSyncRulesContent.js';
6
+ export * from './ParsedSyncConfigSet.js';
7
+ export * from './PersistedReplicationStream.js';
8
+ export * from './PersistedSyncConfigContent.js';
9
+ export * from './PersistedSyncConfigStatus.js';
7
10
  export * from './ReplicationEventPayload.js';
8
11
  export * from './ReplicationLock.js';
9
12
  export * from './ReportStorage.js';
@@ -15,3 +18,8 @@ export * from './StorageProvider.js';
15
18
  export * from './StorageVersionConfig.js';
16
19
  export * from './SyncRulesBucketStorage.js';
17
20
  export * from './WriteCheckpointAPI.js';
21
+
22
+ export * from './implementation/BucketDefinitionMapping.js';
23
+ export * from './implementation/IncrementalReprocessingCompatibility.js';
24
+ export * from './implementation/IncrementalReprocessingSyncConfigLog.js';
25
+ export * from './implementation/ReplicationStreamStorageIds.js';
package/src/sync/sync.ts CHANGED
@@ -367,6 +367,11 @@ async function* bucketDataBatch(request: BucketDataRequest): AsyncGenerator<Buck
367
367
  checkpointInvalidated = true;
368
368
  }
369
369
  if (r.data.length == 0) {
370
+ // An empty chunk is not sent to the client, but may still report progress:
371
+ // storage can emit an empty chunk for a bucket that has no operations in the
372
+ // requested range, and its position must advance so the bucket is not
373
+ // re-requested indefinitely.
374
+ checkpointLine.updateBucketPosition({ bucket: r.bucket, nextAfter: BigInt(r.next_after), hasMore: r.has_more });
370
375
  continue;
371
376
  }
372
377
  logger.debug(`Sending data for ${r.bucket}`);
@@ -11,7 +11,7 @@ export interface CreateWriteCheckpointOptions {
11
11
  export async function createWriteCheckpoint(options: CreateWriteCheckpointOptions) {
12
12
  const full_user_id = checkpointUserId(options.userId, options.clientId);
13
13
 
14
- const syncBucketStorage = await options.storage.getActiveStorage();
14
+ const syncBucketStorage = (await options.storage.getActiveSyncConfig())?.storage;
15
15
  if (!syncBucketStorage) {
16
16
  throw new ServiceError(ErrorCode.PSYNC_S2302, `Cannot create Write Checkpoint since no sync config is active.`);
17
17
  }
@@ -55,7 +55,7 @@ export type ResolvedPowerSyncConfig = {
55
55
  max_parameter_query_results: number;
56
56
  };
57
57
 
58
- /** Prefix for postgres replication slot names. May eventually be connection-specific. */
58
+ /** Prefix for postgres replication slot names, as well as replication stream names. */
59
59
  slot_name_prefix: string;
60
60
 
61
61
  healthcheck: {
package/src/util/lsn.ts CHANGED
@@ -6,3 +6,12 @@ export function maxLsn(a: string | null | undefined, b: string | null | undefine
6
6
  if (b == null) return a;
7
7
  return a > b ? a : b;
8
8
  }
9
+
10
+ /**
11
+ * Return the smaller of two LSNs, ignoring nulls.
12
+ */
13
+ export function minLsn(a: string | null | undefined, b: string | null | undefined): string | null {
14
+ if (a == null) return b ?? null;
15
+ if (b == null) return a;
16
+ return a < b ? a : b;
17
+ }