@powersync/service-core 0.0.0-dev-20260601140105 → 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
package/src/util/utils.ts
CHANGED
|
@@ -223,7 +223,7 @@ export function isCompleteRow<V>(
|
|
|
223
223
|
* All other operations are replaced with a single CLEAR operation,
|
|
224
224
|
* summing their checksums, and using a 0 as an op_id.
|
|
225
225
|
*
|
|
226
|
-
* This is the function $r(B)$, as described in /docs/bucket-properties.md.
|
|
226
|
+
* This is the function $r(B)$, as described in /docs/storage/bucket-properties.md.
|
|
227
227
|
*
|
|
228
228
|
* Used for tests.
|
|
229
229
|
*/
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { ErrorCode, ServiceAssertionError, ServiceError } from '@powersync/lib-services-framework';
|
|
2
|
+
import { RouteAPI } from '../api/RouteAPI.js';
|
|
3
|
+
import {
|
|
4
|
+
BucketStorageFactory,
|
|
5
|
+
CreateManagedWriteCheckpointsResult,
|
|
6
|
+
ManagedWriteCheckpointOptions,
|
|
7
|
+
SyncRulesBucketStorage
|
|
8
|
+
} from '../storage/storage-index.js';
|
|
9
|
+
|
|
10
|
+
// Keep up to three source-head/storage batches executing concurrently under load.
|
|
11
|
+
// There is intentionally no explicit batch-size cap here: the HTTP request queue
|
|
12
|
+
// already bounds how many requests can be waiting in this process.
|
|
13
|
+
// Smaller values here have better efficiency, while larger numbers here may give slight improvements in latency.
|
|
14
|
+
// We want to limit the number of database connections in use for write checkpoints, so we keep the numbers low here.
|
|
15
|
+
const MAX_IN_FLIGHT_WRITE_CHECKPOINT_BATCHES = 3;
|
|
16
|
+
|
|
17
|
+
export interface CreateWriteCheckpointResult {
|
|
18
|
+
writeCheckpoint: string;
|
|
19
|
+
replicationHead: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface QueuedWriteCheckpoint {
|
|
23
|
+
userId: string;
|
|
24
|
+
checkpointRequestId: bigint | undefined;
|
|
25
|
+
resolvers: PromiseWithResolvers<CreateWriteCheckpointResult>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class WriteCheckpointBatcher {
|
|
29
|
+
private pending: QueuedWriteCheckpoint[] = [];
|
|
30
|
+
private inFlight = 0;
|
|
31
|
+
private scheduledPump: NodeJS.Timeout | undefined;
|
|
32
|
+
|
|
33
|
+
constructor(
|
|
34
|
+
private readonly getAPI: () => RouteAPI,
|
|
35
|
+
private readonly getStorage: () => BucketStorageFactory
|
|
36
|
+
) {}
|
|
37
|
+
|
|
38
|
+
enqueue(userId: string, checkpointRequestId?: bigint): Promise<CreateWriteCheckpointResult> {
|
|
39
|
+
const resolvers = Promise.withResolvers<CreateWriteCheckpointResult>();
|
|
40
|
+
this.pending.push({ userId, checkpointRequestId, resolvers });
|
|
41
|
+
this.schedulePump();
|
|
42
|
+
return resolvers.promise;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private schedulePump() {
|
|
46
|
+
if (this.scheduledPump != null) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Delay dispatch by one timer turn so requests arriving together can share
|
|
51
|
+
// one source head and one storage write batch.
|
|
52
|
+
// While normally we wouldn't have http requests arriving at the exact same time, this is relevant when
|
|
53
|
+
// requests are queued by fastify: All current requests are typically batched together, and finish at the
|
|
54
|
+
// same time. Then we get many requests from the queue arriving at the same time. Without this delayed dispatch,
|
|
55
|
+
// the first request would form its own batch, and the rest will then wait for a new batch to become available.
|
|
56
|
+
// The delayed dispatch allow all those requests to be batched together.
|
|
57
|
+
this.scheduledPump = setTimeout(() => {
|
|
58
|
+
this.scheduledPump = undefined;
|
|
59
|
+
this.pump();
|
|
60
|
+
}, 0);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private pump() {
|
|
64
|
+
while (this.inFlight < MAX_IN_FLIGHT_WRITE_CHECKPOINT_BATCHES && this.pending.length > 0) {
|
|
65
|
+
const batch = this.pending;
|
|
66
|
+
this.pending = [];
|
|
67
|
+
this.inFlight++;
|
|
68
|
+
|
|
69
|
+
void this.executeBatch(batch).finally(() => {
|
|
70
|
+
this.inFlight--;
|
|
71
|
+
this.schedulePump();
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private async executeBatch(batch: QueuedWriteCheckpoint[]) {
|
|
77
|
+
try {
|
|
78
|
+
const syncBucketStorage = (await this.getStorage().getActiveSyncConfig())?.storage;
|
|
79
|
+
if (!syncBucketStorage) {
|
|
80
|
+
throw new ServiceError(ErrorCode.PSYNC_S2302, `Cannot create Write Checkpoint since no sync config is active.`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// The source adapter reads the head, hands it to this callback to persist the
|
|
84
|
+
// write-checkpoint mapping, then forces a source marker only when storage
|
|
85
|
+
// reports an advance. Keeping the marker inside the callback means it is
|
|
86
|
+
// causally ordered after the head within a single source session.
|
|
87
|
+
const { writeCheckpoints, currentCheckpoint } = await this.getAPI().createReplicationHead(
|
|
88
|
+
async (currentCheckpoint) => {
|
|
89
|
+
const { writeCheckpoints, shouldAdvance } = await this.createBatchWriteCheckpoints(
|
|
90
|
+
syncBucketStorage,
|
|
91
|
+
batch,
|
|
92
|
+
currentCheckpoint
|
|
93
|
+
);
|
|
94
|
+
return { response: { writeCheckpoints, currentCheckpoint }, shouldAdvance };
|
|
95
|
+
}
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
const results = batch.map((request) => {
|
|
99
|
+
const writeCheckpoint = writeCheckpoints.get(request.userId);
|
|
100
|
+
if (writeCheckpoint == null) {
|
|
101
|
+
throw new ServiceAssertionError(
|
|
102
|
+
`Write checkpoint storage did not return a checkpoint for user ${request.userId}`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return { request, writeCheckpoint };
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
for (const { request, writeCheckpoint } of results) {
|
|
110
|
+
request.resolvers.resolve({
|
|
111
|
+
writeCheckpoint: String(writeCheckpoint),
|
|
112
|
+
replicationHead: currentCheckpoint
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
} catch (error) {
|
|
116
|
+
// Do not retry here. The route should pass failures through so clients can
|
|
117
|
+
// apply their normal write-checkpoint retry policy.
|
|
118
|
+
for (const request of batch) {
|
|
119
|
+
request.resolvers.reject(error);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private async createBatchWriteCheckpoints(
|
|
125
|
+
syncBucketStorage: SyncRulesBucketStorage,
|
|
126
|
+
batch: QueuedWriteCheckpoint[],
|
|
127
|
+
currentCheckpoint: string
|
|
128
|
+
): Promise<CreateManagedWriteCheckpointsResult> {
|
|
129
|
+
return syncBucketStorage.createManagedWriteCheckpoints(
|
|
130
|
+
batch.map((request) => {
|
|
131
|
+
const checkpoint: ManagedWriteCheckpointOptions = {
|
|
132
|
+
user_id: request.userId,
|
|
133
|
+
heads: { '1': currentCheckpoint }
|
|
134
|
+
};
|
|
135
|
+
if (request.checkpointRequestId != null) {
|
|
136
|
+
checkpoint.checkpoint_request_id = request.checkpointRequestId;
|
|
137
|
+
}
|
|
138
|
+
return checkpoint;
|
|
139
|
+
})
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { AbstractReplicationJob } from '@/replication/AbstractReplicationJob.js';
|
|
2
|
+
import { AbstractReplicator, AbstractReplicatorOptions, CreateJobOptions } from '@/replication/AbstractReplicator.js';
|
|
3
|
+
import { PersistedReplicationStream } from '@/storage/PersistedReplicationStream.js';
|
|
4
|
+
import { SyncRulesBucketStorage } from '@/storage/SyncRulesBucketStorage.js';
|
|
5
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
6
|
+
|
|
7
|
+
class TestReplicator extends AbstractReplicator {
|
|
8
|
+
constructor(
|
|
9
|
+
private readonly cleanup: (storage: SyncRulesBucketStorage) => Promise<void>,
|
|
10
|
+
options: AbstractReplicatorOptions = {
|
|
11
|
+
id: 'test',
|
|
12
|
+
storageEngine: {} as AbstractReplicatorOptions['storageEngine'],
|
|
13
|
+
metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
|
|
14
|
+
syncRuleProvider: {} as AbstractReplicatorOptions['syncRuleProvider'],
|
|
15
|
+
rateLimiter: {} as AbstractReplicatorOptions['rateLimiter']
|
|
16
|
+
}
|
|
17
|
+
) {
|
|
18
|
+
super(options);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
createJob(_options: CreateJobOptions): AbstractReplicationJob {
|
|
22
|
+
throw new Error('Not implemented');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
cleanUp(storage: SyncRulesBucketStorage): Promise<void> {
|
|
26
|
+
return this.cleanup(storage);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async testConnection() {
|
|
30
|
+
return { connectionDescription: 'test' };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
terminateStoppedStream(
|
|
34
|
+
replicationStream: PersistedReplicationStream,
|
|
35
|
+
syncRuleStorage: SyncRulesBucketStorage
|
|
36
|
+
): Promise<void> {
|
|
37
|
+
return this.terminateStoppedReplicationStream(replicationStream, syncRuleStorage);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
addClearingJob(replicationStreamId: number, promise: Promise<void>): void {
|
|
41
|
+
this.clearingJobs.set(replicationStreamId, promise);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe('AbstractReplicator stopped stream cleanup', () => {
|
|
46
|
+
it('holds the replication stream lock across source and storage cleanup', async () => {
|
|
47
|
+
const calls: string[] = [];
|
|
48
|
+
const release = vi.fn(async () => {
|
|
49
|
+
calls.push('release');
|
|
50
|
+
});
|
|
51
|
+
const replicationStream = {
|
|
52
|
+
async lock() {
|
|
53
|
+
calls.push('lock');
|
|
54
|
+
return { sync_rules_id: 1, release };
|
|
55
|
+
}
|
|
56
|
+
} as unknown as PersistedReplicationStream;
|
|
57
|
+
const syncRuleStorage = {
|
|
58
|
+
logger: { info: vi.fn() },
|
|
59
|
+
async terminate() {
|
|
60
|
+
calls.push('terminate');
|
|
61
|
+
}
|
|
62
|
+
} as unknown as SyncRulesBucketStorage;
|
|
63
|
+
const replicator = new TestReplicator(async () => {
|
|
64
|
+
calls.push('cleanup');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
await replicator.terminateStoppedStream(replicationStream, syncRuleStorage);
|
|
68
|
+
|
|
69
|
+
expect(calls).toEqual(['lock', 'cleanup', 'terminate', 'release']);
|
|
70
|
+
expect(release).toHaveBeenCalledOnce();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('releases the replication stream lock when cleanup fails', async () => {
|
|
74
|
+
const cleanupError = new Error('cleanup failed');
|
|
75
|
+
const release = vi.fn(async () => {});
|
|
76
|
+
const replicationStream = {
|
|
77
|
+
async lock() {
|
|
78
|
+
return { sync_rules_id: 1, release };
|
|
79
|
+
}
|
|
80
|
+
} as unknown as PersistedReplicationStream;
|
|
81
|
+
const terminate = vi.fn(async () => {});
|
|
82
|
+
const syncRuleStorage = {
|
|
83
|
+
logger: { info: vi.fn() },
|
|
84
|
+
terminate
|
|
85
|
+
} as unknown as SyncRulesBucketStorage;
|
|
86
|
+
const replicator = new TestReplicator(async () => {
|
|
87
|
+
throw cleanupError;
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
await expect(replicator.terminateStoppedStream(replicationStream, syncRuleStorage)).rejects.toBe(cleanupError);
|
|
91
|
+
|
|
92
|
+
expect(terminate).not.toHaveBeenCalled();
|
|
93
|
+
expect(release).toHaveBeenCalledOnce();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('waits for stopped stream cleanup when stopping', async () => {
|
|
97
|
+
let finishCleanup: () => void;
|
|
98
|
+
const cleanup = new Promise<void>((resolve) => {
|
|
99
|
+
finishCleanup = resolve;
|
|
100
|
+
});
|
|
101
|
+
const replicator = new TestReplicator(async () => {});
|
|
102
|
+
replicator.addClearingJob(1, cleanup);
|
|
103
|
+
|
|
104
|
+
let stopped = false;
|
|
105
|
+
const stop = replicator.stop().then(() => {
|
|
106
|
+
stopped = true;
|
|
107
|
+
});
|
|
108
|
+
await Promise.resolve();
|
|
109
|
+
expect(stopped).toBe(false);
|
|
110
|
+
|
|
111
|
+
finishCleanup!();
|
|
112
|
+
await stop;
|
|
113
|
+
expect(stopped).toBe(true);
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -482,4 +482,26 @@ describe('checksum cache', function () {
|
|
|
482
482
|
expect(await cache.getChecksums(123n, [{ bucket: 'test', source: DUMMY_SOURCE }])).toEqual([TEST_123]);
|
|
483
483
|
expect(await cache.getChecksums(1234n, [{ bucket: 'test', source: DUMMY_SOURCE }])).toEqual([TEST_1234]);
|
|
484
484
|
});
|
|
485
|
+
|
|
486
|
+
it('should refresh cached checksums after the configured TTL', async function () {
|
|
487
|
+
let lookups: FetchPartialBucketChecksum[][] = [];
|
|
488
|
+
const cache = new ChecksumCache({
|
|
489
|
+
fetchChecksums: async (batch) => {
|
|
490
|
+
lookups.push(batch);
|
|
491
|
+
return fetchTestChecksums(batch);
|
|
492
|
+
},
|
|
493
|
+
ttlMs: 1
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
expect(await cache.getChecksums(123n, [{ bucket: 'test', source: DUMMY_SOURCE }])).toEqual([TEST_123]);
|
|
497
|
+
expect(await cache.getChecksums(123n, [{ bucket: 'test', source: DUMMY_SOURCE }])).toEqual([TEST_123]);
|
|
498
|
+
|
|
499
|
+
await new Promise((resolve) => setTimeout(resolve, 1001)); // Needs to be >1s
|
|
500
|
+
|
|
501
|
+
expect(await cache.getChecksums(123n, [{ bucket: 'test', source: DUMMY_SOURCE }])).toEqual([TEST_123]);
|
|
502
|
+
expect(lookups.map(removeLookupSources)).toEqual([
|
|
503
|
+
[{ bucket: 'test', end: 123n }],
|
|
504
|
+
[{ bucket: 'test', end: 123n }]
|
|
505
|
+
]);
|
|
506
|
+
});
|
|
485
507
|
});
|
package/test/src/config.test.ts
CHANGED
|
@@ -70,6 +70,108 @@ describe('Config', () => {
|
|
|
70
70
|
expect(config.api_parameters.max_buckets_per_connection).toBe(1);
|
|
71
71
|
});
|
|
72
72
|
|
|
73
|
+
it('should resolve checkpoint request retention config', {}, async () => {
|
|
74
|
+
const yamlConfig = /* yaml */ `
|
|
75
|
+
# PowerSync config
|
|
76
|
+
replication:
|
|
77
|
+
connections: []
|
|
78
|
+
storage:
|
|
79
|
+
type: mongodb
|
|
80
|
+
api:
|
|
81
|
+
parameters:
|
|
82
|
+
checkpoint_request_retention_minutes: 15
|
|
83
|
+
`;
|
|
84
|
+
|
|
85
|
+
const collector = new CompoundConfigCollector();
|
|
86
|
+
|
|
87
|
+
const config = await collector.collectConfig({
|
|
88
|
+
config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
expect(config.api_parameters.checkpoint_request_retention_minutes).toBe(15);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('should default checkpoint request retention to 60 minutes', {}, async () => {
|
|
95
|
+
const yamlConfig = /* yaml */ `
|
|
96
|
+
# PowerSync config
|
|
97
|
+
replication:
|
|
98
|
+
connections: []
|
|
99
|
+
storage:
|
|
100
|
+
type: mongodb
|
|
101
|
+
`;
|
|
102
|
+
|
|
103
|
+
const collector = new CompoundConfigCollector();
|
|
104
|
+
|
|
105
|
+
const config = await collector.collectConfig({
|
|
106
|
+
config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
expect(config.api_parameters.checkpoint_request_retention_minutes).toBe(60);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it.each([0, -1, 1.5])('should reject checkpoint request retention of %s minutes', async (retentionMinutes) => {
|
|
113
|
+
const yamlConfig = /* yaml */ `
|
|
114
|
+
# PowerSync config
|
|
115
|
+
replication:
|
|
116
|
+
connections: []
|
|
117
|
+
storage:
|
|
118
|
+
type: mongodb
|
|
119
|
+
api:
|
|
120
|
+
parameters:
|
|
121
|
+
checkpoint_request_retention_minutes: ${retentionMinutes}
|
|
122
|
+
`;
|
|
123
|
+
|
|
124
|
+
const collector = new CompoundConfigCollector();
|
|
125
|
+
|
|
126
|
+
await expect(
|
|
127
|
+
collector.collectConfig({
|
|
128
|
+
config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
|
|
129
|
+
})
|
|
130
|
+
).rejects.toThrow('api.parameters.checkpoint_request_retention_minutes must be a positive integer');
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('should resolve checksum cache TTL from API parameters', async () => {
|
|
134
|
+
const yamlConfig = /* yaml */ `
|
|
135
|
+
# PowerSync config
|
|
136
|
+
replication:
|
|
137
|
+
connections: []
|
|
138
|
+
storage:
|
|
139
|
+
type: mongodb
|
|
140
|
+
api:
|
|
141
|
+
parameters:
|
|
142
|
+
bucket_count_cache_ttl_minutes: 15
|
|
143
|
+
`;
|
|
144
|
+
|
|
145
|
+
const collector = new CompoundConfigCollector();
|
|
146
|
+
|
|
147
|
+
const config = await collector.collectConfig({
|
|
148
|
+
config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
expect(config.api_parameters.bucket_count_cache_ttl_minutes).toBe(15);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('should reject fractional checksum cache TTL minutes', async () => {
|
|
155
|
+
const yamlConfig = /* yaml */ `
|
|
156
|
+
# PowerSync config
|
|
157
|
+
replication:
|
|
158
|
+
connections: []
|
|
159
|
+
storage:
|
|
160
|
+
type: mongodb
|
|
161
|
+
api:
|
|
162
|
+
parameters:
|
|
163
|
+
bucket_count_cache_ttl_minutes: 1.5
|
|
164
|
+
`;
|
|
165
|
+
|
|
166
|
+
const collector = new CompoundConfigCollector();
|
|
167
|
+
|
|
168
|
+
await expect(
|
|
169
|
+
collector.collectConfig({
|
|
170
|
+
config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
|
|
171
|
+
})
|
|
172
|
+
).rejects.toThrow('api.parameters.bucket_count_cache_ttl_minutes must be a positive integer');
|
|
173
|
+
});
|
|
174
|
+
|
|
73
175
|
it('should throw YAML validation error for invalid base64 config', {}, async () => {
|
|
74
176
|
const yamlConfig = /* yaml */ `
|
|
75
177
|
# PowerSync config
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DiagnosticsOptions, getSyncRulesStatus } from '@/api/diagnostics.js';
|
|
2
2
|
import { RouteAPI, SlotWalBudgetInfo } from '@/api/RouteAPI.js';
|
|
3
|
-
import {
|
|
3
|
+
import { ParsedSyncConfigSet, storage } from '@/index.js';
|
|
4
4
|
import { SqlSyncRules } from '@powersync/service-sync-rules';
|
|
5
5
|
import { describe, expect, test } from 'vitest';
|
|
6
6
|
|
|
@@ -13,53 +13,57 @@ bucket_definitions:
|
|
|
13
13
|
- SELECT id FROM test_table
|
|
14
14
|
`;
|
|
15
15
|
|
|
16
|
-
function makeSyncRulesContent(overrides?: {
|
|
16
|
+
function makeSyncRulesContent(overrides?: {
|
|
17
|
+
slot_name?: string;
|
|
18
|
+
status?: storage.PersistedSyncConfigStatus;
|
|
19
|
+
}): storage.PersistedSyncConfigContent {
|
|
17
20
|
// We don't implement the entire interface correctly here - just enough to test the diagnostics logic.
|
|
18
|
-
|
|
19
|
-
id: 1,
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
compiled_plan: null,
|
|
23
|
-
active: true,
|
|
24
|
-
storageVersion: 1,
|
|
21
|
+
const status = overrides?.status ?? {
|
|
22
|
+
id: '1',
|
|
23
|
+
replicationStreamId: 1,
|
|
24
|
+
state: storage.SyncRuleState.ACTIVE,
|
|
25
25
|
last_checkpoint_lsn: 'some_lsn',
|
|
26
26
|
last_fatal_error: null,
|
|
27
27
|
last_fatal_error_ts: null,
|
|
28
28
|
last_keepalive_ts: new Date(),
|
|
29
|
-
last_checkpoint_ts: new Date()
|
|
29
|
+
last_checkpoint_ts: new Date()
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
replicationStreamId: 1,
|
|
34
|
+
syncConfigId: null,
|
|
35
|
+
replicationStreamName: overrides?.slot_name ?? 'test_slot',
|
|
36
|
+
sync_rules_content: MINIMAL_SYNC_RULES,
|
|
37
|
+
compiled_plan: null,
|
|
38
|
+
storageVersion: 1,
|
|
39
|
+
syncConfigState: status.state,
|
|
30
40
|
parsed(options?: any) {
|
|
31
41
|
const syncRules = SqlSyncRules.fromYaml(MINIMAL_SYNC_RULES, {
|
|
32
42
|
...options,
|
|
33
43
|
defaultSchema: 'public'
|
|
34
44
|
});
|
|
35
45
|
return {
|
|
36
|
-
|
|
37
|
-
} as
|
|
38
|
-
},
|
|
39
|
-
lock() {
|
|
40
|
-
throw new Error('Not implemented in mock');
|
|
46
|
+
syncConfigs: [syncRules]
|
|
47
|
+
} as ParsedSyncConfigSet;
|
|
41
48
|
},
|
|
42
|
-
current_lock: null,
|
|
43
49
|
logger: null as any,
|
|
44
50
|
asUpdateOptions: null as any,
|
|
45
|
-
getStorageConfig: null as any
|
|
46
|
-
|
|
51
|
+
getStorageConfig: null as any,
|
|
52
|
+
async getSyncConfigStatus() {
|
|
53
|
+
return status;
|
|
54
|
+
}
|
|
55
|
+
} as storage.PersistedSyncConfigContent;
|
|
47
56
|
}
|
|
48
57
|
|
|
49
|
-
function
|
|
58
|
+
function makeSystemStorage() {
|
|
50
59
|
return {
|
|
51
|
-
|
|
60
|
+
async getStatus() {
|
|
52
61
|
return {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
snapshot_done: true,
|
|
56
|
-
checkpoint_lsn: 'some_lsn',
|
|
57
|
-
active: true
|
|
58
|
-
};
|
|
59
|
-
}
|
|
62
|
+
snapshotDone: true,
|
|
63
|
+
resumeLsn: 'some_lsn'
|
|
60
64
|
};
|
|
61
65
|
}
|
|
62
|
-
} as
|
|
66
|
+
} as storage.SyncRulesBucketStorage;
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
function makeRouteAPI(walBudget?: SlotWalBudgetInfo | undefined): RouteAPI {
|
|
@@ -92,7 +96,8 @@ function makeRouteAPI(walBudget?: SlotWalBudgetInfo | undefined): RouteAPI {
|
|
|
92
96
|
const OPTIONS: DiagnosticsOptions = {
|
|
93
97
|
live_status: true,
|
|
94
98
|
check_connection: true,
|
|
95
|
-
include_content: false
|
|
99
|
+
include_content: false,
|
|
100
|
+
active: true
|
|
96
101
|
};
|
|
97
102
|
|
|
98
103
|
describe('getSyncRulesStatus WAL budget warnings', () => {
|
|
@@ -102,7 +107,7 @@ describe('getSyncRulesStatus WAL budget warnings', () => {
|
|
|
102
107
|
safe_wal_size: 4 * GB,
|
|
103
108
|
max_slot_wal_keep_size: 10 * GB
|
|
104
109
|
});
|
|
105
|
-
const result = await getSyncRulesStatus(
|
|
110
|
+
const result = await getSyncRulesStatus(api, makeSyncRulesContent(), OPTIONS, makeSystemStorage());
|
|
106
111
|
const walWarnings = result!.errors.filter((e) => e.message.includes('WAL budget'));
|
|
107
112
|
expect(walWarnings).toHaveLength(1);
|
|
108
113
|
expect(walWarnings[0].level).toBe('warning');
|
|
@@ -115,7 +120,7 @@ describe('getSyncRulesStatus WAL budget warnings', () => {
|
|
|
115
120
|
safe_wal_size: 8 * GB,
|
|
116
121
|
max_slot_wal_keep_size: 10 * GB
|
|
117
122
|
});
|
|
118
|
-
const result = await getSyncRulesStatus(
|
|
123
|
+
const result = await getSyncRulesStatus(api, makeSyncRulesContent(), OPTIONS, makeSystemStorage());
|
|
119
124
|
const walWarnings = result!.errors.filter((e) => e.message.includes('WAL budget'));
|
|
120
125
|
expect(walWarnings).toHaveLength(0);
|
|
121
126
|
});
|
|
@@ -126,7 +131,7 @@ describe('getSyncRulesStatus WAL budget warnings', () => {
|
|
|
126
131
|
safe_wal_size: -2.4 * GB,
|
|
127
132
|
max_slot_wal_keep_size: 1 * 1024 * 1024 // 1MB
|
|
128
133
|
});
|
|
129
|
-
const result = await getSyncRulesStatus(
|
|
134
|
+
const result = await getSyncRulesStatus(api, makeSyncRulesContent(), OPTIONS, makeSystemStorage());
|
|
130
135
|
const walWarnings = result!.errors.filter((e) => e.message.includes('WAL budget'));
|
|
131
136
|
expect(walWarnings).toHaveLength(1);
|
|
132
137
|
expect(walWarnings[0].message).toContain('0%');
|
|
@@ -137,7 +142,7 @@ describe('getSyncRulesStatus WAL budget warnings', () => {
|
|
|
137
142
|
const api = makeRouteAPI({
|
|
138
143
|
wal_status: 'lost'
|
|
139
144
|
});
|
|
140
|
-
const result = await getSyncRulesStatus(
|
|
145
|
+
const result = await getSyncRulesStatus(api, makeSyncRulesContent(), OPTIONS, makeSystemStorage());
|
|
141
146
|
const walErrors = result!.errors.filter(
|
|
142
147
|
(e) => e.message.includes('WAL budget') || e.message.includes('PSYNC_S1146')
|
|
143
148
|
);
|
|
@@ -146,10 +151,33 @@ describe('getSyncRulesStatus WAL budget warnings', () => {
|
|
|
146
151
|
|
|
147
152
|
test('no WAL error when getSlotWalBudget is not defined', async () => {
|
|
148
153
|
const api = makeRouteAPI();
|
|
149
|
-
const result = await getSyncRulesStatus(
|
|
154
|
+
const result = await getSyncRulesStatus(api, makeSyncRulesContent(), OPTIONS, makeSystemStorage());
|
|
150
155
|
const walErrors = result!.errors.filter(
|
|
151
156
|
(e) => e.message.includes('WAL budget') || e.message.includes('PSYNC_S1146')
|
|
152
157
|
);
|
|
153
158
|
expect(walErrors).toHaveLength(0);
|
|
154
159
|
});
|
|
160
|
+
|
|
161
|
+
test('uses sync config status for status-derived diagnostics fields', async () => {
|
|
162
|
+
const configStatus: storage.PersistedSyncConfigStatus = {
|
|
163
|
+
id: 'config-a',
|
|
164
|
+
replicationStreamId: 1,
|
|
165
|
+
state: storage.SyncRuleState.ACTIVE,
|
|
166
|
+
last_checkpoint_lsn: 'config_lsn',
|
|
167
|
+
last_fatal_error: 'config failed',
|
|
168
|
+
last_fatal_error_ts: new Date('2026-01-01T00:00:00.000Z'),
|
|
169
|
+
last_keepalive_ts: new Date('2026-01-01T00:01:00.000Z'),
|
|
170
|
+
last_checkpoint_ts: new Date('2026-01-01T00:02:00.000Z')
|
|
171
|
+
};
|
|
172
|
+
const result = await getSyncRulesStatus(
|
|
173
|
+
makeRouteAPI(),
|
|
174
|
+
makeSyncRulesContent({ status: configStatus }),
|
|
175
|
+
OPTIONS,
|
|
176
|
+
makeSystemStorage()
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
expect(result!.connections[0].last_checkpoint_ts).toBe('2026-01-01T00:02:00.000Z');
|
|
180
|
+
expect(result!.connections[0].last_keepalive_ts).toBe('2026-01-01T00:01:00.000Z');
|
|
181
|
+
expect(result!.errors.some((error) => error.message == 'config failed')).toBe(true);
|
|
182
|
+
});
|
|
155
183
|
});
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
AbstractModule,
|
|
3
|
+
loadModules,
|
|
4
|
+
ModuleManager,
|
|
5
|
+
ServiceContextContainer,
|
|
6
|
+
storage,
|
|
7
|
+
TearDownOptions
|
|
8
|
+
} from '@/index.js';
|
|
2
9
|
import { describe, expect, it } from 'vitest';
|
|
3
10
|
|
|
4
11
|
interface MockConfig {
|
|
@@ -27,6 +34,19 @@ class MockPostgresStorageModule extends AbstractModule {
|
|
|
27
34
|
async initialize(context: ServiceContextContainer): Promise<void> {}
|
|
28
35
|
async teardown(options: TearDownOptions): Promise<void> {}
|
|
29
36
|
}
|
|
37
|
+
class RecordingModule extends AbstractModule {
|
|
38
|
+
teardownOptions: TearDownOptions | undefined;
|
|
39
|
+
|
|
40
|
+
constructor(name: string) {
|
|
41
|
+
super({ name });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async initialize(context: ServiceContextContainer): Promise<void> {}
|
|
45
|
+
|
|
46
|
+
async teardown(options: TearDownOptions): Promise<void> {
|
|
47
|
+
this.teardownOptions = options;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
30
50
|
const mockLoaders = {
|
|
31
51
|
connection: {
|
|
32
52
|
mysql: async () => {
|
|
@@ -99,4 +119,16 @@ describe('module loader', () => {
|
|
|
99
119
|
|
|
100
120
|
await expect(loadModules(config as any, loaders)).rejects.toThrowError('Failed to load MySQL module');
|
|
101
121
|
});
|
|
122
|
+
|
|
123
|
+
it('passes replication streams through teardown options', async () => {
|
|
124
|
+
const module = new RecordingModule('RecordingModule');
|
|
125
|
+
const moduleManager = new ModuleManager();
|
|
126
|
+
const replicationStreams = [{ replicationStreamId: 1 }] as storage.PersistedReplicationStream[];
|
|
127
|
+
|
|
128
|
+
moduleManager.register([module]);
|
|
129
|
+
await moduleManager.tearDown({ replicationStreams, syncRules: replicationStreams });
|
|
130
|
+
|
|
131
|
+
expect(module.teardownOptions?.replicationStreams).toBe(replicationStreams);
|
|
132
|
+
expect(module.teardownOptions?.syncRules).toBe(replicationStreams);
|
|
133
|
+
});
|
|
102
134
|
});
|