@powersync/service-core 0.0.0-dev-20260602073133 → 0.0.0-dev-20260909133214

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 (230) hide show
  1. package/CHANGELOG.md +152 -4
  2. package/dist/api/RouteAPI.d.ts +42 -14
  3. package/dist/api/diagnostics.d.ts +12 -1
  4. package/dist/api/diagnostics.js +36 -22
  5. package/dist/api/diagnostics.js.map +1 -1
  6. package/dist/entry/commands/compact-action.js +30 -22
  7. package/dist/entry/commands/compact-action.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/modules/AbstractModule.d.ts +6 -2
  18. package/dist/modules/AbstractModule.js.map +1 -1
  19. package/dist/replication/AbstractReplicator.d.ts +31 -7
  20. package/dist/replication/AbstractReplicator.js +168 -74
  21. package/dist/replication/AbstractReplicator.js.map +1 -1
  22. package/dist/replication/ReplicationModule.d.ts +3 -3
  23. package/dist/replication/ReplicationModule.js.map +1 -1
  24. package/dist/routes/RouterEngine.d.ts +1 -0
  25. package/dist/routes/RouterEngine.js +6 -1
  26. package/dist/routes/RouterEngine.js.map +1 -1
  27. package/dist/routes/configure-fastify.d.ts +104 -56
  28. package/dist/routes/configure-fastify.js +15 -2
  29. package/dist/routes/configure-fastify.js.map +1 -1
  30. package/dist/routes/endpoints/admin.d.ts +42 -24
  31. package/dist/routes/endpoints/admin.js +49 -36
  32. package/dist/routes/endpoints/admin.js.map +1 -1
  33. package/dist/routes/endpoints/checkpointing.d.ts +62 -0
  34. package/dist/routes/endpoints/checkpointing.js +65 -7
  35. package/dist/routes/endpoints/checkpointing.js.map +1 -1
  36. package/dist/routes/endpoints/socket-route.js +3 -2
  37. package/dist/routes/endpoints/socket-route.js.map +1 -1
  38. package/dist/routes/endpoints/sync-rules.js +25 -14
  39. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  40. package/dist/routes/endpoints/sync-stream.js +1 -1
  41. package/dist/routes/endpoints/sync-stream.js.map +1 -1
  42. package/dist/runner/teardown.js +8 -8
  43. package/dist/runner/teardown.js.map +1 -1
  44. package/dist/storage/BucketStorageBatch.d.ts +64 -17
  45. package/dist/storage/BucketStorageBatch.js.map +1 -1
  46. package/dist/storage/BucketStorageFactory.d.ts +50 -31
  47. package/dist/storage/BucketStorageFactory.js +10 -20
  48. package/dist/storage/BucketStorageFactory.js.map +1 -1
  49. package/dist/storage/CheckpointChecksumInvalidatedError.d.ts +12 -0
  50. package/dist/storage/CheckpointChecksumInvalidatedError.js +17 -0
  51. package/dist/storage/CheckpointChecksumInvalidatedError.js.map +1 -0
  52. package/dist/storage/ChecksumCache.d.ts +11 -6
  53. package/dist/storage/ChecksumCache.js +5 -4
  54. package/dist/storage/ChecksumCache.js.map +1 -1
  55. package/dist/storage/ParsedSyncConfigSet.d.ts +23 -0
  56. package/dist/storage/ParsedSyncConfigSet.js +2 -0
  57. package/dist/storage/ParsedSyncConfigSet.js.map +1 -0
  58. package/dist/storage/PersistedReplicationStream.d.ts +32 -0
  59. package/dist/storage/PersistedReplicationStream.js +26 -0
  60. package/dist/storage/PersistedReplicationStream.js.map +1 -0
  61. package/dist/storage/PersistedSyncConfigContent.d.ts +65 -0
  62. package/dist/storage/PersistedSyncConfigContent.js +138 -0
  63. package/dist/storage/PersistedSyncConfigContent.js.map +1 -0
  64. package/dist/storage/PersistedSyncConfigStatus.d.ts +13 -0
  65. package/dist/storage/PersistedSyncConfigStatus.js +2 -0
  66. package/dist/storage/PersistedSyncConfigStatus.js.map +1 -0
  67. package/dist/storage/ReplicationEventPayload.d.ts +6 -1
  68. package/dist/storage/SourceEntity.d.ts +13 -2
  69. package/dist/storage/SourceTable.d.ts +53 -4
  70. package/dist/storage/SourceTable.js +62 -7
  71. package/dist/storage/SourceTable.js.map +1 -1
  72. package/dist/storage/SourceTableReconciler.d.ts +83 -0
  73. package/dist/storage/SourceTableReconciler.js +95 -0
  74. package/dist/storage/SourceTableReconciler.js.map +1 -0
  75. package/dist/storage/StorageVersionConfig.d.ts +4 -0
  76. package/dist/storage/StorageVersionConfig.js +10 -1
  77. package/dist/storage/StorageVersionConfig.js.map +1 -1
  78. package/dist/storage/SyncRulesBucketStorage.d.ts +162 -26
  79. package/dist/storage/SyncRulesBucketStorage.js +3 -0
  80. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  81. package/dist/storage/WriteCheckpointAPI.d.ts +85 -6
  82. package/dist/storage/WriteCheckpointAPI.js +33 -0
  83. package/dist/storage/WriteCheckpointAPI.js.map +1 -1
  84. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +133 -0
  85. package/dist/storage/implementation/BucketDefinitionMapping.js +351 -0
  86. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -0
  87. package/dist/storage/implementation/IncrementalReprocessingCompatibility.d.ts +6 -0
  88. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +31 -0
  89. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -0
  90. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.d.ts +17 -0
  91. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +70 -0
  92. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -0
  93. package/dist/storage/implementation/ReplicationStreamStorageIds.d.ts +15 -0
  94. package/dist/storage/implementation/ReplicationStreamStorageIds.js +20 -0
  95. package/dist/storage/implementation/ReplicationStreamStorageIds.js.map +1 -0
  96. package/dist/storage/storage-index.d.ts +10 -1
  97. package/dist/storage/storage-index.js +10 -1
  98. package/dist/storage/storage-index.js.map +1 -1
  99. package/dist/storage/storage-metrics.js +120 -4
  100. package/dist/storage/storage-metrics.js.map +1 -1
  101. package/dist/sync/BucketChecksumState.d.ts +12 -2
  102. package/dist/sync/BucketChecksumState.js +69 -21
  103. package/dist/sync/BucketChecksumState.js.map +1 -1
  104. package/dist/sync/RequestTracker.d.ts +7 -0
  105. package/dist/sync/RequestTracker.js +12 -0
  106. package/dist/sync/RequestTracker.js.map +1 -1
  107. package/dist/sync/sync.js +184 -43
  108. package/dist/sync/sync.js.map +1 -1
  109. package/dist/sync/util.d.ts +5 -0
  110. package/dist/sync/util.js +19 -1
  111. package/dist/sync/util.js.map +1 -1
  112. package/dist/system/ServiceContext.d.ts +2 -0
  113. package/dist/system/ServiceContext.js +2 -0
  114. package/dist/system/ServiceContext.js.map +1 -1
  115. package/dist/tracing/PerformanceTracer.d.ts +23 -1
  116. package/dist/tracing/PerformanceTracer.js +11 -0
  117. package/dist/tracing/PerformanceTracer.js.map +1 -1
  118. package/dist/util/checkpointing.d.ts +4 -8
  119. package/dist/util/checkpointing.js +1 -16
  120. package/dist/util/checkpointing.js.map +1 -1
  121. package/dist/util/config/compound-config-collector.js +23 -2
  122. package/dist/util/config/compound-config-collector.js.map +1 -1
  123. package/dist/util/config/defaults.d.ts +2 -0
  124. package/dist/util/config/defaults.js +2 -0
  125. package/dist/util/config/defaults.js.map +1 -1
  126. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
  127. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
  128. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
  129. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
  130. package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
  131. package/dist/util/config/sync-rules/sync-rules-provider.js +3 -0
  132. package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
  133. package/dist/util/config/types.d.ts +4 -1
  134. package/dist/util/lsn.d.ts +4 -0
  135. package/dist/util/lsn.js +10 -0
  136. package/dist/util/lsn.js.map +1 -1
  137. package/dist/util/protocol-types.d.ts +4 -4
  138. package/dist/util/protocol-types.js +3 -2
  139. package/dist/util/protocol-types.js.map +1 -1
  140. package/dist/util/util-index.d.ts +1 -0
  141. package/dist/util/util-index.js +1 -0
  142. package/dist/util/util-index.js.map +1 -1
  143. package/dist/util/utils.d.ts +3 -2
  144. package/dist/util/utils.js +17 -2
  145. package/dist/util/utils.js.map +1 -1
  146. package/dist/util/write-checkpoint-batcher.d.ts +19 -0
  147. package/dist/util/write-checkpoint-batcher.js +100 -0
  148. package/dist/util/write-checkpoint-batcher.js.map +1 -0
  149. package/package.json +7 -7
  150. package/src/api/RouteAPI.ts +43 -14
  151. package/src/api/diagnostics.ts +45 -26
  152. package/src/entry/commands/compact-action.ts +37 -23
  153. package/src/metrics/metrics-interfaces.ts +6 -1
  154. package/src/metrics/open-telemetry/MetricAttributeFilteringExporter.ts +85 -0
  155. package/src/metrics/open-telemetry/OpenTelemetryMetricsFactory.ts +7 -2
  156. package/src/metrics/open-telemetry/util.ts +7 -3
  157. package/src/modules/AbstractModule.ts +6 -2
  158. package/src/replication/AbstractReplicator.ts +212 -78
  159. package/src/replication/ReplicationModule.ts +2 -3
  160. package/src/routes/RouterEngine.ts +7 -1
  161. package/src/routes/configure-fastify.ts +25 -2
  162. package/src/routes/endpoints/admin.ts +75 -51
  163. package/src/routes/endpoints/checkpointing.ts +79 -8
  164. package/src/routes/endpoints/socket-route.ts +3 -2
  165. package/src/routes/endpoints/sync-rules.ts +26 -14
  166. package/src/routes/endpoints/sync-stream.ts +1 -1
  167. package/src/runner/teardown.ts +8 -8
  168. package/src/storage/BucketStorageBatch.ts +65 -18
  169. package/src/storage/BucketStorageFactory.ts +73 -46
  170. package/src/storage/CheckpointChecksumInvalidatedError.ts +17 -0
  171. package/src/storage/ChecksumCache.ts +27 -14
  172. package/src/storage/ParsedSyncConfigSet.ts +25 -0
  173. package/src/storage/PersistedReplicationStream.ts +55 -0
  174. package/src/storage/PersistedSyncConfigContent.ts +207 -0
  175. package/src/storage/PersistedSyncConfigStatus.ts +14 -0
  176. package/src/storage/ReplicationEventPayload.ts +6 -1
  177. package/src/storage/SourceEntity.ts +12 -2
  178. package/src/storage/SourceTable.ts +96 -8
  179. package/src/storage/SourceTableReconciler.ts +188 -0
  180. package/src/storage/StorageVersionConfig.ts +11 -1
  181. package/src/storage/SyncRulesBucketStorage.ts +189 -27
  182. package/src/storage/WriteCheckpointAPI.ts +140 -6
  183. package/src/storage/implementation/BucketDefinitionMapping.ts +539 -0
  184. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +41 -0
  185. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +126 -0
  186. package/src/storage/implementation/ReplicationStreamStorageIds.ts +21 -0
  187. package/src/storage/storage-index.ts +11 -1
  188. package/src/storage/storage-metrics.ts +154 -8
  189. package/src/sync/BucketChecksumState.ts +105 -21
  190. package/src/sync/RequestTracker.ts +20 -0
  191. package/src/sync/sync.ts +214 -50
  192. package/src/sync/util.ts +33 -8
  193. package/src/system/ServiceContext.ts +7 -0
  194. package/src/tracing/PerformanceTracer.ts +41 -1
  195. package/src/util/checkpointing.ts +4 -22
  196. package/src/util/config/compound-config-collector.ts +31 -1
  197. package/src/util/config/defaults.ts +2 -0
  198. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
  199. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
  200. package/src/util/config/sync-rules/sync-rules-provider.ts +5 -0
  201. package/src/util/config/types.ts +4 -1
  202. package/src/util/lsn.ts +9 -0
  203. package/src/util/protocol-types.ts +3 -2
  204. package/src/util/util-index.ts +1 -0
  205. package/src/util/utils.ts +16 -2
  206. package/src/util/write-checkpoint-batcher.ts +142 -0
  207. package/test/src/AbstractReplicator.test.ts +177 -0
  208. package/test/src/MetricAttributeFilteringExporter.test.ts +96 -0
  209. package/test/src/PersistedSyncConfigContent.test.ts +152 -0
  210. package/test/src/checksum_cache.test.ts +22 -0
  211. package/test/src/config.test.ts +142 -0
  212. package/test/src/diagnostics.test.ts +87 -34
  213. package/test/src/module-loader.test.ts +33 -1
  214. package/test/src/routes/admin.test.ts +188 -18
  215. package/test/src/routes/checkpointing.test.ts +54 -0
  216. package/test/src/routes/mocks.ts +6 -2
  217. package/test/src/routes/stream.test.ts +123 -2
  218. package/test/src/source-table-reconciler.test.ts +244 -0
  219. package/test/src/storage/SourceTable.test.ts +92 -0
  220. package/test/src/storage-metrics.test.ts +148 -0
  221. package/test/src/sync/BucketChecksumState.test.ts +98 -12
  222. package/test/src/sync/util.test.ts +28 -1
  223. package/test/src/util/checkpointing.test.ts +249 -0
  224. package/test/src/util/utils.test.ts +23 -0
  225. package/tsconfig.json +1 -4
  226. package/tsconfig.tsbuildinfo +1 -1
  227. package/dist/storage/PersistedSyncRulesContent.d.ts +0 -59
  228. package/dist/storage/PersistedSyncRulesContent.js +0 -100
  229. package/dist/storage/PersistedSyncRulesContent.js.map +0 -1
  230. package/src/storage/PersistedSyncRulesContent.ts +0 -174
@@ -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,13 +1,17 @@
1
1
  import { logger } from '@powersync/lib-services-framework';
2
2
  import winston from 'winston';
3
- import { PersistedSyncRulesContent } from '../storage/storage-index.js';
3
+ import { PersistedReplicationStream } from '../storage/storage-index.js';
4
4
  import { ServiceContextContainer } from '../system/ServiceContext.js';
5
5
 
6
6
  export interface TearDownOptions {
7
7
  /**
8
8
  * If required, tear down any configuration/state for the specific replication stream
9
9
  */
10
- syncRules?: PersistedSyncRulesContent[];
10
+ replicationStreams?: PersistedReplicationStream[];
11
+ /**
12
+ * @deprecated Use replicationStreams.
13
+ */
14
+ syncRules?: PersistedReplicationStream[];
11
15
  }
12
16
 
13
17
  export interface AbstractModuleOptions {
@@ -1,6 +1,7 @@
1
- import { container, ErrorCode, logger } from '@powersync/lib-services-framework';
1
+ import { container, ErrorCode, logger, ReplicationAbortedError } from '@powersync/lib-services-framework';
2
2
  import { ReplicationMetric } from '@powersync/service-types';
3
3
  import { hrtime } from 'node:process';
4
+ import { setTimeout as sleep } from 'node:timers/promises';
4
5
  import winston from 'winston';
5
6
  import { MetricsEngine } from '../metrics/MetricsEngine.js';
6
7
  import * as storage from '../storage/storage-index.js';
@@ -10,8 +11,14 @@ import { AbstractReplicationJob } from './AbstractReplicationJob.js';
10
11
  import { ErrorRateLimiter } from './ErrorRateLimiter.js';
11
12
  import { ConnectionTestResult } from './ReplicationModule.js';
12
13
 
13
- // 1 minute
14
- 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
+
17
+ // In the initial startup period, we use a short refresh interval. This helps to take over replication quickly in the case
18
+ // of rolling deploys. After the initial period, we switch to a longer refresh interval to reduce load.
19
+ const FAST_REFRESH_INTERVAL_MS = 500;
20
+ const FAST_REFRESH_TIMEOUT_MS = 120_000;
21
+ const REFRESH_INTERVAL_MS = 5_000;
15
22
 
16
23
  export interface CreateJobOptions {
17
24
  lock: storage.ReplicationLock;
@@ -27,6 +34,10 @@ export interface AbstractReplicatorOptions {
27
34
  * This limits the effect of retries when there is a persistent issue.
28
35
  */
29
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;
30
41
  }
31
42
 
32
43
  /**
@@ -36,35 +47,44 @@ export interface AbstractReplicatorOptions {
36
47
  */
37
48
  export abstract class AbstractReplicator<T extends AbstractReplicationJob = AbstractReplicationJob> {
38
49
  protected logger: winston.Logger;
39
- private lockAlerted: boolean = false;
50
+ private lastReplicationStreamInfoLogs = new Map<string, string>();
40
51
  /**
41
- * Map of replication jobs by replication stream id. Usually there is only one running job, but there could be two when
42
- * transitioning to a new replication stream.
52
+ * Map of replication jobs by replication stream job id. Usually there is only one running job, but there could be two
53
+ * when transitioning to a new replication stream.
43
54
  */
44
- private replicationJobs = new Map<number, T>();
55
+ private replicationJobs = new Map<string, T>();
45
56
 
46
57
  /**
47
- * Map of replciation stream ids to promises that are clearing the replication stream.
58
+ * Map of replication stream ids to promises that are clearing the replication stream.
48
59
  *
49
- * We primarily do this to keep track of what we're currently clearing, but don't currently
50
- * use the Promise value.
60
+ * We primarily do this to keep track of what we're currently clearing.
51
61
  */
52
- private clearingJobs = new Map<number, Promise<void>>();
62
+ protected readonly clearingJobs = new Map<number, Promise<void>>();
53
63
 
54
64
  /**
55
65
  * Used for replication lag computation.
56
66
  */
57
67
  private activeReplicationJob: T | undefined = undefined;
58
68
 
59
- // First ping is only after 5 minutes, not when starting
69
+ // The first ping is only after the configured interval, not when starting.
60
70
  private lastPing = hrtime.bigint();
61
71
 
72
+ private readonly heartbeatIntervalNanos: bigint | null;
73
+
62
74
  private abortController: AbortController | undefined;
63
75
 
64
76
  protected constructor(private options: AbstractReplicatorOptions) {
65
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));
66
81
  }
67
82
 
83
+ /**
84
+ * Create the source-specific replication job for a locked storage stream.
85
+ *
86
+ * The job owns the per-stream snapshot and streaming work for this attempt.
87
+ */
68
88
  abstract createJob(options: CreateJobOptions): T;
69
89
 
70
90
  /**
@@ -127,21 +147,30 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
127
147
  for (const job of this.replicationJobs.values()) {
128
148
  promises.push(job.stop());
129
149
  }
150
+ promises.push(...this.clearingJobs.values());
130
151
  await Promise.all(promises);
131
152
  }
132
153
 
133
154
  private async runLoop() {
134
- const syncRules = await this.syncRuleProvider.get();
155
+ const loadedSyncConfig = await this.syncRuleProvider.get();
135
156
 
136
157
  let configuredLock: storage.ReplicationLock | undefined = undefined;
137
- if (syncRules != null) {
138
- this.logger.info('Loaded sync config');
158
+ if (loadedSyncConfig != null) {
159
+ const versionLabel = this.syncRuleProvider.versionLabel;
160
+ this.logger.info(`Loaded sync config${versionLabel == null ? '' : ` ${versionLabel}`}`);
139
161
  try {
140
162
  // Configure new sync config, if they have changed.
141
163
  // In that case, also immediately take out a lock, so that another process doesn't start replication on it.
164
+ // This upfront lock is mostly superseded by the replicationStreamLoadedSyncConfigMatch() check. However, that doesn't cover old
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
166
+ // the same time.
142
167
 
143
168
  const { lock } = await this.storage.configureSyncRules(
144
- storage.updateSyncRulesFromYaml(syncRules, { lock: true, validate: this.syncRuleProvider.exitOnError })
169
+ storage.updateSyncRulesFromYaml(loadedSyncConfig, {
170
+ lock: true,
171
+ validate: this.syncRuleProvider.exitOnError,
172
+ version_label: versionLabel
173
+ })
145
174
  );
146
175
  if (lock) {
147
176
  configuredLock = lock;
@@ -155,18 +184,27 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
155
184
  } else {
156
185
  this.logger.info('No sync streams or rules configured - configure via API');
157
186
  }
187
+ let useFastRefresh = true;
188
+ const fastRefreshDeadline = Date.now() + FAST_REFRESH_TIMEOUT_MS;
158
189
  while (!this.stopped) {
159
190
  await container.probes.touch();
160
191
  try {
161
- await this.refresh({ configured_lock: configuredLock });
192
+ const refreshResult = await this.refresh({
193
+ configuredLock,
194
+ loadedSyncConfig,
195
+ loadedVersionLabel: this.syncRuleProvider.versionLabel
196
+ });
197
+ if (refreshResult.replicationJobStarted || Date.now() >= fastRefreshDeadline) {
198
+ useFastRefresh = false;
199
+ }
162
200
  // The lock is only valid on the first refresh.
163
201
  configuredLock = undefined;
164
202
 
165
203
  // Ensure that the replication jobs' connections are kept alive.
166
204
  // We don't ping while in error retry back-off, to avoid having too failures.
167
- if (this.rateLimiter.mayPing()) {
205
+ if (this.heartbeatIntervalNanos != null && this.rateLimiter.mayPing()) {
168
206
  const now = hrtime.bigint();
169
- if (now - this.lastPing >= PING_INTERVAL) {
207
+ if (now - this.lastPing >= this.heartbeatIntervalNanos) {
170
208
  for (const activeJob of this.replicationJobs.values()) {
171
209
  await activeJob.keepAlive();
172
210
  }
@@ -177,77 +215,62 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
177
215
  } catch (e) {
178
216
  this.logger.error('Failed to refresh replication jobs', e);
179
217
  }
180
- await new Promise((resolve) => setTimeout(resolve, 5000));
218
+ if (Date.now() >= fastRefreshDeadline) {
219
+ useFastRefresh = false;
220
+ }
221
+ await sleep(useFastRefresh ? FAST_REFRESH_INTERVAL_MS : REFRESH_INTERVAL_MS);
181
222
  }
182
223
  }
183
224
 
184
- private async refresh(options?: { configured_lock?: storage.ReplicationLock }) {
225
+ private async refresh(options?: {
226
+ configuredLock?: storage.ReplicationLock;
227
+ loadedSyncConfig?: string;
228
+ loadedVersionLabel?: string;
229
+ }): Promise<{ replicationJobStarted: boolean }> {
185
230
  if (this.stopped) {
186
- return;
231
+ return { replicationJobStarted: false };
187
232
  }
188
233
 
189
- let configuredLock = options?.configured_lock;
234
+ let configuredLock = options?.configuredLock;
235
+ let replicationJobStarted = false;
190
236
 
191
- const existingJobs = new Map<number, T>(this.replicationJobs.entries());
192
- const replicatingSyncRules = await this.storage.getReplicatingSyncRules();
193
- const newJobs = new Map<number, T>();
237
+ const existingJobs = new Map<string, T>(this.replicationJobs.entries());
238
+ const replicatingStreams = await this.storage.getReplicatingReplicationStreams();
239
+ const newJobs = new Map<string, T>();
240
+ const streamsToStart: storage.PersistedReplicationStream[] = [];
194
241
  let activeJob: T | undefined = undefined;
195
- for (let syncRules of replicatingSyncRules) {
196
- const existingJob = existingJobs.get(syncRules.id);
197
- if (syncRules.active && activeJob == null) {
242
+ for (let replicationStream of replicatingStreams) {
243
+ const jobId = replicationStream.replicationJobId;
244
+ const existingJob = existingJobs.get(jobId);
245
+ const syncConfigMismatchMessage = 'Ignoring replication stream for sync config not loaded by this process';
246
+ if (
247
+ !this.shouldHandleReplicationStream(replicationStream, options?.loadedSyncConfig, options?.loadedVersionLabel)
248
+ ) {
249
+ this.logReplicationStreamInfoOnce(replicationStream, 'sync-config-mismatch', () => {
250
+ replicationStream.logger.info(syncConfigMismatchMessage);
251
+ });
252
+ continue;
253
+ }
254
+ this.clearReplicationStreamInfoLog(replicationStream, 'sync-config-mismatch');
255
+ if (replicationStream.state == storage.SyncRuleState.ACTIVE && activeJob == null) {
198
256
  activeJob = existingJob;
199
257
  }
200
258
  if (existingJob && !existingJob.isStopped) {
201
259
  // No change
202
- existingJobs.delete(syncRules.id);
203
- newJobs.set(syncRules.id, existingJob);
260
+ existingJobs.delete(jobId);
261
+ newJobs.set(jobId, existingJob);
204
262
  } else if (existingJob && existingJob.isStopped) {
205
263
  // Stopped (e.g. fatal error).
206
264
  // Remove from the list. Next refresh call will restart the job.
207
- existingJobs.delete(syncRules.id);
265
+ existingJobs.delete(jobId);
208
266
  } else {
209
267
  // New sync config was found (or resume after restart)
210
- try {
211
- let lock: storage.ReplicationLock;
212
- if (configuredLock?.sync_rules_id == syncRules.id) {
213
- lock = configuredLock;
214
- } else {
215
- lock = await syncRules.lock();
216
- }
217
- const storage = this.storage.getInstance(syncRules);
218
- const newJob = this.createJob({
219
- lock: lock,
220
- storage: storage
221
- });
222
-
223
- newJobs.set(syncRules.id, newJob);
224
- newJob.start();
225
- if (syncRules.active) {
226
- activeJob = newJob;
227
- }
228
- this.lockAlerted = false;
229
- } catch (e) {
230
- if (e?.errorData?.code === ErrorCode.PSYNC_S1003) {
231
- if (!this.lockAlerted) {
232
- syncRules.logger.info(`[${e.errorData.code}] ${e.errorData.description}`);
233
- this.lockAlerted = true;
234
- }
235
- } else {
236
- // Could be a sync config parse error,
237
- // for example from stricter validation that was added.
238
- // This will be retried every couple of seconds.
239
- // When new (valid) sync config is deployed and processed, this one be disabled.
240
- syncRules.logger.error('Failed to start replication for new sync config', e);
241
- }
242
- }
268
+ streamsToStart.push(replicationStream);
243
269
  }
244
270
  }
245
271
 
246
- this.replicationJobs = newJobs;
247
- this.activeReplicationJob = activeJob;
248
-
249
- // Stop any orphaned jobs that no longer have a replication stream.
250
- // Termination happens below
272
+ // Stop any orphaned jobs that no longer have a replication stream before starting replacements.
273
+ // Termination happens below.
251
274
  for (let job of existingJobs.values()) {
252
275
  // Old - stop and clean up
253
276
  try {
@@ -258,10 +281,50 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
258
281
  }
259
282
  }
260
283
 
284
+ for (let replicationStream of streamsToStart) {
285
+ const jobId = replicationStream.replicationJobId;
286
+ try {
287
+ let lock: storage.ReplicationLock;
288
+ if (configuredLock?.sync_rules_id == replicationStream.replicationStreamId) {
289
+ lock = configuredLock;
290
+ } else {
291
+ lock = await replicationStream.lock();
292
+ }
293
+ const syncRuleStorage = this.storage.getInstance(replicationStream);
294
+ const newJob = this.createJob({
295
+ lock: lock,
296
+ storage: syncRuleStorage
297
+ });
298
+
299
+ newJobs.set(jobId, newJob);
300
+ newJob.start();
301
+ replicationJobStarted = true;
302
+ if (replicationStream.state == storage.SyncRuleState.ACTIVE) {
303
+ activeJob = newJob;
304
+ }
305
+ this.lastReplicationStreamInfoLogs.delete(replicationStream.replicationStreamName);
306
+ } catch (e) {
307
+ if (e?.errorData?.code === ErrorCode.PSYNC_S1003) {
308
+ this.logReplicationStreamInfoOnce(replicationStream, 'replication-stream-locked', () => {
309
+ replicationStream.logger.info(`[${e.errorData.code}] ${e.errorData.description}`);
310
+ });
311
+ } else {
312
+ // Could be a sync config parse error,
313
+ // for example from stricter validation that was added.
314
+ // This will be retried every couple of seconds.
315
+ // When new (valid) sync config is deployed and processed, this one be disabled.
316
+ replicationStream.logger.error('Failed to start replication for new sync config', e);
317
+ }
318
+ }
319
+ }
320
+
321
+ this.replicationJobs = newJobs;
322
+ this.activeReplicationJob = activeJob;
323
+
261
324
  // Replication stream stopped previously, including by a different process.
262
- const stopped = await this.storage.getStoppedSyncRules();
263
- for (let syncRules of stopped) {
264
- if (this.clearingJobs.has(syncRules.id)) {
325
+ const stopped = await this.storage.getStoppedReplicationStreams();
326
+ for (let replicationStream of stopped) {
327
+ if (this.clearingJobs.has(replicationStream.replicationStreamId)) {
265
328
  // Already in progress
266
329
  continue;
267
330
  }
@@ -269,22 +332,90 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
269
332
  // We clear storage asynchronously.
270
333
  // It is important to be able to continue running the refresh loop, otherwise we cannot
271
334
  // retry locked replication stream, for example.
272
- const syncRuleStorage = this.storage.getInstance(syncRules, { skipLifecycleHooks: true });
273
- const promise = this.terminateSyncRules(syncRuleStorage)
335
+ const syncRuleStorage = this.storage.getInstance(replicationStream, { skipLifecycleHooks: true });
336
+ const promise = this.terminateStoppedReplicationStream(replicationStream, syncRuleStorage)
274
337
  .catch((e) => {
275
- syncRuleStorage.logger.warn(`Failed clean up replication config`, e);
338
+ if (e instanceof ReplicationAbortedError) {
339
+ // Expected when shutdown aborts an in-progress cleanup.
340
+ } else if (e?.errorData?.code === ErrorCode.PSYNC_S1003) {
341
+ this.logReplicationStreamInfoOnce(replicationStream, 'replication-stream-cleanup-locked', () => {
342
+ replicationStream.logger.info(`[${e.errorData.code}] ${e.errorData.description}`);
343
+ });
344
+ } else {
345
+ syncRuleStorage.logger.warn(`Failed clean up replication config`, e);
346
+ }
276
347
  })
277
348
  .finally(() => {
278
- this.clearingJobs.delete(syncRules.id);
349
+ this.clearingJobs.delete(replicationStream.replicationStreamId);
279
350
  });
280
- this.clearingJobs.set(syncRules.id, promise);
351
+ this.clearingJobs.set(replicationStream.replicationStreamId, promise);
352
+ }
353
+
354
+ return { replicationJobStarted };
355
+ }
356
+
357
+ private logReplicationStreamInfoOnce(
358
+ replicationStream: storage.PersistedReplicationStream,
359
+ category: string,
360
+ log: () => void
361
+ ) {
362
+ if (this.lastReplicationStreamInfoLogs.get(replicationStream.replicationStreamName) == category) {
363
+ return;
364
+ }
365
+
366
+ log();
367
+ this.lastReplicationStreamInfoLogs.set(replicationStream.replicationStreamName, category);
368
+ }
369
+
370
+ private clearReplicationStreamInfoLog(replicationStream: storage.PersistedReplicationStream, category: string) {
371
+ if (this.lastReplicationStreamInfoLogs.get(replicationStream.replicationStreamName) == category) {
372
+ this.lastReplicationStreamInfoLogs.delete(replicationStream.replicationStreamName);
373
+ }
374
+ }
375
+
376
+ /**
377
+ * When we load sync config from the filesystem/config source, we ignore any config loaded by other processes.
378
+ * The idea is that if a different process loads updated config, that process should process it, not this one.
379
+ *
380
+ * This specifically helps for cases with rolling deploys.
381
+ *
382
+ * This does not apply when sync config is loaded from the database/API, instead of in the config.
383
+ */
384
+ private shouldHandleReplicationStream(
385
+ replicationStream: storage.PersistedReplicationStream,
386
+ loadedSyncRules: string | undefined,
387
+ loadedVersionLabel: string | undefined
388
+ ) {
389
+ if (loadedSyncRules == null) {
390
+ return true;
281
391
  }
392
+
393
+ const processingConfig = replicationStream.syncConfigContent.find(
394
+ (syncConfig) => syncConfig.syncConfigState == storage.SyncRuleState.PROCESSING
395
+ );
396
+ return (
397
+ processingConfig == null ||
398
+ (processingConfig.sync_rules_content == loadedSyncRules && processingConfig.version_label == loadedVersionLabel)
399
+ );
282
400
  }
283
401
 
284
402
  protected createJobId(syncRuleId: number) {
285
403
  return `${this.id}-${syncRuleId}`;
286
404
  }
287
405
 
406
+ protected async terminateStoppedReplicationStream(
407
+ replicationStream: storage.PersistedReplicationStream,
408
+ syncRuleStorage: storage.SyncRulesBucketStorage
409
+ ) {
410
+ const lock = await replicationStream.lock();
411
+ this.clearReplicationStreamInfoLog(replicationStream, 'replication-stream-cleanup-locked');
412
+ try {
413
+ await this.terminateSyncRules(syncRuleStorage);
414
+ } finally {
415
+ await lock.release();
416
+ }
417
+ }
418
+
288
419
  protected async terminateSyncRules(syncRuleStorage: storage.SyncRulesBucketStorage) {
289
420
  syncRuleStorage.logger.info(`Terminating replication stream...`);
290
421
  // This deletes postgres replication slots - should complete quickly.
@@ -294,6 +425,9 @@ export abstract class AbstractReplicator<T extends AbstractReplicationJob = Abst
294
425
  syncRuleStorage.logger.info(`Successfully terminated replication stream`);
295
426
  }
296
427
 
428
+ /**
429
+ * Check source connectivity using the replicator's decoded connection config.
430
+ */
297
431
  abstract testConnection(): Promise<ConnectionTestResult>;
298
432
 
299
433
  /**
@@ -1,4 +1,3 @@
1
- import { DataSourceConfig } from '@powersync/service-types/dist/config/PowerSyncConfig.js';
2
1
  import * as t from 'ts-codec';
3
2
 
4
3
  import { schema } from '@powersync/lib-services-framework';
@@ -18,7 +17,7 @@ export interface ConnectionTestResult {
18
17
  /**
19
18
  * Provides a common interface for testing the connection to a DataSource.
20
19
  */
21
- export interface ConnectionTester<TConfig extends DataSourceConfig> {
20
+ export interface ConnectionTester<TConfig extends types.configFile.DataSourceConfig> {
22
21
  /**
23
22
  * Confirm if a connection can be established to the datasource for the provided datasource configuration
24
23
  * @param config
@@ -35,7 +34,7 @@ export interface ReplicationModuleOptions extends modules.AbstractModuleOptions
35
34
  * A replication module describes all the functionality that PowerSync requires to
36
35
  * replicate data from a DataSource. Whenever a new data source is added to powersync this class should be extended.
37
36
  */
38
- export abstract class ReplicationModule<TConfig extends DataSourceConfig>
37
+ export abstract class ReplicationModule<TConfig extends types.configFile.DataSourceConfig>
39
38
  extends modules.AbstractModule
40
39
  implements ConnectionTester<TConfig>
41
40
  {
@@ -11,6 +11,7 @@ export type RouterSetupResponse = {
11
11
 
12
12
  export type RouterEngineRoutes = {
13
13
  api_routes: RouteDefinition[];
14
+ checkpointing_routes: RouteDefinition[];
14
15
  stream_routes: RouteDefinition[];
15
16
  socket_routes: SocketRouteGenerator[];
16
17
  };
@@ -42,6 +43,7 @@ export class RouterEngine {
42
43
 
43
44
  this.routes = {
44
45
  api_routes: [],
46
+ checkpointing_routes: [],
45
47
  stream_routes: [],
46
48
  socket_routes: []
47
49
  };
@@ -49,13 +51,17 @@ export class RouterEngine {
49
51
 
50
52
  public registerRoutes(routes: Partial<RouterEngineRoutes>) {
51
53
  this.routes.api_routes.push(...(routes.api_routes ?? []));
54
+ this.routes.checkpointing_routes.push(...(routes.checkpointing_routes ?? []));
52
55
  this.routes.stream_routes.push(...(routes.stream_routes ?? []));
53
56
  this.routes.socket_routes.push(...(routes.socket_routes ?? []));
54
57
  }
55
58
 
56
59
  public get hasRoutes() {
57
60
  return (
58
- this.routes.api_routes.length > 0 || this.routes.stream_routes.length > 0 || this.routes.socket_routes.length > 0
61
+ this.routes.api_routes.length > 0 ||
62
+ this.routes.checkpointing_routes.length > 0 ||
63
+ this.routes.stream_routes.length > 0 ||
64
+ this.routes.socket_routes.length > 0
59
65
  );
60
66
  }
61
67