@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.
- package/CHANGELOG.md +83 -4
- package/dist/api/RouteAPI.d.ts +42 -14
- package/dist/api/diagnostics.d.ts +12 -1
- package/dist/api/diagnostics.js +34 -22
- package/dist/api/diagnostics.js.map +1 -1
- package/dist/entry/commands/compact-action.js +5 -1
- package/dist/entry/commands/compact-action.js.map +1 -1
- package/dist/modules/AbstractModule.d.ts +6 -2
- package/dist/modules/AbstractModule.js.map +1 -1
- package/dist/replication/AbstractReplicator.d.ts +26 -7
- package/dist/replication/AbstractReplicator.js +148 -68
- package/dist/replication/AbstractReplicator.js.map +1 -1
- package/dist/replication/ReplicationModule.d.ts +3 -3
- package/dist/replication/ReplicationModule.js.map +1 -1
- package/dist/routes/RouterEngine.d.ts +1 -0
- package/dist/routes/RouterEngine.js +6 -1
- package/dist/routes/RouterEngine.js.map +1 -1
- package/dist/routes/configure-fastify.d.ts +95 -56
- package/dist/routes/configure-fastify.js +15 -2
- package/dist/routes/configure-fastify.js.map +1 -1
- package/dist/routes/endpoints/admin.d.ts +24 -24
- package/dist/routes/endpoints/admin.js +46 -35
- package/dist/routes/endpoints/admin.js.map +1 -1
- package/dist/routes/endpoints/checkpointing.d.ts +62 -0
- package/dist/routes/endpoints/checkpointing.js +65 -7
- package/dist/routes/endpoints/checkpointing.js.map +1 -1
- package/dist/routes/endpoints/socket-route.js +3 -2
- package/dist/routes/endpoints/socket-route.js.map +1 -1
- package/dist/routes/endpoints/sync-rules.js +22 -13
- package/dist/routes/endpoints/sync-rules.js.map +1 -1
- package/dist/routes/endpoints/sync-stream.js +1 -1
- package/dist/routes/endpoints/sync-stream.js.map +1 -1
- package/dist/runner/teardown.js +8 -8
- package/dist/runner/teardown.js.map +1 -1
- package/dist/storage/BucketStorageBatch.d.ts +63 -17
- package/dist/storage/BucketStorageBatch.js.map +1 -1
- package/dist/storage/BucketStorageFactory.d.ts +22 -27
- package/dist/storage/BucketStorageFactory.js +4 -18
- package/dist/storage/BucketStorageFactory.js.map +1 -1
- package/dist/storage/CheckpointChecksumInvalidatedError.d.ts +12 -0
- package/dist/storage/CheckpointChecksumInvalidatedError.js +17 -0
- package/dist/storage/CheckpointChecksumInvalidatedError.js.map +1 -0
- package/dist/storage/ChecksumCache.d.ts +11 -6
- package/dist/storage/ChecksumCache.js +5 -4
- package/dist/storage/ChecksumCache.js.map +1 -1
- package/dist/storage/ParsedSyncConfigSet.d.ts +23 -0
- package/dist/storage/ParsedSyncConfigSet.js +2 -0
- package/dist/storage/ParsedSyncConfigSet.js.map +1 -0
- package/dist/storage/PersistedReplicationStream.d.ts +32 -0
- package/dist/storage/PersistedReplicationStream.js +26 -0
- package/dist/storage/PersistedReplicationStream.js.map +1 -0
- package/dist/storage/PersistedSyncConfigContent.d.ts +63 -0
- package/dist/storage/PersistedSyncConfigContent.js +125 -0
- package/dist/storage/PersistedSyncConfigContent.js.map +1 -0
- package/dist/storage/PersistedSyncConfigStatus.d.ts +13 -0
- package/dist/storage/PersistedSyncConfigStatus.js +2 -0
- package/dist/storage/PersistedSyncConfigStatus.js.map +1 -0
- package/dist/storage/SourceEntity.d.ts +6 -0
- package/dist/storage/SourceTable.d.ts +21 -3
- package/dist/storage/SourceTable.js +26 -3
- package/dist/storage/SourceTable.js.map +1 -1
- package/dist/storage/SyncRulesBucketStorage.d.ts +119 -21
- package/dist/storage/SyncRulesBucketStorage.js +3 -0
- package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
- package/dist/storage/WriteCheckpointAPI.d.ts +60 -3
- package/dist/storage/WriteCheckpointAPI.js +33 -0
- package/dist/storage/WriteCheckpointAPI.js.map +1 -1
- package/dist/storage/implementation/BucketDefinitionMapping.d.ts +117 -0
- package/dist/storage/implementation/BucketDefinitionMapping.js +277 -0
- package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -0
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.d.ts +6 -0
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +31 -0
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -0
- package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.d.ts +17 -0
- package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +62 -0
- package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -0
- package/dist/storage/implementation/ReplicationStreamStorageIds.d.ts +15 -0
- package/dist/storage/implementation/ReplicationStreamStorageIds.js +20 -0
- package/dist/storage/implementation/ReplicationStreamStorageIds.js.map +1 -0
- package/dist/storage/storage-index.d.ts +9 -1
- package/dist/storage/storage-index.js +9 -1
- package/dist/storage/storage-index.js.map +1 -1
- package/dist/sync/BucketChecksumState.d.ts +12 -2
- package/dist/sync/BucketChecksumState.js +69 -21
- package/dist/sync/BucketChecksumState.js.map +1 -1
- package/dist/sync/RequestTracker.d.ts +7 -0
- package/dist/sync/RequestTracker.js +12 -0
- package/dist/sync/RequestTracker.js.map +1 -1
- package/dist/sync/sync.js +154 -41
- package/dist/sync/sync.js.map +1 -1
- package/dist/sync/util.d.ts +5 -0
- package/dist/sync/util.js +9 -0
- package/dist/sync/util.js.map +1 -1
- package/dist/system/ServiceContext.d.ts +2 -0
- package/dist/system/ServiceContext.js +2 -0
- package/dist/system/ServiceContext.js.map +1 -1
- package/dist/tracing/PerformanceTracer.d.ts +23 -1
- package/dist/tracing/PerformanceTracer.js +11 -0
- package/dist/tracing/PerformanceTracer.js.map +1 -1
- package/dist/util/checkpointing.d.ts +4 -8
- package/dist/util/checkpointing.js +1 -16
- package/dist/util/checkpointing.js.map +1 -1
- package/dist/util/config/compound-config-collector.js +18 -2
- package/dist/util/config/compound-config-collector.js.map +1 -1
- package/dist/util/config/defaults.d.ts +2 -0
- package/dist/util/config/defaults.js +2 -0
- package/dist/util/config/defaults.js.map +1 -1
- package/dist/util/config/types.d.ts +3 -1
- package/dist/util/lsn.d.ts +4 -0
- package/dist/util/lsn.js +10 -0
- package/dist/util/lsn.js.map +1 -1
- package/dist/util/util-index.d.ts +1 -0
- package/dist/util/util-index.js +1 -0
- package/dist/util/util-index.js.map +1 -1
- package/dist/util/utils.d.ts +1 -1
- package/dist/util/utils.js +1 -1
- package/dist/util/write-checkpoint-batcher.d.ts +19 -0
- package/dist/util/write-checkpoint-batcher.js +100 -0
- package/dist/util/write-checkpoint-batcher.js.map +1 -0
- package/package.json +6 -7
- package/src/api/RouteAPI.ts +43 -14
- package/src/api/diagnostics.ts +43 -26
- package/src/entry/commands/compact-action.ts +7 -1
- package/src/modules/AbstractModule.ts +6 -2
- package/src/replication/AbstractReplicator.ts +181 -72
- package/src/replication/ReplicationModule.ts +2 -3
- package/src/routes/RouterEngine.ts +7 -1
- package/src/routes/configure-fastify.ts +25 -2
- package/src/routes/endpoints/admin.ts +72 -50
- package/src/routes/endpoints/checkpointing.ts +79 -8
- package/src/routes/endpoints/socket-route.ts +3 -2
- package/src/routes/endpoints/sync-rules.ts +23 -13
- package/src/routes/endpoints/sync-stream.ts +1 -1
- package/src/runner/teardown.ts +8 -8
- package/src/storage/BucketStorageBatch.ts +64 -18
- package/src/storage/BucketStorageFactory.ts +30 -39
- package/src/storage/CheckpointChecksumInvalidatedError.ts +17 -0
- package/src/storage/ChecksumCache.ts +27 -14
- package/src/storage/ParsedSyncConfigSet.ts +25 -0
- package/src/storage/PersistedReplicationStream.ts +55 -0
- package/src/storage/PersistedSyncConfigContent.ts +192 -0
- package/src/storage/PersistedSyncConfigStatus.ts +14 -0
- package/src/storage/SourceEntity.ts +6 -0
- package/src/storage/SourceTable.ts +34 -3
- package/src/storage/SyncRulesBucketStorage.ts +138 -22
- package/src/storage/WriteCheckpointAPI.ts +108 -3
- package/src/storage/implementation/BucketDefinitionMapping.ts +436 -0
- package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +41 -0
- package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +109 -0
- package/src/storage/implementation/ReplicationStreamStorageIds.ts +21 -0
- package/src/storage/storage-index.ts +10 -1
- package/src/sync/BucketChecksumState.ts +103 -21
- package/src/sync/RequestTracker.ts +20 -0
- package/src/sync/sync.ts +183 -48
- package/src/sync/util.ts +12 -0
- package/src/system/ServiceContext.ts +7 -0
- package/src/tracing/PerformanceTracer.ts +41 -1
- package/src/util/checkpointing.ts +4 -22
- package/src/util/config/compound-config-collector.ts +25 -1
- package/src/util/config/defaults.ts +2 -0
- package/src/util/config/types.ts +3 -1
- package/src/util/lsn.ts +9 -0
- package/src/util/util-index.ts +1 -0
- package/src/util/utils.ts +1 -1
- package/src/util/write-checkpoint-batcher.ts +142 -0
- package/test/src/AbstractReplicator.test.ts +115 -0
- package/test/src/checksum_cache.test.ts +22 -0
- package/test/src/config.test.ts +102 -0
- package/test/src/diagnostics.test.ts +62 -34
- package/test/src/module-loader.test.ts +33 -1
- package/test/src/routes/admin.test.ts +182 -18
- package/test/src/routes/checkpointing.test.ts +54 -0
- package/test/src/routes/mocks.ts +6 -2
- package/test/src/storage/SourceTable.test.ts +89 -0
- package/test/src/sync/BucketChecksumState.test.ts +98 -12
- package/test/src/sync/util.test.ts +13 -1
- package/test/src/util/checkpointing.test.ts +249 -0
- package/tsconfig.json +1 -4
- package/tsconfig.tsbuildinfo +1 -1
- package/dist/storage/PersistedSyncRulesContent.d.ts +0 -59
- package/dist/storage/PersistedSyncRulesContent.js +0 -100
- package/dist/storage/PersistedSyncRulesContent.js.map +0 -1
- 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 {
|
|
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
|
-
|
|
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
|
|
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
|
|
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<
|
|
51
|
+
private replicationJobs = new Map<string, T>();
|
|
45
52
|
|
|
46
53
|
/**
|
|
47
|
-
* Map of
|
|
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
|
|
50
|
-
* use the Promise value.
|
|
56
|
+
* We primarily do this to keep track of what we're currently clearing.
|
|
51
57
|
*/
|
|
52
|
-
|
|
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
|
|
146
|
+
const loadedSyncConfig = await this.syncRuleProvider.get();
|
|
135
147
|
|
|
136
148
|
let configuredLock: storage.ReplicationLock | undefined = undefined;
|
|
137
|
-
if (
|
|
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(
|
|
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({
|
|
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
|
-
|
|
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?: {
|
|
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?.
|
|
215
|
+
let configuredLock = options?.configuredLock;
|
|
216
|
+
let replicationJobStarted = false;
|
|
190
217
|
|
|
191
|
-
const existingJobs = new Map<
|
|
192
|
-
const
|
|
193
|
-
const newJobs = new Map<
|
|
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
|
|
196
|
-
const
|
|
197
|
-
|
|
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(
|
|
203
|
-
newJobs.set(
|
|
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(
|
|
244
|
+
existingJobs.delete(jobId);
|
|
208
245
|
} else {
|
|
209
246
|
// New sync config was found (or resume after restart)
|
|
210
|
-
|
|
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
|
-
|
|
247
|
-
|
|
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.
|
|
263
|
-
for (let
|
|
264
|
-
if (this.clearingJobs.has(
|
|
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(
|
|
273
|
-
const promise = this.
|
|
314
|
+
const syncRuleStorage = this.storage.getInstance(replicationStream, { skipLifecycleHooks: true });
|
|
315
|
+
const promise = this.terminateStoppedReplicationStream(replicationStream, syncRuleStorage)
|
|
274
316
|
.catch((e) => {
|
|
275
|
-
|
|
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(
|
|
328
|
+
this.clearingJobs.delete(replicationStream.replicationStreamId);
|
|
279
329
|
});
|
|
280
|
-
this.clearingJobs.set(
|
|
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 ||
|
|
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, ...
|
|
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(
|