@powersync/service-core 0.0.0-dev-20260803144812 → 0.0.0-dev-20260929095716
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +114 -5
- package/dist/api/diagnostics.js +7 -2
- package/dist/api/diagnostics.js.map +1 -1
- package/dist/entry/commands/compact-action.js +29 -25
- package/dist/entry/commands/compact-action.js.map +1 -1
- package/dist/entry/commands/config-command.js +1 -1
- package/dist/entry/commands/config-command.js.map +1 -1
- package/dist/metrics/metrics-interfaces.d.ts +5 -1
- package/dist/metrics/metrics-interfaces.js.map +1 -1
- package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.d.ts +36 -0
- package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js +70 -0
- package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js.map +1 -0
- package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js +6 -1
- package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js.map +1 -1
- package/dist/metrics/open-telemetry/util.js +7 -3
- package/dist/metrics/open-telemetry/util.js.map +1 -1
- package/dist/migrations/PowerSyncMigrationManager.js +2 -1
- package/dist/migrations/PowerSyncMigrationManager.js.map +1 -1
- package/dist/replication/AbstractReplicator.d.ts +5 -0
- package/dist/replication/AbstractReplicator.js +31 -13
- package/dist/replication/AbstractReplicator.js.map +1 -1
- package/dist/replication/ReplicationModule.d.ts +0 -7
- package/dist/replication/ReplicationModule.js +0 -1
- package/dist/replication/ReplicationModule.js.map +1 -1
- package/dist/routes/configure-fastify.d.ts +12 -3
- package/dist/routes/endpoints/admin.d.ts +24 -6
- package/dist/routes/endpoints/admin.js +17 -11
- package/dist/routes/endpoints/admin.js.map +1 -1
- package/dist/routes/endpoints/socket-route.js +7 -5
- package/dist/routes/endpoints/socket-route.js.map +1 -1
- package/dist/routes/endpoints/sync-rules.js +18 -10
- package/dist/routes/endpoints/sync-rules.js.map +1 -1
- package/dist/storage/BucketStorageBatch.d.ts +2 -1
- package/dist/storage/BucketStorageBatch.js.map +1 -1
- package/dist/storage/BucketStorageFactory.d.ts +49 -6
- package/dist/storage/BucketStorageFactory.js +25 -8
- package/dist/storage/BucketStorageFactory.js.map +1 -1
- package/dist/storage/PersistedReplicationStream.d.ts +2 -1
- package/dist/storage/PersistedReplicationStream.js.map +1 -1
- package/dist/storage/PersistedSyncConfigContent.d.ts +6 -4
- package/dist/storage/PersistedSyncConfigContent.js +34 -14
- package/dist/storage/PersistedSyncConfigContent.js.map +1 -1
- package/dist/storage/ReplicationEventPayload.d.ts +6 -1
- package/dist/storage/SourceEntity.d.ts +7 -2
- package/dist/storage/SourceTable.d.ts +37 -6
- package/dist/storage/SourceTable.js +42 -10
- package/dist/storage/SourceTable.js.map +1 -1
- package/dist/storage/SourceTableReconciler.d.ts +83 -0
- package/dist/storage/SourceTableReconciler.js +95 -0
- package/dist/storage/SourceTableReconciler.js.map +1 -0
- package/dist/storage/StorageEngine.d.ts +4 -0
- package/dist/storage/StorageEngine.js +7 -1
- package/dist/storage/StorageEngine.js.map +1 -1
- package/dist/storage/StorageProvider.d.ts +8 -0
- package/dist/storage/StorageVersionConfig.d.ts +4 -0
- package/dist/storage/StorageVersionConfig.js +10 -1
- package/dist/storage/StorageVersionConfig.js.map +1 -1
- package/dist/storage/SyncConfigParser.d.ts +44 -0
- package/dist/storage/SyncConfigParser.js +70 -0
- package/dist/storage/SyncConfigParser.js.map +1 -0
- package/dist/storage/SyncRulesBucketStorage.d.ts +48 -8
- package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
- package/dist/storage/WriteCheckpointAPI.d.ts +25 -3
- package/dist/storage/WriteCheckpointAPI.js.map +1 -1
- package/dist/storage/implementation/BucketDefinitionMapping.d.ts +23 -7
- package/dist/storage/implementation/BucketDefinitionMapping.js +88 -14
- package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -1
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +9 -5
- package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -1
- package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +9 -1
- package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -1
- package/dist/storage/storage-index.d.ts +2 -0
- package/dist/storage/storage-index.js +2 -0
- package/dist/storage/storage-index.js.map +1 -1
- package/dist/storage/storage-metrics.js +120 -4
- package/dist/storage/storage-metrics.js.map +1 -1
- package/dist/sync/BucketChecksumState.d.ts +2 -2
- package/dist/sync/BucketChecksumState.js +5 -4
- package/dist/sync/BucketChecksumState.js.map +1 -1
- package/dist/sync/sync.js +37 -9
- package/dist/sync/sync.js.map +1 -1
- package/dist/sync/util.d.ts +1 -1
- package/dist/sync/util.js +13 -1
- package/dist/sync/util.js.map +1 -1
- package/dist/system/ServiceContext.d.ts +20 -0
- package/dist/system/ServiceContext.js +29 -1
- package/dist/system/ServiceContext.js.map +1 -1
- package/dist/util/config/compound-config-collector.js +5 -0
- package/dist/util/config/compound-config-collector.js.map +1 -1
- package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
- package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
- package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
- package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
- package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
- package/dist/util/config/sync-rules/sync-rules-provider.js +3 -0
- package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
- package/dist/util/config/types.d.ts +1 -0
- package/dist/util/param-logging.d.ts +5 -2
- package/dist/util/param-logging.js +17 -9
- package/dist/util/param-logging.js.map +1 -1
- package/dist/util/protocol-types.d.ts +11 -11
- package/dist/util/protocol-types.js +6 -5
- package/dist/util/protocol-types.js.map +1 -1
- package/dist/util/utils.d.ts +2 -1
- package/dist/util/utils.js +16 -1
- package/dist/util/utils.js.map +1 -1
- package/package.json +6 -5
- package/src/api/diagnostics.ts +8 -2
- package/src/entry/commands/compact-action.ts +33 -25
- package/src/entry/commands/config-command.ts +1 -1
- package/src/metrics/metrics-interfaces.ts +6 -1
- package/src/metrics/open-telemetry/MetricAttributeFilteringExporter.ts +85 -0
- package/src/metrics/open-telemetry/OpenTelemetryMetricsFactory.ts +7 -2
- package/src/metrics/open-telemetry/util.ts +7 -3
- package/src/migrations/PowerSyncMigrationManager.ts +2 -1
- package/src/replication/AbstractReplicator.ts +42 -13
- package/src/replication/ReplicationModule.ts +0 -10
- package/src/routes/endpoints/admin.ts +17 -17
- package/src/routes/endpoints/socket-route.ts +9 -6
- package/src/routes/endpoints/sync-rules.ts +21 -12
- package/src/storage/BucketStorageBatch.ts +2 -1
- package/src/storage/BucketStorageFactory.ts +77 -14
- package/src/storage/PersistedReplicationStream.ts +2 -1
- package/src/storage/PersistedSyncConfigContent.ts +42 -19
- package/src/storage/ReplicationEventPayload.ts +6 -1
- package/src/storage/SourceEntity.ts +6 -2
- package/src/storage/SourceTable.ts +68 -11
- package/src/storage/SourceTableReconciler.ts +188 -0
- package/src/storage/StorageEngine.ts +10 -1
- package/src/storage/StorageProvider.ts +8 -0
- package/src/storage/StorageVersionConfig.ts +11 -1
- package/src/storage/SyncConfigParser.ts +121 -0
- package/src/storage/SyncRulesBucketStorage.ts +56 -8
- package/src/storage/WriteCheckpointAPI.ts +32 -3
- package/src/storage/implementation/BucketDefinitionMapping.ts +120 -17
- package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +14 -5
- package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +22 -5
- package/src/storage/storage-index.ts +2 -0
- package/src/storage/storage-metrics.ts +154 -8
- package/src/sync/BucketChecksumState.ts +8 -5
- package/src/sync/sync.ts +40 -11
- package/src/sync/util.ts +25 -9
- package/src/system/ServiceContext.ts +47 -1
- package/src/util/config/compound-config-collector.ts +6 -0
- package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
- package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
- package/src/util/config/sync-rules/sync-rules-provider.ts +5 -0
- package/src/util/config/types.ts +1 -0
- package/src/util/param-logging.ts +21 -14
- package/src/util/protocol-types.ts +8 -7
- package/src/util/utils.ts +15 -1
- package/test/src/AbstractReplicator.test.ts +62 -0
- package/test/src/MetricAttributeFilteringExporter.test.ts +96 -0
- package/test/src/PersistedSyncConfigContent.test.ts +154 -0
- package/test/src/SyncConfigParser.test.ts +330 -0
- package/test/src/broadcast_iterable.test.ts +26 -8
- package/test/src/config.test.ts +40 -0
- package/test/src/diagnostics.test.ts +48 -0
- package/test/src/routes/admin.test.ts +30 -2
- package/test/src/routes/mocks.ts +2 -0
- package/test/src/routes/stream.test.ts +123 -2
- package/test/src/source-table-reconciler.test.ts +244 -0
- package/test/src/storage/SourceTable.test.ts +4 -1
- package/test/src/storage-metrics.test.ts +148 -0
- package/test/src/sync/BucketChecksumState.test.ts +195 -6
- package/test/src/sync/util.test.ts +34 -0
- package/test/src/util/param-logging.test.ts +59 -0
- package/test/src/util/utils.test.ts +23 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -15,6 +15,7 @@ bucket_definitions:
|
|
|
15
15
|
|
|
16
16
|
function makeSyncRulesContent(overrides?: {
|
|
17
17
|
slot_name?: string;
|
|
18
|
+
version_label?: string;
|
|
18
19
|
status?: storage.PersistedSyncConfigStatus;
|
|
19
20
|
}): storage.PersistedSyncConfigContent {
|
|
20
21
|
// We don't implement the entire interface correctly here - just enough to test the diagnostics logic.
|
|
@@ -37,6 +38,7 @@ function makeSyncRulesContent(overrides?: {
|
|
|
37
38
|
compiled_plan: null,
|
|
38
39
|
storageVersion: 1,
|
|
39
40
|
syncConfigState: status.state,
|
|
41
|
+
version_label: overrides?.version_label,
|
|
40
42
|
parsed(options?: any) {
|
|
41
43
|
const syncRules = SqlSyncRules.fromYaml(MINIMAL_SYNC_RULES, {
|
|
42
44
|
...options,
|
|
@@ -180,4 +182,50 @@ describe('getSyncRulesStatus WAL budget warnings', () => {
|
|
|
180
182
|
expect(result!.connections[0].last_keepalive_ts).toBe('2026-01-01T00:01:00.000Z');
|
|
181
183
|
expect(result!.errors.some((error) => error.message == 'config failed')).toBe(true);
|
|
182
184
|
});
|
|
185
|
+
|
|
186
|
+
test('includes the sync config version label', async () => {
|
|
187
|
+
const result = await getSyncRulesStatus(
|
|
188
|
+
makeRouteAPI(),
|
|
189
|
+
makeSyncRulesContent({ version_label: 'v6' }),
|
|
190
|
+
OPTIONS,
|
|
191
|
+
makeSystemStorage()
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
expect(result!.version_label).toBe('v6');
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test('includes the sync config version label when parsing fails', async () => {
|
|
198
|
+
const content = makeSyncRulesContent({ version_label: 'v6' });
|
|
199
|
+
content.parsed = () => {
|
|
200
|
+
throw new Error('Invalid sync config');
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const result = await getSyncRulesStatus(makeRouteAPI(), content, OPTIONS, makeSystemStorage());
|
|
204
|
+
|
|
205
|
+
expect(result!.version_label).toBe('v6');
|
|
206
|
+
expect(result!.errors).toEqual([expect.objectContaining({ level: 'fatal', message: 'Invalid sync config' })]);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test('reports each sync config error with its source location when parsing fails', async () => {
|
|
210
|
+
const yaml = `
|
|
211
|
+
bucket_definitions:
|
|
212
|
+
global:
|
|
213
|
+
data:
|
|
214
|
+
- SELECT id FROM test_table
|
|
215
|
+
unknown_key: true
|
|
216
|
+
`;
|
|
217
|
+
const content = makeSyncRulesContent();
|
|
218
|
+
content.parsed = (options?: any) => {
|
|
219
|
+
SqlSyncRules.fromYaml(yaml, { ...options, defaultSchema: 'public', throwOnError: true });
|
|
220
|
+
throw new Error('Expected parsing to fail');
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
const result = await getSyncRulesStatus(makeRouteAPI(), content, OPTIONS, makeSystemStorage());
|
|
224
|
+
|
|
225
|
+
expect(result!.errors).toHaveLength(1);
|
|
226
|
+
const [error] = result!.errors;
|
|
227
|
+
expect(error.level).toBe('fatal');
|
|
228
|
+
expect(error.message).not.toContain('Expected parsing to fail');
|
|
229
|
+
expect(yaml.slice(error.location!.start_offset, error.location!.end_offset)).toBe('unknown_key');
|
|
230
|
+
});
|
|
183
231
|
});
|
|
@@ -34,6 +34,7 @@ describe('admin routes', () => {
|
|
|
34
34
|
syncConfigId?: string;
|
|
35
35
|
active?: boolean;
|
|
36
36
|
content?: string;
|
|
37
|
+
version_label?: string;
|
|
37
38
|
}): storage.PersistedSyncConfigContent {
|
|
38
39
|
const id = options.id ?? 1;
|
|
39
40
|
const syncConfigId = options.syncConfigId ?? String(id);
|
|
@@ -66,6 +67,7 @@ bucket_definitions:
|
|
|
66
67
|
compiled_plan: null,
|
|
67
68
|
storageVersion: storage.LEGACY_STORAGE_VERSION,
|
|
68
69
|
syncConfigState: syncConfigStatus.state,
|
|
70
|
+
version_label: options.version_label,
|
|
69
71
|
parsed(options?: any) {
|
|
70
72
|
const syncRules = SqlSyncRules.fromYaml(content.sync_rules_content, {
|
|
71
73
|
...options,
|
|
@@ -85,6 +87,28 @@ bucket_definitions:
|
|
|
85
87
|
}
|
|
86
88
|
|
|
87
89
|
describe('validate', () => {
|
|
90
|
+
it('uses the service parser and includes its diagnostics', async () => {
|
|
91
|
+
const context = makeContext();
|
|
92
|
+
context.service_context.syncConfigParser.registerParser({
|
|
93
|
+
id: 'example.validation',
|
|
94
|
+
parse({ context }) {
|
|
95
|
+
expect(context.defaultSchema).toBe('public');
|
|
96
|
+
context.reportDiagnostic({ level: 'fatal', message: 'Rejected by module validation.' });
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
const response = await validate.handler({
|
|
100
|
+
context,
|
|
101
|
+
request,
|
|
102
|
+
params: { sync_rules: 'config: { edition: 3 }\nstreams: {}\n' }
|
|
103
|
+
});
|
|
104
|
+
expect(response.errors).toContainEqual(
|
|
105
|
+
expect.objectContaining({
|
|
106
|
+
level: 'fatal',
|
|
107
|
+
message: 'Rejected by module validation.'
|
|
108
|
+
})
|
|
109
|
+
);
|
|
110
|
+
});
|
|
111
|
+
|
|
88
112
|
it('reports errors with source location', async () => {
|
|
89
113
|
const context = makeContext();
|
|
90
114
|
|
|
@@ -113,7 +137,7 @@ bucket_definitions:
|
|
|
113
137
|
|
|
114
138
|
describe('diagnostics', () => {
|
|
115
139
|
it('returns deploying config status', async () => {
|
|
116
|
-
const active = makeSyncConfigContent({ id: 1, syncConfigId: 'active-config' });
|
|
140
|
+
const active = makeSyncConfigContent({ id: 1, syncConfigId: 'active-config', version_label: 'v5' });
|
|
117
141
|
const deploying = makeSyncConfigContent({ id: 2, syncConfigId: 'deploying-config', active: false });
|
|
118
142
|
const getInstance = vi.fn(() => ({
|
|
119
143
|
async getStatus() {
|
|
@@ -144,12 +168,13 @@ bucket_definitions:
|
|
|
144
168
|
|
|
145
169
|
expect(response.deploying_sync_rules?.connections[0].slot_name).toBe('slot_2');
|
|
146
170
|
expect(response.active_sync_rules?.connections[0].slot_name).toBe('slot_1');
|
|
171
|
+
expect(response.active_sync_rules?.version_label).toBe('v5');
|
|
147
172
|
});
|
|
148
173
|
});
|
|
149
174
|
|
|
150
175
|
describe('reprocess', () => {
|
|
151
176
|
it('reprocesses the active sync config', async () => {
|
|
152
|
-
const active = makeSyncConfigContent({ id: 7, syncConfigId: 'active-config' });
|
|
177
|
+
const active = makeSyncConfigContent({ id: 7, syncConfigId: 'active-config', version_label: 'v6' });
|
|
153
178
|
const updateSyncRules = vi.fn(async () => ({
|
|
154
179
|
replicationStreamId: 8,
|
|
155
180
|
replicationStreamName: 'new_slot',
|
|
@@ -178,6 +203,9 @@ bucket_definitions:
|
|
|
178
203
|
expect(activeBucketStorage.getActiveSyncConfig).toHaveBeenCalledTimes(1);
|
|
179
204
|
expect(activeBucketStorage.getSyncConfigContent).not.toHaveBeenCalled();
|
|
180
205
|
expect(updateSyncRules).toHaveBeenCalledTimes(1);
|
|
206
|
+
expect(updateSyncRules).toHaveBeenCalledWith(
|
|
207
|
+
expect.objectContaining({ version_label: 'v6', forceNewReplicationStream: true })
|
|
208
|
+
);
|
|
181
209
|
expect(response.connections[0].slot_name).toBe('new_slot');
|
|
182
210
|
});
|
|
183
211
|
|
package/test/src/routes/mocks.ts
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
RouteAPI,
|
|
8
8
|
RouterEngine,
|
|
9
9
|
ServiceContext,
|
|
10
|
+
SqlSyncConfigParser,
|
|
10
11
|
StorageEngine,
|
|
11
12
|
SyncContext,
|
|
12
13
|
SyncRulesBucketStorage
|
|
@@ -38,6 +39,7 @@ export function mockServiceContext(storage: Partial<SyncRulesBucketStorage> | nu
|
|
|
38
39
|
});
|
|
39
40
|
createCoreAPIMetrics(metricsEngine);
|
|
40
41
|
const service_context: Partial<ServiceContext> = {
|
|
42
|
+
syncConfigParser: new SqlSyncConfigParser(),
|
|
41
43
|
syncContext: new SyncContext({ maxBuckets: 1, maxDataFetchConcurrency: 1, maxParameterQueryResults: 1 }),
|
|
42
44
|
eventsEngine: new EventsEngine(),
|
|
43
45
|
routerEngine: {
|
|
@@ -1,4 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
BasicRouterRequest,
|
|
3
|
+
CHECKPOINT_INVALIDATE_ALL,
|
|
4
|
+
Context,
|
|
5
|
+
JwtPayload,
|
|
6
|
+
RequestTracker,
|
|
7
|
+
streamResponse,
|
|
8
|
+
SyncRulesBucketStorage
|
|
9
|
+
} from '@/index.js';
|
|
2
10
|
import { logger, RouterResponse, ServiceError } from '@powersync/lib-services-framework';
|
|
3
11
|
import {
|
|
4
12
|
DEFAULT_HYDRATION_STATE,
|
|
@@ -9,7 +17,7 @@ import {
|
|
|
9
17
|
import * as sqlite from 'node:sqlite';
|
|
10
18
|
import { Readable, Writable } from 'stream';
|
|
11
19
|
import { pipeline } from 'stream/promises';
|
|
12
|
-
import { describe, expect, it } from 'vitest';
|
|
20
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
13
21
|
import winston from 'winston';
|
|
14
22
|
import { syncStreamed } from '../../../src/routes/endpoints/sync-stream.js';
|
|
15
23
|
import { DEFAULT_PARAM_LOGGING_FORMAT_OPTIONS, limitParamsForLogging } from '../../../src/util/param-logging.js';
|
|
@@ -182,6 +190,119 @@ describe('Stream Route', () => {
|
|
|
182
190
|
);
|
|
183
191
|
});
|
|
184
192
|
});
|
|
193
|
+
|
|
194
|
+
it('closes after a data fetch error while waiting for a new checkpoint', async () => {
|
|
195
|
+
// After 1,000 operations, the sync stream concurrently calls next() on the
|
|
196
|
+
// checkpoint watcher. This test then fails the next data fetch without
|
|
197
|
+
// producing another checkpoint. Before the fix, awaiting watcher.return()
|
|
198
|
+
// during cleanup queued it behind that pending next(), leaving the response
|
|
199
|
+
// open until an unrelated checkpoint was written.
|
|
200
|
+
const syncRules = SqlSyncRules.fromYaml(
|
|
201
|
+
`
|
|
202
|
+
bucket_definitions:
|
|
203
|
+
global:
|
|
204
|
+
data: []
|
|
205
|
+
`,
|
|
206
|
+
{ defaultSchema: 'public' }
|
|
207
|
+
).config.hydrate(defaultHydrationOptions);
|
|
208
|
+
|
|
209
|
+
let checkpointWatcherAborted = false;
|
|
210
|
+
let dataFetches = 0;
|
|
211
|
+
const storage = {
|
|
212
|
+
watchCheckpointChanges: async function* ({ signal }) {
|
|
213
|
+
yield {
|
|
214
|
+
base: {
|
|
215
|
+
checkpoint: 1n,
|
|
216
|
+
lsn: '1',
|
|
217
|
+
getParameterSets: async () => []
|
|
218
|
+
},
|
|
219
|
+
writeCheckpoint: null,
|
|
220
|
+
update: CHECKPOINT_INVALIDATE_ALL
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
await new Promise<void>((_resolve, reject) => {
|
|
224
|
+
// There is intentionally no next checkpoint: cleanup must abort this
|
|
225
|
+
// pending wait rather than wait for it to complete naturally.
|
|
226
|
+
signal.addEventListener(
|
|
227
|
+
'abort',
|
|
228
|
+
() => {
|
|
229
|
+
checkpointWatcherAborted = true;
|
|
230
|
+
reject(new Error('Checkpoint watcher aborted'));
|
|
231
|
+
},
|
|
232
|
+
{ once: true }
|
|
233
|
+
);
|
|
234
|
+
});
|
|
235
|
+
},
|
|
236
|
+
getChecksums: async (_checkpoint, buckets) =>
|
|
237
|
+
new Map(buckets.map(({ bucket }) => [bucket, { bucket, checksum: 1, count: 1000 }])),
|
|
238
|
+
getBucketDataBatch: async function* () {
|
|
239
|
+
if (dataFetches++ > 0) {
|
|
240
|
+
throw new Error('Simulated data fetch failure');
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
yield {
|
|
244
|
+
chunkData: {
|
|
245
|
+
bucket: 'global[]',
|
|
246
|
+
data: Array.from({ length: 1000 }, () => ({ op: 'PUT' })),
|
|
247
|
+
has_more: true,
|
|
248
|
+
after: '0',
|
|
249
|
+
next_after: '1000'
|
|
250
|
+
},
|
|
251
|
+
targetOp: null
|
|
252
|
+
};
|
|
253
|
+
yield { hasMore: true };
|
|
254
|
+
}
|
|
255
|
+
} as Partial<SyncRulesBucketStorage>;
|
|
256
|
+
const serviceContext = mockServiceContext(storage);
|
|
257
|
+
const controller = new AbortController();
|
|
258
|
+
const checkpointLogger = logger.child({});
|
|
259
|
+
const checkpointLogSpy = vi.spyOn(checkpointLogger, 'info');
|
|
260
|
+
|
|
261
|
+
const response = (async () => {
|
|
262
|
+
for await (const _line of streamResponse({
|
|
263
|
+
syncContext: serviceContext.syncContext,
|
|
264
|
+
bucketStorage: storage as SyncRulesBucketStorage,
|
|
265
|
+
syncRules,
|
|
266
|
+
params: { client_id: 'test-client', raw_data: true },
|
|
267
|
+
token: new JwtPayload({ sub: 'test-user', exp: Date.now() / 1000 + 10_000 }),
|
|
268
|
+
tracker: new RequestTracker(serviceContext.metricsEngine),
|
|
269
|
+
isEncodingAsBson: false,
|
|
270
|
+
signal: controller.signal,
|
|
271
|
+
logger: checkpointLogger
|
|
272
|
+
})) {
|
|
273
|
+
// Consume the response until the simulated data fetch error is propagated.
|
|
274
|
+
}
|
|
275
|
+
})();
|
|
276
|
+
|
|
277
|
+
let timeout: NodeJS.Timeout | undefined;
|
|
278
|
+
const outcome = await Promise.race([
|
|
279
|
+
response.then(
|
|
280
|
+
() => new Error('Sync stream unexpectedly completed'),
|
|
281
|
+
(error) => error
|
|
282
|
+
),
|
|
283
|
+
new Promise((resolve) => {
|
|
284
|
+
timeout = setTimeout(() => resolve(new Error('Sync stream did not close')), 500);
|
|
285
|
+
})
|
|
286
|
+
]);
|
|
287
|
+
clearTimeout(timeout);
|
|
288
|
+
|
|
289
|
+
// Capture this before aborting below, which would set it regardless of the stream cleanup.
|
|
290
|
+
const abortedByCleanup = checkpointWatcherAborted;
|
|
291
|
+
|
|
292
|
+
controller.abort();
|
|
293
|
+
await response.catch(() => {});
|
|
294
|
+
|
|
295
|
+
expect(outcome).toBeInstanceOf(Error);
|
|
296
|
+
expect((outcome as Error).message).toContain('Simulated data fetch failure');
|
|
297
|
+
expect(abortedByCleanup).toBe(true);
|
|
298
|
+
expect(checkpointLogSpy).toHaveBeenCalledWith('checkpoint_interrupted: 1', {
|
|
299
|
+
checkpoint: 1n,
|
|
300
|
+
user_id: 'test-user',
|
|
301
|
+
operations_synced: 1000,
|
|
302
|
+
data_synced_bytes: 0,
|
|
303
|
+
ms: expect.any(Object)
|
|
304
|
+
});
|
|
305
|
+
});
|
|
185
306
|
});
|
|
186
307
|
|
|
187
308
|
export async function drainWithTimeout(readable: Readable, ms = 2_000) {
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { SourceEntityDescriptor } from '@/storage/SourceEntity.js';
|
|
2
|
+
import { SourceTable, sourceTableIdEquals } from '@/storage/SourceTable.js';
|
|
3
|
+
import {
|
|
4
|
+
defaultSourceTableReconciler,
|
|
5
|
+
diffSourceTableUpdates,
|
|
6
|
+
materializeSourceTableResolution,
|
|
7
|
+
sourceIdentityCompatible,
|
|
8
|
+
validateSourceTableCandidateResolution
|
|
9
|
+
} from '@/storage/SourceTableReconciler.js';
|
|
10
|
+
import * as bson from 'bson';
|
|
11
|
+
import { describe, expect, it } from 'vitest';
|
|
12
|
+
|
|
13
|
+
function descriptor(overrides: Partial<SourceEntityDescriptor> = {}): SourceEntityDescriptor {
|
|
14
|
+
return {
|
|
15
|
+
connectionTag: 'default',
|
|
16
|
+
schema: 'public',
|
|
17
|
+
name: 'users',
|
|
18
|
+
objectId: 100,
|
|
19
|
+
replicaIdColumns: [{ name: 'id', type: 'int', typeId: 23 }],
|
|
20
|
+
...overrides
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function candidate(overrides: Partial<ConstructorParameters<typeof SourceTable>[0]> = {}): SourceTable {
|
|
25
|
+
return new SourceTable({
|
|
26
|
+
id: overrides.id ?? 'table-1',
|
|
27
|
+
ref: overrides.ref ?? { connectionTag: 'default', schema: 'public', name: 'users' },
|
|
28
|
+
objectId: 'objectId' in overrides ? overrides.objectId! : 100,
|
|
29
|
+
replicaIdColumns: overrides.replicaIdColumns ?? [{ name: 'id', type: 'int', typeId: 23 }],
|
|
30
|
+
snapshotComplete: overrides.snapshotComplete ?? true,
|
|
31
|
+
bucketDataSources: overrides.bucketDataSources ?? [],
|
|
32
|
+
parameterLookupSources: overrides.parameterLookupSources ?? [],
|
|
33
|
+
sourceMetadata: overrides.sourceMetadata
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
describe('sourceIdentityCompatible', () => {
|
|
38
|
+
it('matches identical identity', () => {
|
|
39
|
+
expect(sourceIdentityCompatible(descriptor(), candidate())).toBe(true);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('rejects a different object id', () => {
|
|
43
|
+
expect(sourceIdentityCompatible(descriptor({ objectId: 200 }), candidate({ objectId: 100 }))).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('rejects a different schema/name', () => {
|
|
47
|
+
expect(sourceIdentityCompatible(descriptor({ name: 'accounts' }), candidate())).toBe(false);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('rejects changed replica-id columns', () => {
|
|
51
|
+
expect(
|
|
52
|
+
sourceIdentityCompatible(
|
|
53
|
+
descriptor(),
|
|
54
|
+
candidate({ replicaIdColumns: [{ name: 'id', type: 'bigint', typeId: 20 }] })
|
|
55
|
+
)
|
|
56
|
+
).toBe(false);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('treats an undefined descriptor object id as a wildcard on object id', () => {
|
|
60
|
+
expect(sourceIdentityCompatible(descriptor({ objectId: undefined }), candidate({ objectId: 999 }))).toBe(true);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe('defaultSourceTableReconciler', () => {
|
|
65
|
+
it('returns all identity-compatible candidates and no metadata', async () => {
|
|
66
|
+
const a = candidate({ id: 'a' });
|
|
67
|
+
const b = candidate({ id: 'b', ref: { connectionTag: 'default', schema: 'public', name: 'accounts' } });
|
|
68
|
+
const resolution = await defaultSourceTableReconciler({ source: descriptor(), candidates: [a, b] });
|
|
69
|
+
expect(resolution.compatibleTables).toEqual([a]);
|
|
70
|
+
expect(resolution.incompatibleTables).toEqual([b]);
|
|
71
|
+
expect(resolution.newTableValues).toEqual({ sourceMetadata: null });
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('returns an empty set when nothing matches', async () => {
|
|
75
|
+
const resolution = await defaultSourceTableReconciler({
|
|
76
|
+
source: descriptor({ objectId: 200 }),
|
|
77
|
+
candidates: [candidate({ objectId: 100 })]
|
|
78
|
+
});
|
|
79
|
+
expect(resolution.compatibleTables).toHaveLength(0);
|
|
80
|
+
expect(resolution.incompatibleTables.map((table) => table.id)).toEqual(['table-1']);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
describe('validateSourceTableCandidateResolution', () => {
|
|
85
|
+
it('accepts an explicit compatible/incompatible partition', () => {
|
|
86
|
+
const a = candidate({ id: 'a' });
|
|
87
|
+
const b = candidate({ id: 'b' });
|
|
88
|
+
expect(() =>
|
|
89
|
+
validateSourceTableCandidateResolution([a, b], {
|
|
90
|
+
compatibleTables: [a],
|
|
91
|
+
incompatibleTables: [b],
|
|
92
|
+
newTableValues: { sourceMetadata: null }
|
|
93
|
+
})
|
|
94
|
+
).not.toThrow();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('rejects omitted, duplicate, and unknown candidates', () => {
|
|
98
|
+
const a = candidate({ id: 'a' });
|
|
99
|
+
expect(() =>
|
|
100
|
+
validateSourceTableCandidateResolution([a], {
|
|
101
|
+
compatibleTables: [],
|
|
102
|
+
incompatibleTables: [],
|
|
103
|
+
newTableValues: { sourceMetadata: null }
|
|
104
|
+
})
|
|
105
|
+
).toThrow(/exactly once/);
|
|
106
|
+
expect(() =>
|
|
107
|
+
validateSourceTableCandidateResolution([a], {
|
|
108
|
+
compatibleTables: [a],
|
|
109
|
+
incompatibleTables: [a],
|
|
110
|
+
newTableValues: { sourceMetadata: null }
|
|
111
|
+
})
|
|
112
|
+
).toThrow(/exactly once/);
|
|
113
|
+
expect(() =>
|
|
114
|
+
validateSourceTableCandidateResolution([a], {
|
|
115
|
+
compatibleTables: [a],
|
|
116
|
+
incompatibleTables: [candidate({ id: 'unknown' })],
|
|
117
|
+
newTableValues: { sourceMetadata: null }
|
|
118
|
+
})
|
|
119
|
+
).toThrow(/unknown candidate/);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe('diffSourceTableUpdates', () => {
|
|
124
|
+
function resolution(compatibleTables: SourceTable[]) {
|
|
125
|
+
return { compatibleTables, incompatibleTables: [], newTableValues: { sourceMetadata: null } };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
it('returns nothing when the reconciler returned the candidates untouched', () => {
|
|
129
|
+
const a = candidate({ id: 'a', sourceMetadata: { captureTableObjectId: 7 } });
|
|
130
|
+
expect(diffSourceTableUpdates([a], resolution([a]))).toEqual([]);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('compares by value, not by reference', () => {
|
|
134
|
+
// A new object with equal metadata should not cause a write.
|
|
135
|
+
const a = candidate({ id: 'a', sourceMetadata: { captureTableObjectId: 7 } });
|
|
136
|
+
const rebuilt = a.withSourceMetadata({ captureTableObjectId: 7 });
|
|
137
|
+
|
|
138
|
+
expect(rebuilt.sourceMetadata).not.toBe(a.sourceMetadata);
|
|
139
|
+
expect(diffSourceTableUpdates([a], resolution([rebuilt]))).toEqual([]);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it('returns changed metadata', () => {
|
|
143
|
+
const a = candidate({ id: 'a', sourceMetadata: { captureTableObjectId: 7 } });
|
|
144
|
+
expect(diffSourceTableUpdates([a], resolution([a.withSourceMetadata({ captureTableObjectId: 8 })]))).toEqual([
|
|
145
|
+
{ id: 'a', sourceMetadata: { captureTableObjectId: 8 } }
|
|
146
|
+
]);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('returns metadata added to a legacy record', () => {
|
|
150
|
+
const legacy = candidate({ id: 'a' });
|
|
151
|
+
expect(legacy.sourceMetadata).toBeNull();
|
|
152
|
+
expect(
|
|
153
|
+
diffSourceTableUpdates([legacy], resolution([legacy.withSourceMetadata({ captureTableObjectId: 7 })]))
|
|
154
|
+
).toEqual([{ id: 'a', sourceMetadata: { captureTableObjectId: 7 } }]);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('returns cleared metadata as null', () => {
|
|
158
|
+
const a = candidate({ id: 'a', sourceMetadata: { captureTableObjectId: 7 } });
|
|
159
|
+
expect(diffSourceTableUpdates([a], resolution([a.withSourceMetadata(null)]))).toEqual([
|
|
160
|
+
{ id: 'a', sourceMetadata: null }
|
|
161
|
+
]);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('materializes only source metadata from reconciler results', () => {
|
|
165
|
+
const persisted = candidate({ id: 'a', snapshotComplete: false });
|
|
166
|
+
const modified = persisted.withSourceMetadata({ captureTableObjectId: 8 });
|
|
167
|
+
modified.snapshotComplete = true;
|
|
168
|
+
modified.syncData = false;
|
|
169
|
+
|
|
170
|
+
const [materialized] = materializeSourceTableResolution([persisted], resolution([modified])).compatibleTables;
|
|
171
|
+
|
|
172
|
+
expect(materialized.sourceMetadata).toEqual({ captureTableObjectId: 8 });
|
|
173
|
+
expect(materialized.snapshotComplete).toBe(false);
|
|
174
|
+
expect(materialized.syncData).toBe(persisted.syncData);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('does not trust incompatible candidate mutations made through a cast', () => {
|
|
178
|
+
const persisted = candidate({ id: 'a', snapshotComplete: false });
|
|
179
|
+
const exposed = persisted.clone();
|
|
180
|
+
// Simulate callback code bypassing the read-only type boundary.
|
|
181
|
+
(exposed as any).snapshotComplete = true;
|
|
182
|
+
|
|
183
|
+
const materialized = materializeSourceTableResolution([persisted], {
|
|
184
|
+
compatibleTables: [],
|
|
185
|
+
incompatibleTables: [exposed],
|
|
186
|
+
newTableValues: { sourceMetadata: null }
|
|
187
|
+
}).incompatibleTables[0];
|
|
188
|
+
|
|
189
|
+
expect(exposed.snapshotComplete).toBe(true);
|
|
190
|
+
expect(materialized).toBe(persisted);
|
|
191
|
+
expect(materialized.snapshotComplete).toBe(false);
|
|
192
|
+
expect(materialized.syncData).toBe(persisted.syncData);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('only reports the candidates that changed', () => {
|
|
196
|
+
const a = candidate({ id: 'a', sourceMetadata: { captureTableObjectId: 7 } });
|
|
197
|
+
const b = candidate({ id: 'b', sourceMetadata: { captureTableObjectId: 7 } });
|
|
198
|
+
const updates = diffSourceTableUpdates([a, b], resolution([a, b.withSourceMetadata({ captureTableObjectId: 9 })]));
|
|
199
|
+
expect(updates).toEqual([{ id: 'b', sourceMetadata: { captureTableObjectId: 9 } }]);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('rejects a compatible table that was never a candidate', () => {
|
|
203
|
+
expect(() => diffSourceTableUpdates([candidate({ id: 'a' })], resolution([candidate({ id: 'ghost' })]))).toThrow(
|
|
204
|
+
/unknown candidate/
|
|
205
|
+
);
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
describe('SourceTable.clone', () => {
|
|
210
|
+
it('isolates mutable identity and metadata values', () => {
|
|
211
|
+
const persisted = candidate({ id: 'a', sourceMetadata: { captureTableObjectId: 7 } });
|
|
212
|
+
const exposed = persisted.clone();
|
|
213
|
+
|
|
214
|
+
(exposed.ref as any).name = 'changed';
|
|
215
|
+
exposed.replicaIdColumns[0].name = 'changed';
|
|
216
|
+
(exposed.sourceMetadata as any).captureTableObjectId = 8;
|
|
217
|
+
|
|
218
|
+
expect(persisted.name).toBe('users');
|
|
219
|
+
expect(persisted.replicaIdColumns[0].name).toBe('id');
|
|
220
|
+
expect(persisted.sourceMetadata).toEqual({ captureTableObjectId: 7 });
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
describe('sourceTableIdEquals', () => {
|
|
225
|
+
it('compares string ids by value', () => {
|
|
226
|
+
expect(sourceTableIdEquals('table-1', 'table-1')).toBe(true);
|
|
227
|
+
expect(sourceTableIdEquals('table-1', 'table-2')).toBe(false);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it('compares BSON ObjectIds by value', () => {
|
|
231
|
+
const id = new bson.ObjectId();
|
|
232
|
+
const copy = new bson.ObjectId(id.toHexString());
|
|
233
|
+
|
|
234
|
+
expect(id).not.toBe(copy);
|
|
235
|
+
expect(sourceTableIdEquals(id, copy)).toBe(true);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it('does not mix string and BSON ObjectId representations', () => {
|
|
239
|
+
const id = new bson.ObjectId();
|
|
240
|
+
|
|
241
|
+
expect(sourceTableIdEquals(id.toHexString(), id)).toBe(false);
|
|
242
|
+
expect(sourceTableIdEquals(id, id.toHexString())).toBe(false);
|
|
243
|
+
});
|
|
244
|
+
});
|
|
@@ -43,7 +43,8 @@ describe('SourceTable', () => {
|
|
|
43
43
|
test('clone preserves all properties including storeCurrentData', () => {
|
|
44
44
|
const table = makeTable({
|
|
45
45
|
replicaIdColumns: [{ name: 'id', type: 'int4' }],
|
|
46
|
-
snapshotComplete: false
|
|
46
|
+
snapshotComplete: false,
|
|
47
|
+
eventDefinitionIds: new Set(['event-1'])
|
|
47
48
|
});
|
|
48
49
|
|
|
49
50
|
table.syncData = false;
|
|
@@ -63,6 +64,8 @@ describe('SourceTable', () => {
|
|
|
63
64
|
expect(cloned.syncEvent).toBe(false);
|
|
64
65
|
expect(cloned.storeCurrentData).toBe(false);
|
|
65
66
|
expect(cloned.snapshotStatus).toEqual(table.snapshotStatus);
|
|
67
|
+
expect(cloned.eventDefinitionIds).toEqual(new Set(['event-1']));
|
|
68
|
+
expect(cloned.eventDefinitionIds).not.toBe(table.eventDefinitionIds);
|
|
66
69
|
});
|
|
67
70
|
});
|
|
68
71
|
|