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

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