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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +22 -11
  2. package/dist/api/RouteAPI.d.ts +8 -1
  3. package/dist/api/api-index.d.ts +1 -0
  4. package/dist/api/api-index.js +1 -0
  5. package/dist/api/api-index.js.map +1 -1
  6. package/dist/api/diagnostics.js +28 -14
  7. package/dist/api/diagnostics.js.map +1 -1
  8. package/dist/api/source-capabilities.d.ts +12 -0
  9. package/dist/api/source-capabilities.js +27 -0
  10. package/dist/api/source-capabilities.js.map +1 -0
  11. package/dist/replication/AbstractReplicator.d.ts +6 -0
  12. package/dist/replication/AbstractReplicator.js +12 -2
  13. package/dist/replication/AbstractReplicator.js.map +1 -1
  14. package/dist/replication/ReplicationModule.js +10 -2
  15. package/dist/replication/ReplicationModule.js.map +1 -1
  16. package/dist/routes/configure-fastify.d.ts +24 -24
  17. package/dist/routes/endpoints/admin.d.ts +48 -48
  18. package/dist/routes/endpoints/admin.js +8 -8
  19. package/dist/routes/endpoints/admin.js.map +1 -1
  20. package/dist/routes/endpoints/sync-rules.js +51 -14
  21. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  22. package/dist/storage/BucketStorageFactory.d.ts +11 -13
  23. package/dist/storage/BucketStorageFactory.js +21 -11
  24. package/dist/storage/BucketStorageFactory.js.map +1 -1
  25. package/dist/storage/PersistedReplicationStream.d.ts +1 -2
  26. package/dist/storage/PersistedReplicationStream.js.map +1 -1
  27. package/dist/storage/PersistedSyncConfigContent.d.ts +4 -4
  28. package/dist/storage/PersistedSyncConfigContent.js +5 -12
  29. package/dist/storage/PersistedSyncConfigContent.js.map +1 -1
  30. package/dist/storage/StorageEngine.d.ts +0 -4
  31. package/dist/storage/StorageEngine.js +1 -7
  32. package/dist/storage/StorageEngine.js.map +1 -1
  33. package/dist/storage/StorageProvider.d.ts +1 -6
  34. package/dist/storage/SyncRulesBucketStorage.d.ts +1 -1
  35. package/dist/storage/storage-index.d.ts +0 -1
  36. package/dist/storage/storage-index.js +0 -1
  37. package/dist/storage/storage-index.js.map +1 -1
  38. package/dist/system/ServiceContext.d.ts +0 -20
  39. package/dist/system/ServiceContext.js +1 -29
  40. package/dist/system/ServiceContext.js.map +1 -1
  41. package/package.json +11 -11
  42. package/src/api/RouteAPI.ts +9 -1
  43. package/src/api/api-index.ts +1 -0
  44. package/src/api/diagnostics.ts +24 -12
  45. package/src/api/source-capabilities.ts +31 -0
  46. package/src/replication/AbstractReplicator.ts +14 -2
  47. package/src/replication/ReplicationModule.ts +9 -2
  48. package/src/routes/endpoints/admin.ts +14 -6
  49. package/src/routes/endpoints/sync-rules.ts +52 -16
  50. package/src/storage/BucketStorageFactory.ts +21 -19
  51. package/src/storage/PersistedReplicationStream.ts +1 -2
  52. package/src/storage/PersistedSyncConfigContent.ts +9 -16
  53. package/src/storage/StorageEngine.ts +1 -10
  54. package/src/storage/StorageProvider.ts +1 -6
  55. package/src/storage/SyncRulesBucketStorage.ts +1 -1
  56. package/src/storage/storage-index.ts +0 -1
  57. package/src/system/ServiceContext.ts +1 -47
  58. package/test/src/AbstractReplicator.test.ts +94 -23
  59. package/test/src/PersistedSyncConfigContent.test.ts +1 -3
  60. package/test/src/diagnostics.test.ts +71 -0
  61. package/test/src/routes/admin.test.ts +205 -11
  62. package/test/src/routes/mocks.ts +0 -2
  63. package/test/src/routes/sync-rules.test.ts +76 -0
  64. package/test/src/source-capabilities.test.ts +42 -0
  65. package/test/src/source_table_config.test.ts +55 -0
  66. package/test/src/storage/BucketStorageFactory.test.ts +46 -0
  67. package/tsconfig.tsbuildinfo +1 -1
  68. package/dist/storage/SyncConfigParser.d.ts +0 -44
  69. package/dist/storage/SyncConfigParser.js +0 -73
  70. package/dist/storage/SyncConfigParser.js.map +0 -1
  71. package/src/storage/SyncConfigParser.ts +0 -124
  72. package/test/src/SyncConfigParser.test.ts +0 -309
@@ -1,5 +1,4 @@
1
1
  import { container, LifeCycledSystem, MigrationManager, ServiceIdentifier } from '@powersync/lib-services-framework';
2
- import type { AdditionalSyncConfigParser } from '@powersync/service-sync-rules';
3
2
 
4
3
  import { EventsEngine } from '../events/EventsEngine.js';
5
4
  import { framework } from '../index.js';
@@ -11,16 +10,6 @@ import * as storage from '../storage/storage-index.js';
11
10
  import { SyncContext } from '../sync/SyncContext.js';
12
11
  import * as utils from '../util/util-index.js';
13
12
 
14
- /**
15
- * Registration-capable sync-config parser exposed to modules through the service context.
16
- */
17
- export interface ServiceContextSyncConfigParser extends storage.SyncConfigParser {
18
- /**
19
- * Registers a deterministic parser extension during module initialization, before storage starts.
20
- */
21
- registerParser(extension: AdditionalSyncConfigParser): void;
22
- }
23
-
24
13
  export interface ServiceContext {
25
14
  configuration: utils.ResolvedPowerSyncConfig;
26
15
  lifeCycleEngine: LifeCycledSystem;
@@ -33,11 +22,6 @@ export interface ServiceContext {
33
22
  writeCheckpointBatcher: utils.WriteCheckpointBatcher;
34
23
  serviceMode: ServiceContextMode;
35
24
  eventsEngine: EventsEngine;
36
- /**
37
- * Service-wide parser shared by routes, replication, and storage. Source modules register parser extensions on this
38
- * instance during module initialization.
39
- */
40
- readonly syncConfigParser: ServiceContextSyncConfigParser;
41
25
  }
42
26
 
43
27
  export enum ServiceContextMode {
@@ -69,20 +53,16 @@ export class ServiceContextContainer implements ServiceContext {
69
53
  routerEngine: routes.RouterEngine;
70
54
  writeCheckpointBatcher: utils.WriteCheckpointBatcher;
71
55
  serviceMode: ServiceContextMode;
72
- readonly #syncConfigParser: ServiceContextSyncConfigParser;
73
56
 
74
57
  constructor(options: ServiceContextOptions) {
75
58
  this.serviceMode = options.serviceMode;
76
59
  const { configuration } = options;
77
60
  this.configuration = configuration;
78
61
 
79
- this.#syncConfigParser = new ServiceContextSyncConfigParserImpl(() => this.storageEngine.started);
80
-
81
62
  this.lifeCycleEngine = new LifeCycledSystem();
82
63
 
83
64
  this.storageEngine = new storage.StorageEngine({
84
- configuration,
85
- syncConfigParser: this.#syncConfigParser
65
+ configuration
86
66
  });
87
67
  this.storageEngine.registerListener({
88
68
  storageFatalError: (error) => {
@@ -134,13 +114,6 @@ export class ServiceContextContainer implements ServiceContext {
134
114
  return container.getOptional(replication.ReplicationEngine);
135
115
  }
136
116
 
137
- /**
138
- * Returns the service-wide parser shared by routes, replication, and storage.
139
- */
140
- get syncConfigParser(): ServiceContextSyncConfigParser {
141
- return this.#syncConfigParser;
142
- }
143
-
144
117
  get metricsEngine(): metrics.MetricsEngine {
145
118
  return container.getImplementation(metrics.MetricsEngine);
146
119
  }
@@ -164,22 +137,3 @@ export class ServiceContextContainer implements ServiceContext {
164
137
  return container.getImplementation(identifier);
165
138
  }
166
139
  }
167
-
168
- /**
169
- * Registration-capable parser exposed by the service context during module initialization.
170
- */
171
- class ServiceContextSyncConfigParserImpl extends storage.SqlSyncConfigParser implements ServiceContextSyncConfigParser {
172
- constructor(private readonly isStorageStarted: () => boolean) {
173
- super();
174
- }
175
-
176
- /**
177
- * Registers an extension while preserving one parser definition for the service lifetime.
178
- */
179
- override registerParser(extension: AdditionalSyncConfigParser): void {
180
- if (this.isStorageStarted()) {
181
- throw new Error('A sync config parser extension cannot be registered after the storage engine has started.');
182
- }
183
- super.registerParser(extension);
184
- }
185
- }
@@ -1,9 +1,10 @@
1
+ import type { RouteAPI } from '@/api/RouteAPI.js';
2
+ import { assertSourceCapabilities, validateNoMongoFilterExpressions } from '@/api/source-capabilities.js';
1
3
  import { AbstractReplicationJob } from '@/replication/AbstractReplicationJob.js';
2
4
  import { AbstractReplicator, AbstractReplicatorOptions, CreateJobOptions } from '@/replication/AbstractReplicator.js';
3
5
  import { PersistedReplicationStream } from '@/storage/PersistedReplicationStream.js';
4
- import { SqlSyncConfigParser } from '@/storage/SyncConfigParser.js';
5
6
  import { SyncRulesBucketStorage } from '@/storage/SyncRulesBucketStorage.js';
6
- import { PrecompiledSyncConfig } from '@powersync/service-sync-rules';
7
+ import type { SyncConfig } from '@powersync/service-sync-rules';
7
8
  import { describe, expect, it, vi } from 'vitest';
8
9
 
9
10
  class TestReplicator extends AbstractReplicator {
@@ -64,26 +65,95 @@ class TestReplicator extends AbstractReplicator {
64
65
  }
65
66
 
66
67
  describe('AbstractReplicator startup sync config', () => {
67
- it.each([true, false])('retains registered module options with exit_on_error=%s', async (exitOnError) => {
68
- const syncConfigParser = new SqlSyncConfigParser([
69
- {
70
- id: 'example.tables',
71
- extendJsonSchema({ schema }) {
72
- (schema.properties as any).config.properties.source_table_options.additionalProperties.properties.sample = {
73
- type: 'number'
74
- };
75
- },
76
- parse({ config, context }) {
77
- const sourceTables = (config as { config: { source_table_options: { orders: { sample: number } } } }).config
78
- .source_table_options;
79
- context.parsedConfig.sourceTableConfig = sourceTables;
80
- (context.parsedConfig as PrecompiledSyncConfig).plan.moduleData = { 'example.tables': null };
81
- }
68
+ it.each([true, false])('rejects unsupported file-loaded filters with exit_on_error=%s', async (exitOnError) => {
69
+ const yaml = /* yaml */ `
70
+ # Sync config fixture.
71
+ config:
72
+ edition: 3
73
+ source_table_options:
74
+ orders:
75
+ mongodb_filter_expression: { $eq: ['$$doc.active', true] }
76
+ streams:
77
+ orders:
78
+ query: SELECT * FROM orders
79
+ `;
80
+ const configureSyncRules = vi.fn(async () => ({ updated: false }));
81
+ const replicator = new TestReplicator(async () => {}, {
82
+ id: 'test',
83
+ storageEngine: {
84
+ activeBucketStorage: { configureSyncRules }
85
+ } as unknown as AbstractReplicatorOptions['storageEngine'],
86
+ syncRuleProvider: { get: async () => yaml, exitOnError, versionLabel: undefined },
87
+ metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
88
+ rateLimiter: {} as AbstractReplicatorOptions['rateLimiter']
89
+ });
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();
103
+ });
104
+
105
+ it.each(['warning', 'valid', 'unexpected error'] as const)(
106
+ 'handles %s source-capability results before persisting a file-loaded config',
107
+ async (result) => {
108
+ const yaml = /* yaml */ `
109
+ # Sync config fixture.
110
+ config:
111
+ edition: 3
112
+ streams:
113
+ orders:
114
+ query: SELECT * FROM orders
115
+ `;
116
+ const calls: string[] = [];
117
+ const configureSyncRules = vi.fn(async () => {
118
+ calls.push('persist');
119
+ return { updated: false };
120
+ });
121
+ const replicator = new TestReplicator(async () => {}, {
122
+ id: 'test',
123
+ storageEngine: {
124
+ activeBucketStorage: { configureSyncRules }
125
+ } as unknown as AbstractReplicatorOptions['storageEngine'],
126
+ syncRuleProvider: { get: async () => yaml, exitOnError: true, versionLabel: undefined },
127
+ metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
128
+ rateLimiter: {} as AbstractReplicatorOptions['rateLimiter']
129
+ });
130
+ replicator.registerSourceCapabilitiesAssertion((config) =>
131
+ assertSourceCapabilities(
132
+ {
133
+ async validateSourceCapabilities() {
134
+ calls.push('validate');
135
+ if (result === 'unexpected error') throw new Error('Source validation failed');
136
+ return result === 'warning' ? [{ level: 'warning', message: 'Missing index' }] : [];
137
+ }
138
+ } as unknown as RouteAPI,
139
+ config
140
+ )
141
+ );
142
+
143
+ if (result === 'unexpected error') {
144
+ await expect(replicator.runStartupForTest()).rejects.toThrow('Source validation failed');
145
+ expect(calls).toEqual(['validate']);
146
+ } else {
147
+ await replicator.runStartupForTest();
148
+ expect(calls).toEqual(['validate', 'persist']);
82
149
  }
83
- ]);
150
+ }
151
+ );
152
+
153
+ it.each([true, false])('retains source-table options with exit_on_error=%s', async (exitOnError) => {
84
154
  const yaml = /* yaml */ `
85
155
  {
86
- config: { edition: 3, source_table_options: { orders: { sample: 10 } } },
156
+ config: { edition: 3, source_table_options: { orders: { mongodb_filter_expression: 'disabled' } } },
87
157
  streams: { orders: { query: SELECT * FROM orders } }
88
158
  }
89
159
  `;
@@ -91,7 +161,7 @@ describe('AbstractReplicator startup sync config', () => {
91
161
  const replicator = new TestReplicator(async () => {}, {
92
162
  id: 'test',
93
163
  storageEngine: {
94
- activeBucketStorage: { syncConfigParser, configureSyncRules }
164
+ activeBucketStorage: { configureSyncRules }
95
165
  } as unknown as AbstractReplicatorOptions['storageEngine'],
96
166
  syncRuleProvider: { get: async () => yaml, exitOnError, versionLabel: 'v2' },
97
167
  metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
@@ -108,14 +178,15 @@ describe('AbstractReplicator startup sync config', () => {
108
178
  parsed: expect.objectContaining({
109
179
  errors: [],
110
180
  config: expect.objectContaining({
111
- sourceTableConfig: { orders: { sample: 10 } }
181
+ plan: expect.objectContaining({
182
+ sourceTableConfig: { orders: { mongodb_filter_expression: 'disabled' } }
183
+ })
112
184
  })
113
185
  }),
114
186
  plan: expect.objectContaining({
115
187
  plan: expect.objectContaining({
116
188
  version: 3,
117
- sourceTableConfig: { orders: { sample: 10 } },
118
- moduleData: { 'example.tables': null }
189
+ sourceTableConfig: { orders: { mongodb_filter_expression: 'disabled' } }
119
190
  })
120
191
  })
121
192
  })
@@ -11,7 +11,6 @@ import { describe, expect, test } from 'vitest';
11
11
  import {
12
12
  parsePersistedSyncConfigContent,
13
13
  SerializedSyncPlan,
14
- SqlSyncConfigParser,
15
14
  updateSyncRulesFromConfig
16
15
  } from '../../src/storage/storage-index.js';
17
16
 
@@ -148,7 +147,6 @@ function restore(compiledPlan: SerializedSyncPlan) {
148
147
  content: yamlWithEvents,
149
148
  compiledPlan,
150
149
  storageVersion: 1,
151
- parseOptions: { defaultSchema: 'test_schema' },
152
- syncConfigParser: new SqlSyncConfigParser()
150
+ parseOptions: { defaultSchema: 'test_schema' }
153
151
  });
154
152
  }
@@ -230,3 +230,74 @@ streams:
230
230
  expect(yaml.slice(error.location!.start_offset, error.location!.end_offset)).toBe('unknown_key');
231
231
  });
232
232
  });
233
+
234
+ describe('source capability validation', () => {
235
+ test('reports capability failures alongside table diagnostics', async () => {
236
+ const api = makeRouteAPI();
237
+ api.validateSourceCapabilities = async () => [
238
+ { level: 'fatal', message: 'Source capability unavailable' },
239
+ { level: 'warning', message: 'Source advisory', location: { start_offset: 1, end_offset: 4 } }
240
+ ];
241
+ api.getDebugTablesInfo = async () => [
242
+ {
243
+ schema: 'public',
244
+ pattern: 'items',
245
+ wildcard: false,
246
+ table: {
247
+ schema: 'public',
248
+ name: 'items',
249
+ data_queries: true,
250
+ parameter_queries: false,
251
+ replication_id: [],
252
+ errors: [{ level: 'warning', message: 'Index missing' }]
253
+ }
254
+ }
255
+ ];
256
+ const result = await getSyncRulesStatus(api, makeSyncRulesContent(), OPTIONS, makeSystemStorage());
257
+ expect(result!.errors).toEqual(
258
+ expect.arrayContaining([
259
+ expect.objectContaining({ level: 'fatal', message: 'Source capability unavailable' }),
260
+ expect.objectContaining({ level: 'warning', message: 'Index missing' }),
261
+ expect.objectContaining({
262
+ level: 'warning',
263
+ message: 'Source advisory',
264
+ location: { start_offset: 1, end_offset: 4 }
265
+ })
266
+ ])
267
+ );
268
+ expect(result!.connections[0].tables).toHaveLength(1);
269
+ });
270
+
271
+ test('preserves both validation failures and continues independent diagnostics', async () => {
272
+ const api = makeRouteAPI({
273
+ wal_status: 'extended',
274
+ safe_wal_size: 4 * GB,
275
+ max_slot_wal_keep_size: 10 * GB
276
+ });
277
+ api.validateSourceCapabilities = async () => {
278
+ throw new Error('Source capability unavailable');
279
+ };
280
+ api.getDebugTablesInfo = async () => {
281
+ throw new Error('Table metadata unavailable');
282
+ };
283
+ const result = await getSyncRulesStatus(api, makeSyncRulesContent(), OPTIONS, makeSystemStorage());
284
+ expect(result!.errors).toEqual(
285
+ expect.arrayContaining([
286
+ expect.objectContaining({ level: 'fatal', message: 'Source capability unavailable' }),
287
+ expect.objectContaining({ level: 'fatal', message: 'Table metadata unavailable' }),
288
+ expect.objectContaining({ level: 'warning', message: expect.stringContaining('WAL budget') })
289
+ ])
290
+ );
291
+ });
292
+
293
+ test('does not check capabilities when connection checks are disabled', async () => {
294
+ const api = makeRouteAPI();
295
+ let called = false;
296
+ api.validateSourceCapabilities = async () => {
297
+ called = true;
298
+ return [];
299
+ };
300
+ await getSyncRulesStatus(api, makeSyncRulesContent(), { ...OPTIONS, check_connection: false }, makeSystemStorage());
301
+ expect(called).toBe(false);
302
+ });
303
+ });
@@ -1,8 +1,9 @@
1
1
  import { BasicRouterRequest, Context, JwtPayload, ParsedSyncConfigSet, storage } from '@/index.js';
2
2
  import { logger } from '@powersync/lib-services-framework';
3
- import { SqlSyncRules } from '@powersync/service-sync-rules';
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';
6
+ import { deploySyncRules, reprocessSyncRules, validateSyncRules } from '../../../src/routes/endpoints/sync-rules.js';
6
7
  import { mockServiceContext } from './mocks.js';
7
8
 
8
9
  describe('admin routes', () => {
@@ -86,20 +87,127 @@ bucket_definitions:
86
87
  return content as unknown as storage.PersistedSyncConfigContent;
87
88
  }
88
89
 
89
- describe('validate', () => {
90
- it('uses the service parser and includes its diagnostics', async () => {
90
+ it.each([false, true])(
91
+ 'continues sync-config diagnostics after capability failure (table failure: %s)',
92
+ async (tableFailure) => {
91
93
  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.' });
94
+ const api = context.service_context.routerEngine.getAPI();
95
+ vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(api);
96
+ api.validateSourceCapabilities = async () => {
97
+ throw new Error('Unsupported capability');
98
+ };
99
+ const tables = vi.spyOn(api, 'getDebugTablesInfo').mockImplementation(async () => {
100
+ if (tableFailure) throw new Error('Table inspection failed');
101
+ return [{ schema: 'public', pattern: 'items', wildcard: false, tables: [] }];
102
+ });
103
+ const response = await validateSyncRules.handler({
104
+ context,
105
+ request,
106
+ params: {
107
+ content: /* yaml */ `
108
+ # Sync config fixture.
109
+ config:
110
+ edition: 3
111
+ streams:
112
+ items:
113
+ query: SELECT * FROM items
114
+ `
97
115
  }
98
116
  });
117
+ const body = JSON.parse(response.data);
118
+ expect(body.valid).toBe(false);
119
+ expect(body.errors).toEqual(
120
+ tableFailure ? ['Unsupported capability', 'Table inspection failed'] : ['Unsupported capability']
121
+ );
122
+ expect(tables).toHaveBeenCalledOnce();
123
+ expect(body.source_tables).toHaveLength(tableFailure ? 0 : 1);
124
+ expect(body.data_tables).toBeDefined();
125
+ }
126
+ );
127
+
128
+ it('keeps advisory capability diagnostics visible without invalidating the config', async () => {
129
+ const context = makeContext();
130
+ const api = context.service_context.routerEngine.getAPI();
131
+ vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(api);
132
+ api.validateSourceCapabilities = async () => [{ level: 'warning', message: 'Source advisory' }];
133
+ const response = await validateSyncRules.handler({
134
+ context,
135
+ request,
136
+ params: {
137
+ content: /* yaml */ `
138
+ # Sync config fixture.
139
+ config:
140
+ edition: 3
141
+ streams:
142
+ items:
143
+ query: SELECT * FROM items
144
+ `
145
+ }
146
+ });
147
+ expect(JSON.parse(response.data)).toMatchObject({ valid: true, warnings: ['Source advisory'] });
148
+ });
149
+
150
+ it.each([true, false])('deployment checks source capabilities before persistence (allowed: %s)', async (allowed) => {
151
+ const updateSyncRules = vi.fn(async () => ({ replicationStreamName: 'new-slot' }));
152
+ const context = makeContext({ updateSyncRules });
153
+ context.service_context.configuration = {
154
+ sync_rules: { present: false }
155
+ } as typeof context.service_context.configuration;
156
+ const api = context.service_context.routerEngine.getAPI();
157
+ vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(api);
158
+ api.validateSourceCapabilities = async (config) => {
159
+ expect((config as PrecompiledSyncConfig).plan.sourceTableConfig?.orders?.mongodb_filter_expression).toEqual({
160
+ $eq: ['$$doc.active', true]
161
+ });
162
+ return allowed
163
+ ? [{ level: 'warning', message: 'Advisory source warning' }]
164
+ : [{ level: 'fatal', message: 'MongoDB pre-filtering is not available for this connection.' }];
165
+ };
166
+ const result = deploySyncRules.handler({
167
+ context,
168
+ request,
169
+ params: {
170
+ content: /* yaml */ `
171
+ # Sync config fixture.
172
+ config:
173
+ edition: 3
174
+ source_table_options:
175
+ orders:
176
+ mongodb_filter_expression: { $eq: ['$$doc.active', true] }
177
+ streams:
178
+ orders:
179
+ query: SELECT * FROM orders
180
+ `
181
+ }
182
+ });
183
+ if (allowed) {
184
+ await expect(result).resolves.toEqual({ slot_name: 'new-slot' });
185
+ expect(updateSyncRules).toHaveBeenCalledOnce();
186
+ } else {
187
+ await expect(result).rejects.toThrow();
188
+ expect(updateSyncRules).not.toHaveBeenCalled();
189
+ }
190
+ });
191
+
192
+ describe('validate', () => {
193
+ it('uses the service parser and includes its diagnostics', async () => {
194
+ const context = makeContext();
195
+ const api = context.service_context.routerEngine.getAPI();
196
+ vi.spyOn(context.service_context.routerEngine, 'getAPI').mockReturnValue(api);
197
+ api.validateSourceCapabilities = async () => {
198
+ throw new Error('Rejected by module validation.');
199
+ };
99
200
  const response = await validate.handler({
100
201
  context,
101
202
  request,
102
- params: { sync_rules: 'config: { edition: 3 }\nstreams: {}\n' }
203
+ params: {
204
+ sync_rules: /* yaml */ `
205
+ # Sync config fixture.
206
+ config:
207
+ edition: 3
208
+ streams: {}
209
+ `
210
+ }
103
211
  });
104
212
  expect(response.errors).toContainEqual(
105
213
  expect.objectContaining({
@@ -125,13 +233,59 @@ bucket_definitions:
125
233
  request
126
234
  });
127
235
 
128
- expect(response.errors).toEqual([
236
+ expect(response.errors).toContainEqual(
129
237
  expect.objectContaining({
130
238
  level: 'warning',
131
239
  location: { start_offset: 70, end_offset: 83 },
132
240
  message: 'Table public.missing_table not found'
133
241
  })
134
- ]);
242
+ );
243
+ });
244
+
245
+ it('warns that bucket_definitions are deprecated', async () => {
246
+ const context = makeContext();
247
+
248
+ const response = await validate.handler({
249
+ context,
250
+ params: {
251
+ sync_rules: `
252
+ bucket_definitions:
253
+ mybucket:
254
+ data:
255
+ - SELECT * FROM missing_table
256
+ `
257
+ },
258
+ request
259
+ });
260
+
261
+ expect(response.errors).toContainEqual(
262
+ expect.objectContaining({
263
+ level: 'warning',
264
+ message: expect.stringContaining('Sync Rules (`bucket_definitions`) are deprecated')
265
+ })
266
+ );
267
+ });
268
+
269
+ it('does not report the deprecation warning for a Sync Streams config', async () => {
270
+ const context = makeContext();
271
+
272
+ const response = await validate.handler({
273
+ context,
274
+ params: {
275
+ sync_rules: `
276
+ config:
277
+ edition: 3
278
+ streams:
279
+ mystream:
280
+ query: SELECT * FROM missing_table
281
+ `
282
+ },
283
+ request
284
+ });
285
+
286
+ expect(response.errors).not.toContainEqual(
287
+ expect.objectContaining({ message: expect.stringContaining('are deprecated') })
288
+ );
135
289
  });
136
290
  });
137
291
 
@@ -173,6 +327,24 @@ bucket_definitions:
173
327
  });
174
328
 
175
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
+ });
347
+
176
348
  it('reprocesses the active sync config', async () => {
177
349
  const active = makeSyncConfigContent({ id: 7, syncConfigId: 'active-config', version_label: 'v6' });
178
350
  const updateSyncRules = vi.fn(async () => ({
@@ -236,5 +408,27 @@ bucket_definitions:
236
408
  expect(activeBucketStorage.getActiveSyncConfig).not.toHaveBeenCalled();
237
409
  expect(activeBucketStorage.updateSyncRules).not.toHaveBeenCalled();
238
410
  });
411
+
412
+ it('logs that bucket_definitions are deprecated', async () => {
413
+ const warnSpy = vi.spyOn(logger, 'warn');
414
+ const activeBucketStorage = {
415
+ getDeployingSyncConfig: vi.fn(async () => null),
416
+ getActiveSyncConfig: vi.fn(async () => ({
417
+ content: makeSyncConfigContent({}),
418
+ replicationStream: {},
419
+ storage: {}
420
+ })),
421
+ updateSyncRules: vi.fn(async () => ({ replicationStreamName: 'new_slot' }))
422
+ };
423
+
424
+ await reprocess.handler({
425
+ context: makeContext(activeBucketStorage),
426
+ params: {},
427
+ request
428
+ });
429
+
430
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Sync Rules (`bucket_definitions`) are deprecated'));
431
+ warnSpy.mockRestore();
432
+ });
239
433
  });
240
434
  });
@@ -7,7 +7,6 @@ import {
7
7
  RouteAPI,
8
8
  RouterEngine,
9
9
  ServiceContext,
10
- SqlSyncConfigParser,
11
10
  StorageEngine,
12
11
  SyncContext,
13
12
  SyncRulesBucketStorage
@@ -39,7 +38,6 @@ export function mockServiceContext(storage: Partial<SyncRulesBucketStorage> | nu
39
38
  });
40
39
  createCoreAPIMetrics(metricsEngine);
41
40
  const service_context: Partial<ServiceContext> = {
42
- syncConfigParser: new SqlSyncConfigParser(),
43
41
  syncContext: new SyncContext({ maxBuckets: 1, maxDataFetchConcurrency: 1, maxParameterQueryResults: 1 }),
44
42
  eventsEngine: new EventsEngine(),
45
43
  routerEngine: {