@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
@@ -28,7 +28,11 @@ export function registerCompactAction(program: Command) {
28
28
  .command(COMMAND_NAME)
29
29
  .option(`-b, --buckets [buckets]`, 'Full bucket names, comma-separated (e.g., "global[],mybucket[\\"user1\\"]")')
30
30
  .option('-p, --parameter-indexes', 'Compacting parameter indexes. Defaults to set unless --buckets is provided.')
31
- .option('--no-parameter-indexes', 'Disabling compacting parameter indexes.');
31
+ .option('--no-parameter-indexes', 'Disabling compacting parameter indexes.')
32
+ .option(
33
+ '--incremental-only',
34
+ '[EXPERIMENTAL] Perform incremental compacting only. Parameter compaction runs on supported storage versions.'
35
+ );
32
36
 
33
37
  wrapConfigCommand(compactCommand);
34
38
 
@@ -42,14 +46,15 @@ export function registerCompactAction(program: Command) {
42
46
  if (invalid.length > 0) {
43
47
  logger.error(
44
48
  `Invalid bucket names: ${invalid.join(', ')}. ` +
45
- `Pass full bucket names (e.g., "global[]"), not bucket definition names (e.g., "global").`
49
+ `Pass full bucket names (e.g., "global[]"), not bucket definition or Sync Stream names (e.g., "global").`
46
50
  );
47
51
  process.exit(1);
48
52
  }
49
53
  }
50
54
 
51
- let compactParameters: boolean | null = options.parameterIndexes;
55
+ const incremental: boolean = options.incrementalOnly ?? false;
52
56
 
57
+ let compactParameters: boolean | null = options.parameterIndexes;
53
58
  if (buckets == null) {
54
59
  logger.info('Compacting storage for all buckets...');
55
60
  } else if (buckets.length == 0) {
@@ -87,29 +92,32 @@ export function registerCompactAction(program: Command) {
87
92
  Date.now() - config.api_parameters.checkpoint_request_retention_minutes * MINUTE_MS
88
93
  );
89
94
 
90
- const active = (await bucketStorage.getActiveSyncConfig())?.storage;
91
- if (active == null) {
92
- logger.info('No active instance to compact');
93
- return;
94
- }
95
- if (buckets != null) {
96
- logger.info('Performing compaction...');
97
- await active.compact({
98
- memoryLimitMB: COMPACT_MEMORY_LIMIT_MB,
99
- compactBuckets: buckets,
100
- compactParameterData: compactParameters ?? false,
101
- deleteCheckpointRequestsBefore,
102
- signal: abortController.signal
103
- });
104
- } else {
105
- await active.compact({
106
- memoryLimitMB: COMPACT_MEMORY_LIMIT_MB,
107
- compactParameterData: compactParameters ?? true,
108
- deleteCheckpointRequestsBefore,
109
- signal: abortController.signal
110
- });
95
+ const streams = await bucketStorage.getReplicatingReplicationStreams();
96
+ for (let stream of streams) {
97
+ const storage = bucketStorage.getInstance(stream);
98
+ const compactParameterData =
99
+ (compactParameters ?? buckets == null) && (!incremental || storage.supportsIncrementalParameterCompaction());
100
+ logger.info(`[${stream.replicationStreamName}] Performing compaction...`);
101
+ if (buckets != null) {
102
+ await storage.compact({
103
+ memoryLimitMB: COMPACT_MEMORY_LIMIT_MB,
104
+ compactBuckets: buckets,
105
+ compactParameterData,
106
+ incrementalOnly: incremental,
107
+ deleteCheckpointRequestsBefore,
108
+ signal: abortController.signal
109
+ });
110
+ } else {
111
+ await storage.compact({
112
+ memoryLimitMB: COMPACT_MEMORY_LIMIT_MB,
113
+ compactParameterData,
114
+ incrementalOnly: incremental,
115
+ deleteCheckpointRequestsBefore,
116
+ signal: abortController.signal
117
+ });
118
+ }
119
+ logger.info(`[${stream.replicationStreamName}] Successfully compacted storage.`);
111
120
  }
112
- logger.info('Successfully compacted storage.');
113
121
  } catch (e) {
114
122
  logger.error(`Failed to compact:`, e);
115
123
  // Indirectly triggers lifeCycleEngine.stop
@@ -19,7 +19,7 @@ export function wrapConfigCommand(command: Command) {
19
19
  )
20
20
  .option(
21
21
  `-sync64, --sync-base64 [base64]`,
22
- 'Base64 encoded YAML Sync Config. Defaults to process.env.POWERSYNC_SYNC_CONFIG_B64 or process.env.POWERSYNC_SYNC_RULES_B64 for backwards compatility.',
22
+ 'Base64 encoded YAML Sync Config. Defaults to process.env.POWERSYNC_SYNC_CONFIG_B64 or process.env.POWERSYNC_SYNC_RULES_B64 for backwards compatibility.',
23
23
  util.env.POWERSYNC_SYNC_CONFIG_B64 || util.env.POWERSYNC_SYNC_RULES_B64
24
24
  );
25
25
  }
@@ -19,7 +19,12 @@ export interface ObservableGauge {
19
19
  * Set a value provider that provides the value for the gauge at the time of observation.
20
20
  * @param valueProvider
21
21
  */
22
- setValueProvider(valueProvider: () => Promise<number | undefined>): void;
22
+ setValueProvider(valueProvider: () => Promise<number | ObservableGaugeObservation[] | undefined>): void;
23
+ }
24
+
25
+ export interface ObservableGaugeObservation {
26
+ value: number;
27
+ attributes?: Record<string, string>;
23
28
  }
24
29
 
25
30
  export enum Precision {
@@ -0,0 +1,85 @@
1
+ import { Attributes } from '@opentelemetry/api';
2
+ import { ExportResult } from '@opentelemetry/core';
3
+ import {
4
+ AggregationSelector,
5
+ AggregationTemporalitySelector,
6
+ DataPoint,
7
+ DataPointType,
8
+ MetricData,
9
+ PushMetricExporter,
10
+ ResourceMetrics
11
+ } from '@opentelemetry/sdk-metrics';
12
+
13
+ /**
14
+ * Decorates a push exporter and removes selected attributes from every metric data point before
15
+ * delegating the export. The input metrics are not mutated, so another reader can export the
16
+ * original attributes.
17
+ *
18
+ * This exporter deliberately does not merge data points when filtering makes their attribute sets
19
+ * identical. Both points are forwarded with the same attributes. There is no generally correct
20
+ * merge operation at this layer: gauges, counters, and histograms have different aggregation
21
+ * semantics. Callers must therefore ensure that an excluded attribute does not distinguish data
22
+ * points for the same metric, resource, and instrumentation scope. Otherwise, the resulting
23
+ * duplicate series identity may be rejected or interpreted unpredictably downstream.
24
+ *
25
+ * Lifecycle methods and aggregation selection are delegated unchanged to the wrapped exporter.
26
+ */
27
+ export class MetricAttributeFilteringExporter implements PushMetricExporter {
28
+ readonly selectAggregation?: AggregationSelector;
29
+ readonly selectAggregationTemporality?: AggregationTemporalitySelector;
30
+
31
+ constructor(
32
+ /** The exporter that receives the filtered copy of the metrics. */
33
+ private readonly delegate: PushMetricExporter,
34
+ /** Attribute names to remove from every exported data point. */
35
+ private readonly excludedAttributes: ReadonlySet<string>
36
+ ) {
37
+ this.selectAggregation = delegate.selectAggregation?.bind(delegate);
38
+ this.selectAggregationTemporality = delegate.selectAggregationTemporality?.bind(delegate);
39
+ }
40
+
41
+ export(metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void): void {
42
+ this.delegate.export(this.filterAttributes(metrics), resultCallback);
43
+ }
44
+
45
+ forceFlush(): Promise<void> {
46
+ return this.delegate.forceFlush();
47
+ }
48
+
49
+ shutdown(): Promise<void> {
50
+ return this.delegate.shutdown();
51
+ }
52
+
53
+ private filterAttributes(metrics: ResourceMetrics): ResourceMetrics {
54
+ return {
55
+ ...metrics,
56
+ scopeMetrics: metrics.scopeMetrics.map((scopeMetrics) => ({
57
+ ...scopeMetrics,
58
+ metrics: scopeMetrics.metrics.map((metric) => this.filterMetricAttributes(metric))
59
+ }))
60
+ };
61
+ }
62
+
63
+ private filterMetricAttributes(metric: MetricData): MetricData {
64
+ switch (metric.dataPointType) {
65
+ case DataPointType.SUM:
66
+ case DataPointType.GAUGE:
67
+ return { ...metric, dataPoints: metric.dataPoints.map((dataPoint) => this.filterDataPoint(dataPoint)) };
68
+ case DataPointType.HISTOGRAM:
69
+ return { ...metric, dataPoints: metric.dataPoints.map((dataPoint) => this.filterDataPoint(dataPoint)) };
70
+ case DataPointType.EXPONENTIAL_HISTOGRAM:
71
+ return { ...metric, dataPoints: metric.dataPoints.map((dataPoint) => this.filterDataPoint(dataPoint)) };
72
+ }
73
+ }
74
+
75
+ private filterDataPoint<T>(dataPoint: DataPoint<T>): DataPoint<T> {
76
+ return {
77
+ ...dataPoint,
78
+ attributes: this.filterDataPointAttributes(dataPoint.attributes)
79
+ };
80
+ }
81
+
82
+ private filterDataPointAttributes(attributes: Attributes): Attributes {
83
+ return Object.fromEntries(Object.entries(attributes).filter(([name]) => !this.excludedAttributes.has(name)));
84
+ }
85
+ }
@@ -4,6 +4,7 @@ import {
4
4
  MetricMetadata,
5
5
  MetricsFactory,
6
6
  ObservableGauge,
7
+ ObservableGaugeObservation,
7
8
  Precision,
8
9
  UpDownCounter
9
10
  } from '../metrics-interfaces.js';
@@ -31,12 +32,16 @@ export class OpenTelemetryMetricsFactory implements MetricsFactory {
31
32
  });
32
33
 
33
34
  return {
34
- setValueProvider(valueProvider: () => Promise<number | undefined>) {
35
+ setValueProvider(valueProvider: () => Promise<number | ObservableGaugeObservation[] | undefined>) {
35
36
  gauge.addCallback(async (result) => {
36
37
  const value = await valueProvider();
37
38
 
38
- if (value != undefined) {
39
+ if (typeof value === 'number') {
39
40
  result.observe(value);
41
+ } else if (value != undefined) {
42
+ for (const observation of value) {
43
+ result.observe(observation.value, observation.attributes);
44
+ }
40
45
  }
41
46
  });
42
47
  }
@@ -4,6 +4,7 @@ import { MeterProvider, MetricReader, PeriodicExportingMetricReader } from '@ope
4
4
  import { logger } from '@powersync/lib-services-framework';
5
5
  import { ServiceContext } from '../../system/ServiceContext.js';
6
6
  import { MetricsFactory } from '../metrics-interfaces.js';
7
+ import { MetricAttributeFilteringExporter } from './MetricAttributeFilteringExporter.js';
7
8
  import { OpenTelemetryMetricsFactory } from './OpenTelemetryMetricsFactory.js';
8
9
 
9
10
  import { resourceFromAttributes } from '@opentelemetry/resources';
@@ -29,10 +30,13 @@ export function createOpenTelemetryMetricsFactory(context: ServiceContext): Metr
29
30
  }
30
31
 
31
32
  if (!configuration.telemetry.disable_telemetry_sharing) {
33
+ const otlpExporter = new OTLPMetricExporter({
34
+ url: configuration.telemetry.internal_service_endpoint
35
+ });
32
36
  const periodicExporter = new PeriodicExportingMetricReader({
33
- exporter: new OTLPMetricExporter({
34
- url: configuration.telemetry.internal_service_endpoint
35
- }),
37
+ // sync_config_id uniquely identifies these metric series after version_label is removed,
38
+ // so filtering cannot create duplicate data points.
39
+ exporter: new MetricAttributeFilteringExporter(otlpExporter, new Set(['version_label'])),
36
40
  exportIntervalMillis: 1000 * 60 * 5 // 5 minutes
37
41
  });
38
42
 
@@ -1,6 +1,7 @@
1
1
  import * as framework from '@powersync/lib-services-framework';
2
2
  import fs from 'fs/promises';
3
3
  import path from 'path';
4
+ import { pathToFileURL } from 'url';
4
5
  import * as system from '../system/system-index.js';
5
6
 
6
7
  /**
@@ -28,7 +29,7 @@ export abstract class AbstractPowerSyncMigrationAgent extends framework.Abstract
28
29
 
29
30
  return await Promise.all(
30
31
  migrations.map(async (migration) => {
31
- const module = await import(path.resolve(migrationsDir, migration));
32
+ const module = await import(pathToFileURL(path.resolve(migrationsDir, migration)).href);
32
33
  return {
33
34
  name: path.basename(migration).replace(path.extname(migration), ''),
34
35
  up: module.up,
@@ -11,8 +11,8 @@ import { AbstractReplicationJob } from './AbstractReplicationJob.js';
11
11
  import { ErrorRateLimiter } from './ErrorRateLimiter.js';
12
12
  import { ConnectionTestResult } from './ReplicationModule.js';
13
13
 
14
- // 1 minute
15
- const PING_INTERVAL = 1_000_000_000n * 60n;
14
+ // Default to 1 minute when no source-specific interval is configured.
15
+ const DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 60;
16
16
 
17
17
  // In the initial startup period, we use a short refresh interval. This helps to take over replication quickly in the case
18
18
  // of rolling deploys. After the initial period, we switch to a longer refresh interval to reduce load.
@@ -34,6 +34,10 @@ export interface AbstractReplicatorOptions {
34
34
  * This limits the effect of retries when there is a persistent issue.
35
35
  */
36
36
  rateLimiter: ErrorRateLimiter;
37
+ /**
38
+ * Interval in seconds between source connection pings. Null or undefined uses the default; 0 disables pings.
39
+ */
40
+ heartbeatIntervalSeconds?: number | null;
37
41
  }
38
42
 
39
43
  /**
@@ -62,13 +66,18 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
62
66
  */
63
67
  private activeReplicationJob: T | undefined = undefined;
64
68
 
65
- // First ping is only after 5 minutes, not when starting
69
+ // The first ping is only after the configured interval, not when starting.
66
70
  private lastPing = hrtime.bigint();
67
71
 
72
+ private readonly heartbeatIntervalNanos: bigint | null;
73
+
68
74
  private abortController: AbortController | undefined;
69
75
 
70
76
  protected constructor(private options: AbstractReplicatorOptions) {
71
77
  this.logger = logger.child({ name: `Replicator:${options.id}` });
78
+ const heartbeatIntervalSeconds = options.heartbeatIntervalSeconds ?? DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
79
+ this.heartbeatIntervalNanos =
80
+ heartbeatIntervalSeconds === 0 ? null : BigInt(Math.round(heartbeatIntervalSeconds * 1_000_000_000));
72
81
  }
73
82
 
74
83
  /**
@@ -147,7 +156,8 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
147
156
 
148
157
  let configuredLock: storage.ReplicationLock | undefined = undefined;
149
158
  if (loadedSyncConfig != null) {
150
- this.logger.info('Loaded sync config');
159
+ const versionLabel = this.syncRuleProvider.versionLabel;
160
+ this.logger.info(`Loaded sync config${versionLabel == null ? '' : ` ${versionLabel}`}`);
151
161
  try {
152
162
  // Configure new sync config, if they have changed.
153
163
  // In that case, also immediately take out a lock, so that another process doesn't start replication on it.
@@ -155,8 +165,16 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
155
165
  // versions before that check was added, so we keep the lock for now - for where te service version and sync config is updated at
156
166
  // the same time.
157
167
 
168
+ const parsed = this.options.storageEngine.activeBucketStorage.syncConfigParser.parseContent(loadedSyncConfig, {
169
+ schema: undefined,
170
+ defaultSchema: 'not_applicable',
171
+ throwOnError: this.syncRuleProvider.exitOnError
172
+ });
158
173
  const { lock } = await this.storage.configureSyncRules(
159
- storage.updateSyncRulesFromYaml(loadedSyncConfig, { lock: true, validate: this.syncRuleProvider.exitOnError })
174
+ storage.updateSyncRulesFromConfig(parsed, {
175
+ lock: true,
176
+ version_label: versionLabel
177
+ })
160
178
  );
161
179
  if (lock) {
162
180
  configuredLock = lock;
@@ -168,14 +186,18 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
168
186
  throw e;
169
187
  }
170
188
  } else {
171
- this.logger.info('No sync streams or rules configured - configure via API');
189
+ this.logger.info('No sync config configured - configure via API');
172
190
  }
173
191
  let useFastRefresh = true;
174
192
  const fastRefreshDeadline = Date.now() + FAST_REFRESH_TIMEOUT_MS;
175
193
  while (!this.stopped) {
176
194
  await container.probes.touch();
177
195
  try {
178
- const refreshResult = await this.refresh({ configuredLock, loadedSyncConfig });
196
+ const refreshResult = await this.refresh({
197
+ configuredLock,
198
+ loadedSyncConfig,
199
+ loadedVersionLabel: this.syncRuleProvider.versionLabel
200
+ });
179
201
  if (refreshResult.replicationJobStarted || Date.now() >= fastRefreshDeadline) {
180
202
  useFastRefresh = false;
181
203
  }
@@ -184,9 +206,9 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
184
206
 
185
207
  // Ensure that the replication jobs' connections are kept alive.
186
208
  // We don't ping while in error retry back-off, to avoid having too failures.
187
- if (this.rateLimiter.mayPing()) {
209
+ if (this.heartbeatIntervalNanos != null && this.rateLimiter.mayPing()) {
188
210
  const now = hrtime.bigint();
189
- if (now - this.lastPing >= PING_INTERVAL) {
211
+ if (now - this.lastPing >= this.heartbeatIntervalNanos) {
190
212
  for (const activeJob of this.replicationJobs.values()) {
191
213
  await activeJob.keepAlive();
192
214
  }
@@ -207,6 +229,7 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
207
229
  private async refresh(options?: {
208
230
  configuredLock?: storage.ReplicationLock;
209
231
  loadedSyncConfig?: string;
232
+ loadedVersionLabel?: string;
210
233
  }): Promise<{ replicationJobStarted: boolean }> {
211
234
  if (this.stopped) {
212
235
  return { replicationJobStarted: false };
@@ -224,7 +247,9 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
224
247
  const jobId = replicationStream.replicationJobId;
225
248
  const existingJob = existingJobs.get(jobId);
226
249
  const syncConfigMismatchMessage = 'Ignoring replication stream for sync config not loaded by this process';
227
- if (!this.shouldHandleReplicationStream(replicationStream, options?.loadedSyncConfig)) {
250
+ if (
251
+ !this.shouldHandleReplicationStream(replicationStream, options?.loadedSyncConfig, options?.loadedVersionLabel)
252
+ ) {
228
253
  this.logReplicationStreamInfoOnce(replicationStream, 'sync-config-mismatch', () => {
229
254
  replicationStream.logger.info(syncConfigMismatchMessage);
230
255
  });
@@ -269,7 +294,7 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
269
294
  } else {
270
295
  lock = await replicationStream.lock();
271
296
  }
272
- const syncRuleStorage = this.storage.getInstance(replicationStream);
297
+ const syncRuleStorage = this.storage.getInstance(replicationStream, { replicationLock: lock });
273
298
  const newJob = this.createJob({
274
299
  lock: lock,
275
300
  storage: syncRuleStorage
@@ -362,7 +387,8 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
362
387
  */
363
388
  private shouldHandleReplicationStream(
364
389
  replicationStream: storage.PersistedReplicationStream,
365
- loadedSyncRules: string | undefined
390
+ loadedSyncRules: string | undefined,
391
+ loadedVersionLabel: string | undefined
366
392
  ) {
367
393
  if (loadedSyncRules == null) {
368
394
  return true;
@@ -371,7 +397,10 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
371
397
  const processingConfig = replicationStream.syncConfigContent.find(
372
398
  (syncConfig) => syncConfig.syncConfigState == storage.SyncRuleState.PROCESSING
373
399
  );
374
- return processingConfig == null || processingConfig.sync_rules_content == loadedSyncRules;
400
+ return (
401
+ processingConfig == null ||
402
+ (processingConfig.sync_rules_content == loadedSyncRules && processingConfig.version_label == loadedVersionLabel)
403
+ );
375
404
  }
376
405
 
377
406
  protected createJobId(syncRuleId: number) {
@@ -63,14 +63,6 @@ export abstract class ReplicationModule<TConfig extends types.configFile.DataSou
63
63
  */
64
64
  protected abstract createReplicator(context: system.ServiceContext): AbstractReplicator;
65
65
 
66
- /**
67
- * Any additional initialization specific to the module should be added here. Will be called if necessary after the
68
- * main initialization has been completed
69
- * @param context
70
- * @protected
71
- */
72
- protected abstract onInitialized(context: system.ServiceContext): Promise<void>;
73
-
74
66
  public abstract testConnection(config: TConfig): Promise<ConnectionTestResult>;
75
67
 
76
68
  /**
@@ -100,8 +92,6 @@ export abstract class ReplicationModule<TConfig extends types.configFile.DataSou
100
92
 
101
93
  context.replicationEngine?.register(this.createReplicator(context));
102
94
  context.routerEngine?.registerAPI(this.createRouteAPIAdapter());
103
-
104
- await this.onInitialized(context);
105
95
  }
106
96
 
107
97
  protected decodeConfig(config: TConfig): void {
@@ -1,13 +1,7 @@
1
1
  import * as sqlite from 'node:sqlite';
2
2
 
3
3
  import { ErrorCode, errors, router, schema } from '@powersync/lib-services-framework';
4
- import {
5
- HydratedSyncConfig,
6
- nodeSqlite,
7
- SourceSchema,
8
- SqlSyncRules,
9
- StaticSchema
10
- } from '@powersync/service-sync-rules';
4
+ import { HydratedSyncConfig, nodeSqlite, SourceSchema, StaticSchema } from '@powersync/service-sync-rules';
11
5
  import { internal_routes } from '@powersync/service-types';
12
6
 
13
7
  import { DEFAULT_HYDRATION_STATE } from '@powersync/service-sync-rules';
@@ -158,14 +152,20 @@ export const reprocess = routeDefinition({
158
152
  });
159
153
  }
160
154
  // There are some differences between this and using asUpdateOptions():
161
- // 1. This always re-parses the source YAML. If there are changes to the sync stream compiler, that can affect the sync plan.
155
+ // 1. This always re-parses the source YAML. If there are changes to the Sync Streams compiler, that can affect the sync plan.
162
156
  // 2. If the source does not set the storage version, this will update it do the current version.
163
157
  // We can consider tweaking this behavior in the future.
158
+ const parsed = service_context.syncConfigParser.parseContent(active.content.sync_rules_content, {
159
+ ...apiHandler.getParseSyncRulesOptions(),
160
+ schema: undefined,
161
+ // This sync config already passed validation. But if the config is not valid anymore due
162
+ // to a service change, we do want to report the error here.
163
+ throwOnError: true
164
+ });
164
165
  const new_rules = await activeBucketStorage.updateSyncRules(
165
- storage.updateSyncRulesFromYaml(active.content.sync_rules_content, {
166
- // This sync config already passed validation. But if the config is not valid anymore due
167
- // to a service change, we do want to report the error here.
168
- validate: true
166
+ storage.updateSyncRulesFromConfig(parsed, {
167
+ version_label: active.content.version_label,
168
+ forceNewReplicationStream: true
169
169
  })
170
170
  );
171
171
 
@@ -186,16 +186,16 @@ export const reprocess = routeDefinition({
186
186
 
187
187
  class FakeSyncRulesContentForValidation extends storage.PersistedSyncConfigContent {
188
188
  constructor(
189
- private readonly apiHandler: api.RouteAPI,
189
+ private readonly validationParser: storage.SyncConfigParser,
190
190
  private readonly schema: SourceSchema,
191
191
  data: storage.PersistedSyncConfigContentData
192
192
  ) {
193
- super(data);
193
+ super(data, validationParser);
194
194
  }
195
195
 
196
196
  parsed(options: storage.ParseSyncConfigOptions): storage.ParsedSyncConfigSet {
197
- const syncConfig = SqlSyncRules.fromYaml(this.sync_rules_content, {
198
- ...this.apiHandler.getParseSyncRulesOptions(),
197
+ const syncConfig = this.validationParser.parseContent(this.sync_rules_content, {
198
+ ...options,
199
199
  schema: this.schema
200
200
  });
201
201
 
@@ -235,7 +235,7 @@ export const validate = routeDefinition({
235
235
  const schemaData = await api.getConnectionsSchema(apiHandler);
236
236
  const schema = new StaticSchema(schemaData.connections);
237
237
 
238
- const sync_rules = new FakeSyncRulesContentForValidation(apiHandler, schema, {
238
+ const sync_rules = new FakeSyncRulesContentForValidation(service_context.syncConfigParser, schema, {
239
239
  // Dummy values
240
240
  replicationStreamId: 0,
241
241
  replicationStreamName: '',
@@ -16,6 +16,10 @@ export const syncStreamReactive: SocketRouteGenerator = (router) =>
16
16
  const { routerEngine, metricsEngine, syncContext } = service_context;
17
17
  const streamStart = Date.now();
18
18
 
19
+ // Format client-controlled values before registering connection resources.
20
+ const formattedAppMetadata = params.app_metadata ? limitParamsForLogging(params.app_metadata) : undefined;
21
+ const formattedClientParams = params.parameters ? limitParamsForLogging(params.parameters) : undefined;
22
+
19
23
  logger.defaultMeta = {
20
24
  ...logger.defaultMeta,
21
25
  user_id: context.token_payload!.userIdJson,
@@ -99,13 +103,12 @@ export const syncStreamReactive: SocketRouteGenerator = (router) =>
99
103
  tracker.setCompressed(connection.tracker.encoding);
100
104
  }
101
105
 
102
- const formattedAppMetadata = params.app_metadata ? limitParamsForLogging(params.app_metadata) : undefined;
103
- logger.info('Sync stream started', {
104
- app_metadata: formattedAppMetadata,
105
- client_params: params.parameters ? limitParamsForLogging(params.parameters) : undefined
106
- });
107
-
108
106
  try {
107
+ logger.info('Sync stream started', {
108
+ app_metadata: formattedAppMetadata,
109
+ client_params: formattedClientParams
110
+ });
111
+
109
112
  for await (const data of sync.streamResponse({
110
113
  syncContext: syncContext,
111
114
  bucketStorage: bucketStorage,
@@ -1,10 +1,11 @@
1
1
  import { ErrorCode, errors, router, schema } from '@powersync/lib-services-framework';
2
- import { SqlSyncRules, SyncConfigWithErrors, SyncRulesErrors } from '@powersync/service-sync-rules';
2
+ import { SyncConfigWithErrors, SyncRulesErrors } from '@powersync/service-sync-rules';
3
3
  import type { FastifyPluginAsync } from 'fastify';
4
4
  import * as t from 'ts-codec';
5
5
 
6
6
  import { RouteAPI } from '../../api/RouteAPI.js';
7
- import { updateSyncRulesFromConfig, updateSyncRulesFromYaml } from '../../storage/BucketStorageFactory.js';
7
+ import { updateSyncRulesFromConfig } from '../../storage/BucketStorageFactory.js';
8
+ import { SyncConfigParser } from '../../storage/SyncConfigParser.js';
8
9
  import { authApi } from '../auth.js';
9
10
  import { routeDefinition } from '../router.js';
10
11
 
@@ -56,7 +57,7 @@ export const deploySyncRules = routeDefinition({
56
57
 
57
58
  try {
58
59
  const apiHandler = service_context.routerEngine.getAPI();
59
- syncConfig = SqlSyncRules.fromYaml(content, {
60
+ syncConfig = service_context.syncConfigParser.parseContent(content, {
60
61
  ...apiHandler.getParseSyncRulesOptions(),
61
62
  // We don't do any schema-level validation at this point
62
63
  schema: undefined
@@ -94,7 +95,7 @@ export const validateSyncRules = routeDefinition({
94
95
  const { service_context } = payload.context;
95
96
  const apiHandler = service_context.routerEngine.getAPI();
96
97
 
97
- const info = await debugSyncRules(apiHandler, content);
98
+ const info = await debugSyncRules(apiHandler, content, service_context.syncConfigParser);
98
99
 
99
100
  return replyPrettyJson(info);
100
101
  }
@@ -121,10 +122,12 @@ export const currentSyncRules = routeDefinition({
121
122
 
122
123
  const sync_rules = active.content;
123
124
  const apiHandler = service_context.routerEngine.getAPI();
124
- const info = await debugSyncRules(apiHandler, sync_rules.sync_rules_content);
125
+ const info = await debugSyncRules(apiHandler, sync_rules.sync_rules_content, service_context.syncConfigParser);
125
126
  const next = await activeBucketStorage.getDeployingSyncConfig();
126
127
 
127
- const next_info = next ? await debugSyncRules(apiHandler, next.content.sync_rules_content) : null;
128
+ const next_info = next
129
+ ? await debugSyncRules(apiHandler, next.content.sync_rules_content, service_context.syncConfigParser)
130
+ : null;
128
131
 
129
132
  const response = {
130
133
  current: {
@@ -176,11 +179,17 @@ export const reprocessSyncRules = routeDefinition({
176
179
  }
177
180
 
178
181
  const sync_rules = active.content;
182
+ const parsed = payload.context.service_context.syncConfigParser.parseContent(sync_rules.sync_rules_content, {
183
+ ...payload.context.service_context.routerEngine.getAPI().getParseSyncRulesOptions(),
184
+ schema: undefined,
185
+ // This sync config already passed validation. But if the rules are not valid anymore due
186
+ // to a service change, we do want to report the error here.
187
+ throwOnError: true
188
+ });
179
189
  const new_rules = await activeBucketStorage.updateSyncRules(
180
- updateSyncRulesFromYaml(sync_rules.sync_rules_content, {
181
- // This sync config already passed validation. But if the rules are not valid anymore due
182
- // to a service change, we do want to report the error here.
183
- validate: true
190
+ updateSyncRulesFromConfig(parsed, {
191
+ version_label: sync_rules.version_label,
192
+ forceNewReplicationStream: true
184
193
  })
185
194
  );
186
195
  return {
@@ -199,9 +208,9 @@ function replyPrettyJson(payload: any) {
199
208
  });
200
209
  }
201
210
 
202
- async function debugSyncRules(apiHandler: RouteAPI, sync_rules: string) {
211
+ async function debugSyncRules(apiHandler: RouteAPI, sync_rules: string, syncConfigParser: SyncConfigParser) {
203
212
  try {
204
- const rules = SqlSyncRules.fromYaml(sync_rules, {
213
+ const rules = syncConfigParser.parseContent(sync_rules, {
205
214
  ...apiHandler.getParseSyncRulesOptions(),
206
215
  // No schema-based validation at this point
207
216
  schema: undefined
@@ -176,7 +176,8 @@ export interface BucketStorageBatch extends ObserverClient<BucketBatchStorageLis
176
176
  * Queue a custom checkpoint request to be persisted after operations are
177
177
  * flushed. Set `checkpoint_requested_at` when the custom checkpoint came from
178
178
  * a client checkpoint request and should be cleaned up by request-retention
179
- * compaction; omit it for persistent source-owned checkpoints.
179
+ * compaction; omit it for persistent source-owned checkpoints. Incremental
180
+ * event handlers should copy `event_id` from their {@link ReplicationEventPayload}.
180
181
  */
181
182
  addCustomWriteCheckpoint(checkpoint: BatchedCustomWriteCheckpointOptions): void;
182
183
  }