@powersync/service-core 0.0.0-dev-20260803144812 → 0.0.0-dev-20260929095716

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 (169) hide show
  1. package/CHANGELOG.md +114 -5
  2. package/dist/api/diagnostics.js +7 -2
  3. package/dist/api/diagnostics.js.map +1 -1
  4. package/dist/entry/commands/compact-action.js +29 -25
  5. package/dist/entry/commands/compact-action.js.map +1 -1
  6. package/dist/entry/commands/config-command.js +1 -1
  7. package/dist/entry/commands/config-command.js.map +1 -1
  8. package/dist/metrics/metrics-interfaces.d.ts +5 -1
  9. package/dist/metrics/metrics-interfaces.js.map +1 -1
  10. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.d.ts +36 -0
  11. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js +70 -0
  12. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js.map +1 -0
  13. package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js +6 -1
  14. package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js.map +1 -1
  15. package/dist/metrics/open-telemetry/util.js +7 -3
  16. package/dist/metrics/open-telemetry/util.js.map +1 -1
  17. package/dist/migrations/PowerSyncMigrationManager.js +2 -1
  18. package/dist/migrations/PowerSyncMigrationManager.js.map +1 -1
  19. package/dist/replication/AbstractReplicator.d.ts +5 -0
  20. package/dist/replication/AbstractReplicator.js +31 -13
  21. package/dist/replication/AbstractReplicator.js.map +1 -1
  22. package/dist/replication/ReplicationModule.d.ts +0 -7
  23. package/dist/replication/ReplicationModule.js +0 -1
  24. package/dist/replication/ReplicationModule.js.map +1 -1
  25. package/dist/routes/configure-fastify.d.ts +12 -3
  26. package/dist/routes/endpoints/admin.d.ts +24 -6
  27. package/dist/routes/endpoints/admin.js +17 -11
  28. package/dist/routes/endpoints/admin.js.map +1 -1
  29. package/dist/routes/endpoints/socket-route.js +7 -5
  30. package/dist/routes/endpoints/socket-route.js.map +1 -1
  31. package/dist/routes/endpoints/sync-rules.js +18 -10
  32. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  33. package/dist/storage/BucketStorageBatch.d.ts +2 -1
  34. package/dist/storage/BucketStorageBatch.js.map +1 -1
  35. package/dist/storage/BucketStorageFactory.d.ts +49 -6
  36. package/dist/storage/BucketStorageFactory.js +25 -8
  37. package/dist/storage/BucketStorageFactory.js.map +1 -1
  38. package/dist/storage/PersistedReplicationStream.d.ts +2 -1
  39. package/dist/storage/PersistedReplicationStream.js.map +1 -1
  40. package/dist/storage/PersistedSyncConfigContent.d.ts +6 -4
  41. package/dist/storage/PersistedSyncConfigContent.js +34 -14
  42. package/dist/storage/PersistedSyncConfigContent.js.map +1 -1
  43. package/dist/storage/ReplicationEventPayload.d.ts +6 -1
  44. package/dist/storage/SourceEntity.d.ts +7 -2
  45. package/dist/storage/SourceTable.d.ts +37 -6
  46. package/dist/storage/SourceTable.js +42 -10
  47. package/dist/storage/SourceTable.js.map +1 -1
  48. package/dist/storage/SourceTableReconciler.d.ts +83 -0
  49. package/dist/storage/SourceTableReconciler.js +95 -0
  50. package/dist/storage/SourceTableReconciler.js.map +1 -0
  51. package/dist/storage/StorageEngine.d.ts +4 -0
  52. package/dist/storage/StorageEngine.js +7 -1
  53. package/dist/storage/StorageEngine.js.map +1 -1
  54. package/dist/storage/StorageProvider.d.ts +8 -0
  55. package/dist/storage/StorageVersionConfig.d.ts +4 -0
  56. package/dist/storage/StorageVersionConfig.js +10 -1
  57. package/dist/storage/StorageVersionConfig.js.map +1 -1
  58. package/dist/storage/SyncConfigParser.d.ts +44 -0
  59. package/dist/storage/SyncConfigParser.js +70 -0
  60. package/dist/storage/SyncConfigParser.js.map +1 -0
  61. package/dist/storage/SyncRulesBucketStorage.d.ts +48 -8
  62. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  63. package/dist/storage/WriteCheckpointAPI.d.ts +25 -3
  64. package/dist/storage/WriteCheckpointAPI.js.map +1 -1
  65. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +23 -7
  66. package/dist/storage/implementation/BucketDefinitionMapping.js +88 -14
  67. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -1
  68. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +9 -5
  69. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -1
  70. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +9 -1
  71. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -1
  72. package/dist/storage/storage-index.d.ts +2 -0
  73. package/dist/storage/storage-index.js +2 -0
  74. package/dist/storage/storage-index.js.map +1 -1
  75. package/dist/storage/storage-metrics.js +120 -4
  76. package/dist/storage/storage-metrics.js.map +1 -1
  77. package/dist/sync/BucketChecksumState.d.ts +2 -2
  78. package/dist/sync/BucketChecksumState.js +5 -4
  79. package/dist/sync/BucketChecksumState.js.map +1 -1
  80. package/dist/sync/sync.js +37 -9
  81. package/dist/sync/sync.js.map +1 -1
  82. package/dist/sync/util.d.ts +1 -1
  83. package/dist/sync/util.js +13 -1
  84. package/dist/sync/util.js.map +1 -1
  85. package/dist/system/ServiceContext.d.ts +20 -0
  86. package/dist/system/ServiceContext.js +29 -1
  87. package/dist/system/ServiceContext.js.map +1 -1
  88. package/dist/util/config/compound-config-collector.js +5 -0
  89. package/dist/util/config/compound-config-collector.js.map +1 -1
  90. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
  91. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
  92. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
  93. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
  94. package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
  95. package/dist/util/config/sync-rules/sync-rules-provider.js +3 -0
  96. package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
  97. package/dist/util/config/types.d.ts +1 -0
  98. package/dist/util/param-logging.d.ts +5 -2
  99. package/dist/util/param-logging.js +17 -9
  100. package/dist/util/param-logging.js.map +1 -1
  101. package/dist/util/protocol-types.d.ts +11 -11
  102. package/dist/util/protocol-types.js +6 -5
  103. package/dist/util/protocol-types.js.map +1 -1
  104. package/dist/util/utils.d.ts +2 -1
  105. package/dist/util/utils.js +16 -1
  106. package/dist/util/utils.js.map +1 -1
  107. package/package.json +6 -5
  108. package/src/api/diagnostics.ts +8 -2
  109. package/src/entry/commands/compact-action.ts +33 -25
  110. package/src/entry/commands/config-command.ts +1 -1
  111. package/src/metrics/metrics-interfaces.ts +6 -1
  112. package/src/metrics/open-telemetry/MetricAttributeFilteringExporter.ts +85 -0
  113. package/src/metrics/open-telemetry/OpenTelemetryMetricsFactory.ts +7 -2
  114. package/src/metrics/open-telemetry/util.ts +7 -3
  115. package/src/migrations/PowerSyncMigrationManager.ts +2 -1
  116. package/src/replication/AbstractReplicator.ts +42 -13
  117. package/src/replication/ReplicationModule.ts +0 -10
  118. package/src/routes/endpoints/admin.ts +17 -17
  119. package/src/routes/endpoints/socket-route.ts +9 -6
  120. package/src/routes/endpoints/sync-rules.ts +21 -12
  121. package/src/storage/BucketStorageBatch.ts +2 -1
  122. package/src/storage/BucketStorageFactory.ts +77 -14
  123. package/src/storage/PersistedReplicationStream.ts +2 -1
  124. package/src/storage/PersistedSyncConfigContent.ts +42 -19
  125. package/src/storage/ReplicationEventPayload.ts +6 -1
  126. package/src/storage/SourceEntity.ts +6 -2
  127. package/src/storage/SourceTable.ts +68 -11
  128. package/src/storage/SourceTableReconciler.ts +188 -0
  129. package/src/storage/StorageEngine.ts +10 -1
  130. package/src/storage/StorageProvider.ts +8 -0
  131. package/src/storage/StorageVersionConfig.ts +11 -1
  132. package/src/storage/SyncConfigParser.ts +121 -0
  133. package/src/storage/SyncRulesBucketStorage.ts +56 -8
  134. package/src/storage/WriteCheckpointAPI.ts +32 -3
  135. package/src/storage/implementation/BucketDefinitionMapping.ts +120 -17
  136. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +14 -5
  137. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +22 -5
  138. package/src/storage/storage-index.ts +2 -0
  139. package/src/storage/storage-metrics.ts +154 -8
  140. package/src/sync/BucketChecksumState.ts +8 -5
  141. package/src/sync/sync.ts +40 -11
  142. package/src/sync/util.ts +25 -9
  143. package/src/system/ServiceContext.ts +47 -1
  144. package/src/util/config/compound-config-collector.ts +6 -0
  145. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
  146. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
  147. package/src/util/config/sync-rules/sync-rules-provider.ts +5 -0
  148. package/src/util/config/types.ts +1 -0
  149. package/src/util/param-logging.ts +21 -14
  150. package/src/util/protocol-types.ts +8 -7
  151. package/src/util/utils.ts +15 -1
  152. package/test/src/AbstractReplicator.test.ts +62 -0
  153. package/test/src/MetricAttributeFilteringExporter.test.ts +96 -0
  154. package/test/src/PersistedSyncConfigContent.test.ts +154 -0
  155. package/test/src/SyncConfigParser.test.ts +330 -0
  156. package/test/src/broadcast_iterable.test.ts +26 -8
  157. package/test/src/config.test.ts +40 -0
  158. package/test/src/diagnostics.test.ts +48 -0
  159. package/test/src/routes/admin.test.ts +30 -2
  160. package/test/src/routes/mocks.ts +2 -0
  161. package/test/src/routes/stream.test.ts +123 -2
  162. package/test/src/source-table-reconciler.test.ts +244 -0
  163. package/test/src/storage/SourceTable.test.ts +4 -1
  164. package/test/src/storage-metrics.test.ts +148 -0
  165. package/test/src/sync/BucketChecksumState.test.ts +195 -6
  166. package/test/src/sync/util.test.ts +34 -0
  167. package/test/src/util/param-logging.test.ts +59 -0
  168. package/test/src/util/utils.test.ts +23 -0
  169. package/tsconfig.tsbuildinfo +1 -1
@@ -4,7 +4,6 @@ import {
4
4
  SerializedSyncPlan as RawSerializedSyncPlan,
5
5
  SerializedCompatibilityContext,
6
6
  serializeSyncPlan,
7
- SqlSyncRules,
8
7
  SyncConfigWithErrors
9
8
  } from '@powersync/service-sync-rules';
10
9
  import { ReplicationError } from '@powersync/service-types';
@@ -14,8 +13,16 @@ import { PersistedSyncConfigContent } from './PersistedSyncConfigContent.js';
14
13
  import { ReplicationEventPayload } from './ReplicationEventPayload.js';
15
14
  import { ReplicationLock } from './ReplicationLock.js';
16
15
  import { ReportStorage } from './ReportStorage.js';
16
+ import { SqlSyncConfigParser, SyncConfigParser } from './SyncConfigParser.js';
17
17
  import { SyncRulesBucketStorage } from './SyncRulesBucketStorage.js';
18
18
 
19
+ export interface BucketStorageFactoryOptions {
20
+ /**
21
+ * Service-wide parser assembled before storage startup.
22
+ */
23
+ syncConfigParser: SyncConfigParser;
24
+ }
25
+
19
26
  /**
20
27
  * Represents a configured storage provider.
21
28
  *
@@ -28,6 +35,16 @@ export abstract class BucketStorageFactory
28
35
  extends BaseObserver<BucketStorageFactoryListener>
29
36
  implements AsyncDisposable
30
37
  {
38
+ readonly syncConfigParser: SyncConfigParser;
39
+
40
+ /**
41
+ * Creates a storage factory using the service-wide parser assembled before storage startup.
42
+ */
43
+ constructor(options: BucketStorageFactoryOptions) {
44
+ super();
45
+ this.syncConfigParser = options.syncConfigParser;
46
+ }
47
+
31
48
  /**
32
49
  * Update sync config from configuration, if changed.
33
50
  */
@@ -37,10 +54,17 @@ export abstract class BucketStorageFactory
37
54
  const deploying = await this.getDeployingSyncConfig();
38
55
  const active = await this.getActiveSyncConfig();
39
56
 
40
- if (deploying?.content.sync_rules_content == options.config.yaml) {
57
+ if (
58
+ deploying?.content.sync_rules_content == options.config.yaml &&
59
+ deploying.content.version_label == options.version_label
60
+ ) {
41
61
  logger.info('Sync config unchanged');
42
62
  return { updated: false };
43
- } else if (deploying == null && active?.content.sync_rules_content == options.config.yaml) {
63
+ } else if (
64
+ deploying == null &&
65
+ active?.content.sync_rules_content == options.config.yaml &&
66
+ active.content.version_label == options.version_label
67
+ ) {
44
68
  logger.info('Sync config unchanged');
45
69
  return { updated: false };
46
70
  } else {
@@ -110,10 +134,14 @@ export abstract class BucketStorageFactory
110
134
  */
111
135
  abstract getSystemIdentifier(): Promise<BucketStorageSystemIdentifier>;
112
136
 
113
- abstract [Symbol.asyncDispose](): PromiseLike<void>;
137
+ async [Symbol.asyncDispose](): Promise<void> {
138
+ await this.iterateAsyncListeners(async (listener) => listener.beforeDispose?.());
139
+ }
114
140
  }
115
141
 
116
142
  export interface BucketStorageFactoryListener {
143
+ /** Release owned resources before the factory closes its database connections. */
144
+ beforeDispose: () => Promise<void>;
117
145
  syncStorageCreated: (storage: SyncRulesBucketStorage) => void;
118
146
  replicationEvent: (event: ReplicationEventPayload) => void;
119
147
  }
@@ -141,13 +169,36 @@ export interface StorageMetrics {
141
169
  * Size of current_data.
142
170
  */
143
171
  replication_size_bytes: number;
172
+
173
+ /**
174
+ * Size of active object-storage references, such as S3 bucket-data objects.
175
+ */
176
+ object_storage_size_bytes?: number;
177
+
178
+ /**
179
+ * Per-sync-config storage sizes, when the storage backend can provide them.
180
+ */
181
+ sync_config_metrics?: StorageSyncConfigMetrics[];
182
+ }
183
+
184
+ export interface StorageSyncConfigMetrics {
185
+ sync_config_id: string;
186
+ sync_config_state: string;
187
+ /** Optional operator-supplied label identifying this sync config version. */
188
+ version_label?: string;
189
+ attributed_bucket_data_bytes: number;
190
+ attributed_parameter_indexes_bytes: number;
191
+ attributed_source_records_bytes: number;
192
+ attributed_object_storage_bytes: number;
144
193
  }
145
194
 
146
195
  export interface UpdateSyncRulesOptions {
196
+ /** Optional operator-supplied label identifying this deployed sync config version. */
197
+ version_label?: string;
147
198
  config: {
148
199
  yaml: string;
149
200
  /**
150
- * The serialized sync plan for the sync configuration, or `null` for configurations not using the sync stream
201
+ * The serialized sync plan for the sync configuration, or `null` for configurations not using the Sync Streams
151
202
  * compiler.
152
203
  */
153
204
  plan: SerializedSyncPlan | null;
@@ -161,6 +212,12 @@ export interface UpdateSyncRulesOptions {
161
212
  lock?: boolean;
162
213
  storageVersion?: number;
163
214
 
215
+ /**
216
+ * Start a replacement replication stream instead of incrementally reprocessing a
217
+ * compatible active stream. Used when the current stream needs a full reprocess.
218
+ */
219
+ forceNewReplicationStream?: boolean;
220
+
164
221
  /**
165
222
  * Only relevant if the result is used. This does not affect the persisted config.
166
223
  */
@@ -174,11 +231,10 @@ export interface SerializedSyncPlan {
174
231
  plan: RawSerializedSyncPlan;
175
232
  compatibility: SerializedCompatibilityContext;
176
233
  /**
177
- * Event descriptors are not currently represented in the sync plan because they don't use the sync streams compiler
178
- * yet.
234
+ * Raw event SQL persisted as a compatibility mirror for compiled {@link plan} events.
179
235
  *
180
- * We might revisit that in the future, but for now we store SQL text of their definitions here to be able to restore
181
- * them.
236
+ * Compiled events are an additive plan field. Older services ignore that field and restore these descriptors through
237
+ * the legacy evaluator. Keep dual-writing this field until a future plan version explicitly removes that support.
182
238
  */
183
239
  eventDescriptors: Record<string, string[]>;
184
240
  errors?: ReplicationError[];
@@ -188,14 +244,15 @@ export function updateSyncRulesFromYaml(
188
244
  content: string,
189
245
  options?: Omit<UpdateSyncRulesOptions, 'config'> & { validate?: boolean }
190
246
  ): UpdateSyncRulesOptions {
191
- const config = SqlSyncRules.fromYaml(content, {
247
+ const { validate, ...updateOptions } = options ?? {};
248
+ const config = new SqlSyncConfigParser().parseContent(content, {
192
249
  // No schema-based validation at this point
193
250
  schema: undefined,
194
251
  defaultSchema: options?.defaultSchema ?? 'not_applicable', // Not needed for validation
195
- throwOnError: options?.validate ?? false
252
+ throwOnError: validate ?? false
196
253
  });
197
254
 
198
- return updateSyncRulesFromConfig(config, options);
255
+ return updateSyncRulesFromConfig(config, updateOptions);
199
256
  }
200
257
 
201
258
  export function updateSyncRulesFromConfig(
@@ -206,13 +263,14 @@ export function updateSyncRulesFromConfig(
206
263
  const { config, errors } = parsed;
207
264
  if (config instanceof PrecompiledSyncConfig) {
208
265
  const eventDescriptors: Record<string, string[]> = {};
209
- for (const event of config.eventDescriptors) {
210
- eventDescriptors[event.name] = event.sourceQueries.map((q) => q.sql);
266
+ for (const event of config.plan.events) {
267
+ eventDescriptors[event.name] = event.sourceQueries.map((query) => query.sql);
211
268
  }
212
269
 
213
270
  plan = {
214
271
  compatibility: config.compatibility.serialize(),
215
272
  plan: serializeSyncPlan(config.plan),
273
+ // Dual-write raw SQL so older services can ignore additive compiled plan events without losing event behavior.
216
274
  eventDescriptors,
217
275
  errors: errors.map((e) => syncConfigYamlErrorToReplicationError(e))
218
276
  };
@@ -222,6 +280,11 @@ export function updateSyncRulesFromConfig(
222
280
  }
223
281
 
224
282
  export interface GetIntanceOptions {
283
+ /**
284
+ * The job lease, including a lease acquired during initial configuration.
285
+ * Required for writing; optional for reading.
286
+ */
287
+ replicationLock?: ReplicationLock;
225
288
  /**
226
289
  * Set to true to skip trigger any events for creating the instance.
227
290
  *
@@ -2,9 +2,10 @@ import { logger as defaultLogger, ErrorCode, ServiceError } from '@powersync/lib
2
2
  import { Logger } from 'winston';
3
3
  import { SyncRuleState } from './BucketStorage.js';
4
4
  import type { ParsedSyncConfigSet } from './ParsedSyncConfigSet.js';
5
- import type { ParseSyncConfigOptions, PersistedSyncConfigContent } from './PersistedSyncConfigContent.js';
5
+ import type { PersistedSyncConfigContent } from './PersistedSyncConfigContent.js';
6
6
  import { ReplicationLock } from './ReplicationLock.js';
7
7
  import { STORAGE_VERSION_CONFIG, StorageVersionConfig } from './StorageVersionConfig.js';
8
+ import type { ParseSyncConfigOptions } from './SyncConfigParser.js';
8
9
 
9
10
  export abstract class PersistedReplicationStream implements PersistedReplicationStreamData {
10
11
  readonly replicationStreamId: number;
@@ -2,6 +2,7 @@ import { logger as defaultLogger, ErrorCode, ServiceError } from '@powersync/lib
2
2
  import {
3
3
  CompatibilityContext,
4
4
  CompatibilityOption,
5
+ compileEventDefinitions,
5
6
  DEFAULT_HYDRATION_STATE,
6
7
  deserializeSyncPlan,
7
8
  ErrorLocation,
@@ -9,8 +10,6 @@ import {
9
10
  HydrationState,
10
11
  nodeSqlite,
11
12
  PrecompiledSyncConfig,
12
- SqlEventDescriptor,
13
- SqlSyncRules,
14
13
  SyncConfigWithErrors,
15
14
  versionedHydrationState,
16
15
  YamlError
@@ -22,35 +21,48 @@ import { SerializedSyncPlan, UpdateSyncRulesOptions } from './BucketStorageFacto
22
21
  import { ParsedSyncConfigSet } from './ParsedSyncConfigSet.js';
23
22
  import { PersistedSyncConfigStatus } from './PersistedSyncConfigStatus.js';
24
23
  import { STORAGE_VERSION_CONFIG, StorageVersionConfig } from './StorageVersionConfig.js';
24
+ import { ParseSyncConfigOptions, SyncConfigParser } from './SyncConfigParser.js';
25
25
 
26
26
  export interface ParsePersistedSyncConfigContentOptions {
27
27
  content: string;
28
28
  compiledPlan: SerializedSyncPlan | null;
29
29
  storageVersion: number;
30
30
  parseOptions: ParseSyncConfigOptions;
31
+ syncConfigParser: SyncConfigParser;
31
32
  }
32
33
 
33
34
  export function parsePersistedSyncConfigContent(options: ParsePersistedSyncConfigContentOptions): SyncConfigWithErrors {
34
- const { content, compiledPlan, storageVersion, parseOptions } = options;
35
+ const { content, compiledPlan, storageVersion, parseOptions, syncConfigParser } = options;
35
36
 
36
37
  if (compiledPlan == null) {
37
38
  // Fallback: Only parse from YAML if no compiled plan is available.
38
- return SqlSyncRules.fromYaml(content, parseOptions);
39
+ return syncConfigParser.parseContent(content, parseOptions);
39
40
  }
40
41
 
41
42
  const plan = deserializeSyncPlan(compiledPlan.plan);
42
43
  const compatibility = CompatibilityContext.deserialize(compiledPlan.compatibility);
43
- const eventDefinitions: SqlEventDescriptor[] = [];
44
- for (const [name, queries] of Object.entries(compiledPlan.eventDescriptors)) {
45
- const descriptor = new SqlEventDescriptor(name, compatibility);
46
- for (const query of queries) {
47
- descriptor.addSourceQuery(query, parseOptions);
44
+ const errors: YamlError[] = [];
45
+ // Compiled events are additive to plan versions 1 and 2. New readers prefer them when present; when an older plan
46
+ // does not contain them, normalize the dual-written raw SQL at this loading boundary. This keeps legacy event
47
+ // evaluators out of PrecompiledSyncConfig while older binaries can continue reading the same persisted config.
48
+ if (compiledPlan.plan.events == null) {
49
+ const normalized = compileEventDefinitions(compiledPlan.eventDescriptors, {
50
+ ...parseOptions,
51
+ // The legacy evaluator ignored event payload filters. Preserve that behavior for plans deployed before compiled
52
+ // events existed; a redeploy compiles and validates those filters before the replacement config is activated.
53
+ compileEventPayloadFilters: false
54
+ });
55
+ const fatalErrors = normalized.errors.filter((error) => error.type == 'fatal');
56
+ if (fatalErrors.length != 0) {
57
+ throw new Error(
58
+ `Failed to compile persisted replication events: ${fatalErrors.map((error) => error.message).join(', ')}`
59
+ );
48
60
  }
49
-
50
- eventDefinitions.push(descriptor);
61
+ plan.events = normalized.events;
62
+ errors.push(...normalized.errors.map((error) => new YamlError(error)));
51
63
  }
52
64
 
53
- const precompiled = new PrecompiledSyncConfig(plan, compatibility, eventDefinitions, {
65
+ const precompiled = new PrecompiledSyncConfig(plan, compatibility, {
54
66
  defaultSchema: parseOptions.defaultSchema,
55
67
  sourceText: content
56
68
  });
@@ -58,8 +70,13 @@ export function parsePersistedSyncConfigContent(options: ParsePersistedSyncConfi
58
70
  // Note: If the original content did not define a storage version, this will still set the storage version.
59
71
  // This means asUpdateOptions will not change the storage version, even if the default changes.
60
72
  precompiled.storageVersion = storageVersion;
73
+ errors.push(
74
+ ...syncConfigParser.validatePersisted({
75
+ config: precompiled,
76
+ context: { defaultSchema: parseOptions.defaultSchema }
77
+ })
78
+ );
61
79
 
62
- const errors: YamlError[] = [];
63
80
  if (compiledPlan.errors) {
64
81
  for (const error of compiledPlan.errors) {
65
82
  const location: ErrorLocation | undefined = error.location && {
@@ -93,8 +110,12 @@ export abstract class PersistedSyncConfigContent implements PersistedSyncConfigC
93
110
  readonly logger: Logger;
94
111
  readonly syncConfigId: PersistedSyncConfigId | null;
95
112
  readonly syncConfigState: SyncRuleState;
113
+ readonly version_label: string | undefined;
96
114
 
97
- constructor(data: PersistedSyncConfigContentData) {
115
+ constructor(
116
+ data: PersistedSyncConfigContentData,
117
+ private readonly syncConfigParser: SyncConfigParser
118
+ ) {
98
119
  this.replicationStreamId = data.replicationStreamId;
99
120
  this.sync_rules_content = data.sync_rules_content;
100
121
  this.compiled_plan = data.compiled_plan;
@@ -102,7 +123,9 @@ export abstract class PersistedSyncConfigContent implements PersistedSyncConfigC
102
123
  this.storageVersion = data.storageVersion;
103
124
  this.syncConfigId = data.syncConfigId ?? null;
104
125
  this.syncConfigState = data.syncConfigState;
105
- this.logger = defaultLogger.child({ prefix: `[${this.replicationStreamName}] ` });
126
+ this.version_label = data.version_label;
127
+ const versionPrefix = this.version_label == null ? '' : `[${this.version_label}]`;
128
+ this.logger = defaultLogger.child({ prefix: `[${this.replicationStreamName}]${versionPrefix} ` });
106
129
  }
107
130
 
108
131
  /**
@@ -131,7 +154,8 @@ export abstract class PersistedSyncConfigContent implements PersistedSyncConfigC
131
154
  content: this.sync_rules_content,
132
155
  compiledPlan: this.compiled_plan,
133
156
  storageVersion: this.storageVersion,
134
- parseOptions: options
157
+ parseOptions: options,
158
+ syncConfigParser: this.syncConfigParser
135
159
  });
136
160
  }
137
161
 
@@ -167,6 +191,7 @@ export abstract class PersistedSyncConfigContent implements PersistedSyncConfigC
167
191
  const parsed = this.parseSingleConfig({ defaultSchema: 'not_applicable' });
168
192
  return {
169
193
  config: { yaml: this.sync_rules_content, plan: this.compiled_plan, parsed },
194
+ version_label: this.version_label,
170
195
  ...options
171
196
  };
172
197
  }
@@ -185,8 +210,6 @@ export interface PersistedSyncConfigContentData {
185
210
 
186
211
  readonly syncConfigId?: PersistedSyncConfigId | null;
187
212
  readonly syncConfigState: SyncRuleState;
213
+ readonly version_label?: string;
188
214
  }
189
215
  export type PersistedSyncConfigId = string;
190
- export interface ParseSyncConfigOptions {
191
- defaultSchema: string;
192
- }
@@ -11,6 +11,11 @@ export type EventData = {
11
11
  export type ReplicationEventPayload = {
12
12
  batch: BucketStorageBatch;
13
13
  data: EventData;
14
- event: sync_rules.SqlEventDescriptor;
14
+ event: sync_rules.HydratedEventDescriptor;
15
+ /**
16
+ * Storage-assigned id for this event definition. Present when storage uses persisted event mappings, allowing event
17
+ * handlers to route custom checkpoints without deriving an id from compiled event content.
18
+ */
19
+ event_id?: sync_rules.EventDefinitionId;
15
20
  table: SourceTable;
16
21
  };
@@ -1,5 +1,11 @@
1
1
  import { SourceTableRef } from '@powersync/service-sync-rules';
2
2
 
3
+ /**
4
+ * Source-specific JSON metadata. Storage does not interpret it. Source-table APIs use null to
5
+ * represent the absence of metadata.
6
+ */
7
+ export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
8
+
3
9
  export interface ColumnDescriptor {
4
10
  name: string;
5
11
  /**
@@ -19,8 +25,6 @@ export interface SourceEntityDescriptor extends SourceTableRef {
19
25
  * If specified, this is specifically used to detect renames.
20
26
  */
21
27
  objectId: number | string | undefined;
22
- schema: string;
23
- name: string;
24
28
  /**
25
29
  * The columns that are used to uniquely identify a record in the source entity.
26
30
  */
@@ -2,19 +2,30 @@ import {
2
2
  BucketDataSource,
3
3
  BucketDefinitionId,
4
4
  DEFAULT_TAG,
5
+ EventDefinitionId,
5
6
  ParameterIndexId,
6
7
  ParameterIndexLookupCreator,
7
8
  SourceTableRef
8
9
  } from '@powersync/service-sync-rules';
9
10
  import { bson } from '../index.js';
10
11
  import * as util from '../util/util-index.js';
11
- import { ColumnDescriptor } from './SourceEntity.js';
12
+ import { ColumnDescriptor, JsonValue } from './SourceEntity.js';
12
13
 
13
14
  /**
14
15
  * Format of the id depends on the bucket storage module. It should be consistent within the module.
15
16
  */
16
17
  export type SourceTableId = string | bson.ObjectId;
17
18
 
19
+ /**
20
+ * Compare source-table ids without coercing between storage-specific types.
21
+ */
22
+ export function sourceTableIdEquals(left: SourceTableId, right: SourceTableId): boolean {
23
+ if (typeof left === 'string' || typeof right === 'string') {
24
+ return typeof left === 'string' && typeof right === 'string' && left === right;
25
+ }
26
+ return left.equals(right);
27
+ }
28
+
18
29
  export interface SourceTableOptions {
19
30
  id: SourceTableId;
20
31
  ref: SourceTableRef;
@@ -25,6 +36,17 @@ export interface SourceTableOptions {
25
36
  parameterLookupSources: ParameterIndexLookupCreator[];
26
37
  bucketDataSourceIds?: Set<BucketDefinitionId>;
27
38
  parameterLookupSourceIds?: Set<ParameterIndexId>;
39
+ /**
40
+ * Compiled event definitions assigned to this persisted source-table record.
41
+ *
42
+ * Undefined is the legacy/non-incremental representation where event selection is
43
+ * based on the table ref. V3 incremental storage always supplies this set.
44
+ */
45
+ eventDefinitionIds?: Set<EventDefinitionId>;
46
+ /**
47
+ * Source-specific metadata. Null when no metadata has been recorded.
48
+ */
49
+ sourceMetadata?: JsonValue;
28
50
  }
29
51
 
30
52
  export interface TableSnapshotStatus {
@@ -61,11 +83,11 @@ export class SourceTable {
61
83
  public syncParameters = true;
62
84
 
63
85
  /**
64
- * True if this table should fire events for row changes.
86
+ * True if this table should evaluate event definitions for row changes.
65
87
  *
66
- * This value is resolved externally, and cached here. When multiple SourceTables exist
67
- * for the same SourceTableRef (v3 storage), resolveTables designates exactly one of them
68
- * as the event carrier, so that a row change saved once per table fires each event once.
88
+ * This value is resolved externally, and cached here. V3 storage assigns disjoint
89
+ * event-definition ids to SourceTables for the same physical table. Multiple records
90
+ * may evaluate different events, but each event id is evaluated through at most one record.
69
91
  *
70
92
  * Defaults to true for tests.
71
93
  */
@@ -136,6 +158,14 @@ export class SourceTable {
136
158
  return this.options.parameterLookupSourceIds;
137
159
  }
138
160
 
161
+ get eventDefinitionIds() {
162
+ return this.options.eventDefinitionIds;
163
+ }
164
+
165
+ get sourceMetadata() {
166
+ return this.options.sourceMetadata ?? null;
167
+ }
168
+
139
169
  /**
140
170
  * Sanitized name of the entity in the format of "{schema}.{entity name}".
141
171
  * Suitable for safe use in Postgres queries.
@@ -152,23 +182,42 @@ export class SourceTable {
152
182
  * In-memory clone of the table status.
153
183
  */
154
184
  clone() {
185
+ return this.copyWithSourceMetadata(this.sourceMetadata);
186
+ }
187
+
188
+ /**
189
+ * Copy this table with different source metadata, preserving its resolved state.
190
+ */
191
+ withSourceMetadata(sourceMetadata: JsonValue) {
192
+ return this.copyWithSourceMetadata(sourceMetadata);
193
+ }
194
+
195
+ private copyWithSourceMetadata(sourceMetadata: JsonValue) {
155
196
  const copy = new SourceTable({
156
197
  id: this.id,
157
- ref: this.options.ref,
198
+ ref: { ...this.options.ref },
158
199
  objectId: this.objectId,
159
- replicaIdColumns: this.replicaIdColumns,
200
+ replicaIdColumns: this.replicaIdColumns.map((column) => ({ ...column })),
160
201
  snapshotComplete: this.snapshotComplete,
161
- bucketDataSources: this.bucketDataSources,
162
- parameterLookupSources: this.parameterLookupSources,
202
+ bucketDataSources: [...this.bucketDataSources],
203
+ parameterLookupSources: [...this.parameterLookupSources],
163
204
  bucketDataSourceIds: this.bucketDataSourceIds == null ? undefined : new Set(this.bucketDataSourceIds),
164
205
  parameterLookupSourceIds:
165
- this.parameterLookupSourceIds == null ? undefined : new Set(this.parameterLookupSourceIds)
206
+ this.parameterLookupSourceIds == null ? undefined : new Set(this.parameterLookupSourceIds),
207
+ eventDefinitionIds: this.eventDefinitionIds == null ? undefined : new Set(this.eventDefinitionIds),
208
+ sourceMetadata: structuredClone(sourceMetadata)
166
209
  });
167
210
  copy.syncData = this.syncData;
168
211
  copy.syncParameters = this.syncParameters;
169
212
  copy.syncEvent = this.syncEvent;
170
213
  copy.storeCurrentData = this.storeCurrentData;
171
- copy.snapshotStatus = this.snapshotStatus;
214
+ copy.snapshotStatus =
215
+ this.snapshotStatus == null
216
+ ? undefined
217
+ : {
218
+ ...this.snapshotStatus,
219
+ lastKey: this.snapshotStatus.lastKey?.slice() ?? null
220
+ };
172
221
  return copy;
173
222
  }
174
223
 
@@ -183,3 +232,11 @@ export class SourceTable {
183
232
  }
184
233
  }
185
234
  }
235
+
236
+ /**
237
+ * A cloned SourceTable exposed to reconciliation with public fields typed as read-only.
238
+ * `options` is omitted so callers cannot mutate the underlying option bag without an explicit cast.
239
+ */
240
+ export type SourceTableCandidate = Omit<Readonly<SourceTable>, 'options' | 'withSourceMetadata'> & {
241
+ withSourceMetadata(sourceMetadata: JsonValue): SourceTableCandidate;
242
+ };