@powersync/service-core 0.0.0-dev-20261007110800 → 0.0.0-dev-20261015132441

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.
@@ -73,18 +73,8 @@ export const deploySyncRules = routeDefinition({
73
73
  }
74
74
 
75
75
  logSyncConfigErrors(syncConfig);
76
-
77
- try {
78
- // Validate if the current sources support the configuration specified in the Sync Config
79
- await assertSourceCapabilities(service_context.routerEngine.getAPI(), syncConfig.config);
80
- } catch (error) {
81
- throw new errors.ServiceError({
82
- status: 422,
83
- code: ErrorCode.PSYNC_R0001,
84
- description: 'Source capability validation failed',
85
- details: error.message
86
- });
87
- }
76
+ // Validate if the current sources support the configuration specified in the sync config
77
+ await assertSourceCapabilities(service_context.routerEngine.getAPI(), syncConfig.config);
88
78
 
89
79
  const sync_rules = await storageEngine.activeBucketStorage.updateSyncRules(updateSyncRulesFromConfig(syncConfig));
90
80
 
@@ -232,7 +222,7 @@ async function debugSyncRules(apiHandler: RouteAPI, sync_rules: string) {
232
222
  schema: undefined
233
223
  });
234
224
  const errors: string[] = [];
235
- const warnings: string[] = [];
225
+ const warnings = rules.errors.filter((error) => error.type === 'warning').map((error) => error.message);
236
226
  const recordError = (error: any) => {
237
227
  errors.push(...(error instanceof SyncRulesErrors ? error.errors.map((e) => e.message) : [error.message]));
238
228
  };
@@ -10,6 +10,7 @@ import {
10
10
  HydrationState,
11
11
  nodeSqlite,
12
12
  PrecompiledSyncConfig,
13
+ SourceConnectionMap,
13
14
  SqlSyncRules,
14
15
  SyncConfigWithErrors,
15
16
  versionedHydrationState,
@@ -205,4 +206,5 @@ export type PersistedSyncConfigId = string;
205
206
 
206
207
  export interface ParseSyncConfigOptions {
207
208
  defaultSchema: string;
209
+ connections?: SourceConnectionMap;
208
210
  }
@@ -1,10 +1,10 @@
1
1
  import type { RouteAPI } from '@/api/RouteAPI.js';
2
- import { assertSourceCapabilities, validateNoMongoFilterExpressions } from '@/api/source-capabilities.js';
2
+ import { assertSourceCapabilities } from '@/api/source-capabilities.js';
3
3
  import { AbstractReplicationJob } from '@/replication/AbstractReplicationJob.js';
4
4
  import { AbstractReplicator, AbstractReplicatorOptions, CreateJobOptions } from '@/replication/AbstractReplicator.js';
5
5
  import { PersistedReplicationStream } from '@/storage/PersistedReplicationStream.js';
6
+ import type { ReplicationLock } from '@/storage/ReplicationLock.js';
6
7
  import { SyncRulesBucketStorage } from '@/storage/SyncRulesBucketStorage.js';
7
- import type { SyncConfig } from '@powersync/service-sync-rules';
8
8
  import { describe, expect, it, vi } from 'vitest';
9
9
 
10
10
  class TestReplicator extends AbstractReplicator {
@@ -55,6 +55,14 @@ class TestReplicator extends AbstractReplicator {
55
55
  await (this as any).runLoop();
56
56
  }
57
57
 
58
+ async refreshForTest(configuredLock?: ReplicationLock): Promise<{ replicationJobStarted: boolean }> {
59
+ (this as any).abortController = new AbortController();
60
+ return (this as any).refresh({
61
+ configuredLock,
62
+ loadedVersionLabel: this.syncRuleProvider.versionLabel
63
+ });
64
+ }
65
+
58
66
  shouldHandleStreamForTest(
59
67
  replicationStream: PersistedReplicationStream,
60
68
  loadedSyncRules: string | undefined,
@@ -65,9 +73,9 @@ class TestReplicator extends AbstractReplicator {
65
73
  }
66
74
 
67
75
  describe('AbstractReplicator startup sync config', () => {
68
- it.each([true, false])('rejects unsupported file-loaded filters with exit_on_error=%s', async (exitOnError) => {
76
+ it.each([true, false])('respects exit_on_error=%s for unsupported file-loaded filters', async (exitOnError) => {
69
77
  const yaml = /* yaml */ `
70
- # Sync config fixture.
78
+ # sync config fixture.
71
79
  config:
72
80
  edition: 3
73
81
  source_table_options:
@@ -77,36 +85,43 @@ describe('AbstractReplicator startup sync config', () => {
77
85
  orders:
78
86
  query: SELECT * FROM orders
79
87
  `;
80
- const configureSyncRules = vi.fn(async () => ({ updated: false }));
88
+ const configureSyncRules = vi.fn(
89
+ async (_options: import('@/storage/BucketStorageFactory.js').UpdateSyncRulesOptions) => ({ updated: false })
90
+ );
81
91
  const replicator = new TestReplicator(async () => {}, {
82
92
  id: 'test',
83
93
  storageEngine: {
84
94
  activeBucketStorage: { configureSyncRules }
85
95
  } as unknown as AbstractReplicatorOptions['storageEngine'],
96
+ configuration: { connections: [{ type: 'postgresql' }] },
86
97
  syncRuleProvider: { get: async () => yaml, exitOnError, versionLabel: undefined },
87
98
  metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
88
99
  rateLimiter: {} as AbstractReplicatorOptions['rateLimiter']
89
100
  });
90
- replicator.registerSourceCapabilitiesAssertion((config) =>
91
- assertSourceCapabilities(
92
- {
93
- async validateSourceCapabilities(config: SyncConfig) {
94
- return validateNoMongoFilterExpressions(config, 'default');
95
- }
96
- } as unknown as RouteAPI,
97
- config
98
- )
99
- );
100
-
101
- await expect(replicator.runStartupForTest()).rejects.toThrow('only supported by MongoDB sources');
102
- expect(configureSyncRules).not.toHaveBeenCalled();
101
+ if (exitOnError) {
102
+ await expect(replicator.runStartupForTest()).rejects.toThrow('only supported by MongoDB sources');
103
+ expect(configureSyncRules).not.toHaveBeenCalled();
104
+ } else {
105
+ await expect(replicator.runStartupForTest()).resolves.toBeUndefined();
106
+ expect(configureSyncRules).toHaveBeenCalledOnce();
107
+ expect(configureSyncRules.mock.calls[0][0].config.plan?.errors).toEqual([
108
+ expect.objectContaining({
109
+ level: 'fatal',
110
+ message: expect.stringContaining('only supported by MongoDB sources')
111
+ })
112
+ ]);
113
+ }
103
114
  });
104
115
 
105
- it.each(['warning', 'valid', 'unexpected error'] as const)(
106
- 'handles %s source-capability results before persisting a file-loaded config',
107
- async (result) => {
116
+ it.each(
117
+ [true, false].flatMap((exitOnError) =>
118
+ (['warning', 'valid', 'unexpected error'] as const).map((result) => ({ exitOnError, result }))
119
+ )
120
+ )(
121
+ 'checks source capabilities before persistence: $result, exit_on_error=$exitOnError',
122
+ async ({ result, exitOnError }) => {
108
123
  const yaml = /* yaml */ `
109
- # Sync config fixture.
124
+ # sync config fixture.
110
125
  config:
111
126
  edition: 3
112
127
  streams:
@@ -123,7 +138,7 @@ describe('AbstractReplicator startup sync config', () => {
123
138
  storageEngine: {
124
139
  activeBucketStorage: { configureSyncRules }
125
140
  } as unknown as AbstractReplicatorOptions['storageEngine'],
126
- syncRuleProvider: { get: async () => yaml, exitOnError: true, versionLabel: undefined },
141
+ syncRuleProvider: { get: async () => yaml, exitOnError, versionLabel: undefined },
127
142
  metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
128
143
  rateLimiter: {} as AbstractReplicatorOptions['rateLimiter']
129
144
  });
@@ -140,7 +155,7 @@ describe('AbstractReplicator startup sync config', () => {
140
155
  )
141
156
  );
142
157
 
143
- if (result === 'unexpected error') {
158
+ if (result === 'unexpected error' && exitOnError) {
144
159
  await expect(replicator.runStartupForTest()).rejects.toThrow('Source validation failed');
145
160
  expect(calls).toEqual(['validate']);
146
161
  } else {
@@ -232,6 +232,39 @@ streams:
232
232
  });
233
233
 
234
234
  describe('source capability validation', () => {
235
+ test('exposes stored replication errors when source checks cannot run', async () => {
236
+ const content = makeSyncRulesContent({
237
+ status: {
238
+ id: '1',
239
+ replicationStreamId: 1,
240
+ state: storage.SyncRuleState.PROCESSING,
241
+ last_checkpoint_lsn: null,
242
+ last_fatal_error: 'Source capability unavailable',
243
+ last_fatal_error_ts: new Date(),
244
+ last_keepalive_ts: null,
245
+ last_checkpoint_ts: null
246
+ }
247
+ });
248
+ const result = await getSyncRulesStatus(
249
+ makeRouteAPI(),
250
+ content,
251
+ {
252
+ ...OPTIONS,
253
+ check_connection: false,
254
+ active: false,
255
+ include_content: true
256
+ },
257
+ makeSystemStorage()
258
+ );
259
+ expect(result?.content).toBe(MINIMAL_SYNC_RULES);
260
+ expect(result?.errors).toContainEqual(
261
+ expect.objectContaining({
262
+ level: 'fatal',
263
+ message: 'Source capability unavailable'
264
+ })
265
+ );
266
+ });
267
+
235
268
  test('reports capability failures alongside table diagnostics', async () => {
236
269
  const api = makeRouteAPI();
237
270
  api.validateSourceCapabilities = async () => [
@@ -1,5 +1,5 @@
1
1
  import { BasicRouterRequest, Context, JwtPayload, ParsedSyncConfigSet, storage } from '@/index.js';
2
- import { logger } from '@powersync/lib-services-framework';
2
+ import { ErrorCode, logger } from '@powersync/lib-services-framework';
3
3
  import { PrecompiledSyncConfig, SqlSyncRules } from '@powersync/service-sync-rules';
4
4
  import { describe, expect, it, vi } from 'vitest';
5
5
  import { diagnostics, reprocess, validate } from '../../../src/routes/endpoints/admin.js';
@@ -105,7 +105,7 @@ bucket_definitions:
105
105
  request,
106
106
  params: {
107
107
  content: /* yaml */ `
108
- # Sync config fixture.
108
+ # sync config fixture.
109
109
  config:
110
110
  edition: 3
111
111
  streams:
@@ -135,7 +135,7 @@ bucket_definitions:
135
135
  request,
136
136
  params: {
137
137
  content: /* yaml */ `
138
- # Sync config fixture.
138
+ # sync config fixture.
139
139
  config:
140
140
  edition: 3
141
141
  streams:
@@ -168,7 +168,7 @@ bucket_definitions:
168
168
  request,
169
169
  params: {
170
170
  content: /* yaml */ `
171
- # Sync config fixture.
171
+ # sync config fixture.
172
172
  config:
173
173
  edition: 3
174
174
  source_table_options:
@@ -202,7 +202,7 @@ bucket_definitions:
202
202
  request,
203
203
  params: {
204
204
  sync_rules: /* yaml */ `
205
- # Sync config fixture.
205
+ # sync config fixture.
206
206
  config:
207
207
  edition: 3
208
208
  streams: {}
@@ -327,23 +327,38 @@ streams:
327
327
  });
328
328
 
329
329
  describe('reprocess', () => {
330
- it.each([reprocess, reprocessSyncRules])('blocks reprocessing on returned fatal diagnostics', async (route) => {
331
- const active = makeSyncConfigContent({ id: 7 });
332
- const updateSyncRules = vi.fn();
333
- const context = makeContext({
334
- getDeployingSyncConfig: vi.fn(async () => null),
335
- getActiveSyncConfig: vi.fn(async () => ({ content: active })),
336
- updateSyncRules
337
- });
338
- const api = context.service_context.routerEngine.getAPI();
339
- vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(api);
340
- api.validateSourceCapabilities = async () => [
341
- { level: 'warning', message: 'Advisory' },
342
- { level: 'fatal', message: 'Unsupported source' }
343
- ];
344
- await expect(route.handler({ context, params: {}, request })).rejects.toThrow('Unsupported source');
345
- expect(updateSyncRules).not.toHaveBeenCalled();
346
- });
330
+ it.each([reprocess, reprocessSyncRules].flatMap((route) => [false, true].map((throws) => ({ route, throws }))))(
331
+ 'returns 422 for rejected reprocessing at $route.path (adapter throws: $throws)',
332
+ async ({ route, throws }) => {
333
+ const active = makeSyncConfigContent({ id: 7 });
334
+ const updateSyncRules = vi.fn();
335
+ const context = makeContext({
336
+ getDeployingSyncConfig: vi.fn(async () => null),
337
+ getActiveSyncConfig: vi.fn(async () => ({ content: active })),
338
+ updateSyncRules
339
+ });
340
+ const api = context.service_context.routerEngine.getAPI();
341
+ vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(api);
342
+ api.validateSourceCapabilities = async () => {
343
+ if (throws) {
344
+ throw new Error('Unsupported source');
345
+ }
346
+ return [
347
+ { level: 'warning', message: 'Advisory' },
348
+ { level: 'fatal', message: 'Unsupported source' }
349
+ ];
350
+ };
351
+ await expect(route.handler({ context, params: {}, request })).rejects.toMatchObject({
352
+ errorData: {
353
+ status: 422,
354
+ code: ErrorCode.PSYNC_R0001,
355
+ description: 'Source capability validation failed',
356
+ details: 'Unsupported source'
357
+ }
358
+ });
359
+ expect(updateSyncRules).not.toHaveBeenCalled();
360
+ }
361
+ );
347
362
 
348
363
  it('reprocesses the active sync config', async () => {
349
364
  const active = makeSyncConfigContent({ id: 7, syncConfigId: 'active-config', version_label: 'v6' });
@@ -1,7 +1,7 @@
1
1
  import { BasicRouterRequest, Context, JwtPayload } from '@/index.js';
2
2
  import { logger } from '@powersync/lib-services-framework';
3
3
  import { describe, expect, it, vi } from 'vitest';
4
- import { deploySyncRules } from '../../../src/routes/endpoints/sync-rules.js';
4
+ import { deploySyncRules, validateSyncRules } from '../../../src/routes/endpoints/sync-rules.js';
5
5
  import { mockServiceContext } from './mocks.js';
6
6
 
7
7
  describe('sync-rules routes', () => {
@@ -30,6 +30,54 @@ describe('sync-rules routes', () => {
30
30
  };
31
31
  }
32
32
 
33
+ describe('filter connection validation', () => {
34
+ const FILTERED_CONFIG = /* yaml */ `
35
+ # sync config fixture.
36
+ config:
37
+ edition: 3
38
+ source_table_options:
39
+ orders:
40
+ mongodb_filter_expression: { $eq: ['$$doc.active', true] }
41
+ streams:
42
+ orders:
43
+ query: SELECT * FROM orders
44
+ `;
45
+
46
+ it.each(['postgresql', 'mongodb', undefined])('reports connection-type validation for %s', async (type) => {
47
+ const context = makeContext();
48
+ const adapter = context.service_context.routerEngine.getAPI();
49
+ vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(adapter);
50
+ vi.spyOn(adapter, 'getParseSyncRulesOptions').mockReturnValue({
51
+ defaultSchema: 'public',
52
+ connections: type === undefined ? undefined : { default: { type } }
53
+ });
54
+ const response = await validateSyncRules.handler({ context, params: { content: FILTERED_CONFIG }, request });
55
+ const result = JSON.parse(response.data);
56
+ expect(result.valid).toBe(type !== 'postgresql');
57
+ if (type === 'postgresql') {
58
+ expect(result.errors).toEqual([expect.stringContaining('only supported by MongoDB sources')]);
59
+ } else if (type === undefined) {
60
+ expect(result.warnings).toEqual([expect.stringContaining('without connection type information')]);
61
+ } else {
62
+ expect(result.warnings).toBeUndefined();
63
+ }
64
+ });
65
+
66
+ it('rejects deployment during parsing before persisting a non-MongoDB filter', async () => {
67
+ const context = makeContext();
68
+ const adapter = context.service_context.routerEngine.getAPI();
69
+ vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(adapter);
70
+ vi.spyOn(adapter, 'getParseSyncRulesOptions').mockReturnValue({
71
+ defaultSchema: 'public',
72
+ connections: { default: { type: 'postgresql' } }
73
+ });
74
+ await expect(deploySyncRules.handler({ context, params: { content: FILTERED_CONFIG }, request })).rejects.toThrow(
75
+ 'Sync config parsing failed'
76
+ );
77
+ expect(context.service_context.storageEngine.activeBucketStorage.updateSyncRules).not.toHaveBeenCalled();
78
+ });
79
+ });
80
+
33
81
  describe('deploy', () => {
34
82
  it('logs that bucket_definitions are deprecated', async () => {
35
83
  const warnSpy = vi.spyOn(logger, 'warn');
@@ -4,7 +4,7 @@ import { PrecompiledSyncConfig, SqlSyncRules } from '@powersync/service-sync-rul
4
4
  import { describe, expect, test } from 'vitest';
5
5
 
6
6
  const CONFIGURED = /* yaml */ `
7
- # Sync config fixture.
7
+ # sync config fixture.
8
8
  config:
9
9
  edition: 3
10
10
  source_table_options:
@@ -16,7 +16,7 @@ const CONFIGURED = /* yaml */ `
16
16
  `;
17
17
 
18
18
  describe('source-table options', () => {
19
- test('parses without module registration and preserves filters through compiled storage', () => {
19
+ test('preserves filters through compiled storage', () => {
20
20
  const parsed = SqlSyncRules.fromYaml(CONFIGURED, { defaultSchema: 'app' });
21
21
  const update = updateSyncRulesFromConfig(parsed);
22
22
  const restored = parsePersistedSyncConfigContent({
@@ -25,10 +25,9 @@ describe('source-table options', () => {
25
25
  storageVersion: 2,
26
26
  parseOptions: { defaultSchema: 'app' }
27
27
  });
28
- expect((restored.config as PrecompiledSyncConfig).plan.sourceTableConfig).toEqual(
29
- (parsed.config as PrecompiledSyncConfig).plan.sourceTableConfig
30
- );
31
- expect(update.config.plan!.plan).not.toHaveProperty('moduleData');
28
+ expect((restored.config as PrecompiledSyncConfig).plan.sourceTableConfig).toEqual({
29
+ orders: { mongodb_filter_expression: { $eq: ['$$doc.active', true] } }
30
+ });
32
31
  });
33
32
  test('reports invalid expressions before storage', () => {
34
33
  expect(() =>
@@ -37,7 +36,50 @@ describe('source-table options', () => {
37
36
  })
38
37
  ).toThrow('Expected a source field');
39
38
  });
40
- test('removing filters after a downgrade requires replacement processing', () => {
39
+ test.each([
40
+ ['a..orders: {}', 'Source table patterns must use'],
41
+ ['Users: {}, users: {}', 'resolve to the same pattern']
42
+ ])('persists fatal diagnostics for invalid source-table options: %s', (options, message) => {
43
+ const yaml = /* yaml */ `
44
+ # sync config fixture.
45
+ config:
46
+ edition: 3
47
+ source_table_options: { ${options} }
48
+ streams:
49
+ orders:
50
+ query: SELECT * FROM orders
51
+ `;
52
+ const parsed = SqlSyncRules.fromYaml(yaml, { defaultSchema: 'app', throwOnError: false });
53
+ expect(parsed.errors).toContainEqual(
54
+ expect.objectContaining({ type: 'fatal', message: expect.stringContaining(message) })
55
+ );
56
+ const diagnostic = parsed.errors.find((error) => error.type === 'fatal' && error.message.includes(message))!;
57
+ const offendingKey = options.startsWith('a..') ? 'a..orders' : 'users';
58
+ expect(yaml.slice(diagnostic.location.start, diagnostic.location.end)).toContain(offendingKey);
59
+ const update = updateSyncRulesFromConfig(parsed);
60
+ expect(update.config.yaml).toBe(yaml);
61
+ const restored = parsePersistedSyncConfigContent({
62
+ content: update.config.yaml,
63
+ compiledPlan: update.config.plan!,
64
+ storageVersion: 2,
65
+ parseOptions: { defaultSchema: 'app' }
66
+ });
67
+ expect(restored.errors.map(({ message, type, location }) => ({ message, type, location }))).toEqual(
68
+ parsed.errors.map(({ message, type, location }) => ({ message, type, location }))
69
+ );
70
+ expect((restored.config as PrecompiledSyncConfig).plan.sourceTableConfig ?? {}).toEqual({});
71
+ });
72
+
73
+ test('keeps valid filters on a partial plan with an unrelated SQL error', () => {
74
+ const yaml = CONFIGURED.replace('SELECT * FROM orders', 'SELECT FROM');
75
+ const parsed = SqlSyncRules.fromYaml(yaml, { defaultSchema: 'app', throwOnError: false });
76
+ expect(parsed.errors.some((error) => error.type === 'fatal')).toBe(true);
77
+ const update = updateSyncRulesFromConfig(parsed);
78
+ expect(update.config.plan!.plan.sourceTableConfig).toEqual({
79
+ orders: { mongodb_filter_expression: { $eq: ['$$doc.active', true] } }
80
+ });
81
+ });
82
+ test('requires replacement processing when filters change or are removed', () => {
41
83
  const deploy = (yaml: string) => updateSyncRulesFromConfig(SqlSyncRules.fromYaml(yaml, { defaultSchema: 'app' }));
42
84
  const first = deploy(CONFIGURED);
43
85
  const same = deploy(CONFIGURED.replace('SELECT *', 'SELECT id'));
@@ -52,4 +94,11 @@ describe('source-table options', () => {
52
94
  expect(isCompatible([first.config.plan], changed.config, logger)).toBe(false);
53
95
  expect(isCompatible([first.config.plan], removed.config, logger)).toBe(false);
54
96
  });
97
+ test('requires replacement processing when saved source-table options no longer validate', () => {
98
+ const update = updateSyncRulesFromConfig(SqlSyncRules.fromYaml(CONFIGURED, { defaultSchema: 'app' }));
99
+ const existing = structuredClone(update.config.plan!);
100
+ // A saved expression can become unsupported after a module or version change.
101
+ Object.assign(existing.plan.sourceTableConfig!.orders!, { mongodb_filter_expression: { $unsupported: [] } });
102
+ expect(isCompatible([existing], update.config, logger)).toBe(false);
103
+ });
55
104
  });