@powersync/service-core 0.0.0-dev-20260224151854 → 0.0.0-dev-20260225160713

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 (40) hide show
  1. package/CHANGELOG.md +8 -5
  2. package/dist/entry/commands/config-command.js +2 -2
  3. package/dist/entry/commands/config-command.js.map +1 -1
  4. package/dist/routes/endpoints/admin.js +2 -1
  5. package/dist/routes/endpoints/admin.js.map +1 -1
  6. package/dist/storage/BucketStorageFactory.d.ts +22 -8
  7. package/dist/storage/BucketStorageFactory.js +14 -2
  8. package/dist/storage/BucketStorageFactory.js.map +1 -1
  9. package/dist/storage/PersistedSyncRulesContent.d.ts +3 -1
  10. package/dist/storage/PersistedSyncRulesContent.js +29 -6
  11. package/dist/storage/PersistedSyncRulesContent.js.map +1 -1
  12. package/dist/util/config/collectors/config-collector.js +13 -0
  13. package/dist/util/config/collectors/config-collector.js.map +1 -1
  14. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.d.ts +1 -1
  15. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +4 -4
  16. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
  17. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.d.ts +1 -1
  18. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +2 -2
  19. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
  20. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.d.ts +1 -1
  21. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.js +3 -3
  22. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.js.map +1 -1
  23. package/dist/util/config/types.d.ts +1 -1
  24. package/dist/util/config/types.js.map +1 -1
  25. package/dist/util/env.d.ts +1 -0
  26. package/dist/util/env.js +5 -0
  27. package/dist/util/env.js.map +1 -1
  28. package/package.json +5 -5
  29. package/src/entry/commands/config-command.ts +3 -3
  30. package/src/routes/endpoints/admin.ts +2 -1
  31. package/src/storage/BucketStorageFactory.ts +47 -4
  32. package/src/storage/PersistedSyncRulesContent.ts +39 -6
  33. package/src/util/config/collectors/config-collector.ts +16 -0
  34. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +5 -5
  35. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +3 -3
  36. package/src/util/config/sync-rules/impl/inline-sync-rules-collector.ts +4 -4
  37. package/src/util/config/types.ts +1 -2
  38. package/src/util/env.ts +5 -0
  39. package/test/src/config.test.ts +115 -0
  40. package/tsconfig.tsbuildinfo +1 -1
@@ -4,7 +4,13 @@ import { ReplicationEventPayload } from './ReplicationEventPayload.js';
4
4
  import { ReplicationLock } from './ReplicationLock.js';
5
5
  import { SyncRulesBucketStorage } from './SyncRulesBucketStorage.js';
6
6
  import { ReportStorage } from './ReportStorage.js';
7
- import { SqlSyncRules, SyncConfig } from '@powersync/service-sync-rules';
7
+ import {
8
+ PrecompiledSyncConfig,
9
+ SerializedCompatibilityContext,
10
+ serializeSyncPlan,
11
+ SqlSyncRules,
12
+ SyncConfig
13
+ } from '@powersync/service-sync-rules';
8
14
 
9
15
  /**
10
16
  * Represents a configured storage provider.
@@ -148,12 +154,32 @@ export interface StorageMetrics {
148
154
  export interface UpdateSyncRulesOptions {
149
155
  config: {
150
156
  yaml: string;
151
- // TODO: Add serialized sync plan if available
157
+ /**
158
+ * The serialized sync plan for the sync configuration, or `null` for configurations not using the sync stream
159
+ * compiler.
160
+ */
161
+ plan: SerializedSyncPlan | null;
152
162
  };
153
163
  lock?: boolean;
154
164
  storageVersion?: number;
155
165
  }
156
166
 
167
+ export interface SerializedSyncPlan {
168
+ /**
169
+ * The serialized plan, from {@link serializeSyncPlan}.
170
+ */
171
+ plan: unknown;
172
+ compatibility: SerializedCompatibilityContext;
173
+ /**
174
+ * Event descriptors are not currently represented in the sync plan because they don't use the sync streams compiler
175
+ * yet.
176
+ *
177
+ * We might revisit that in the future, but for now we store SQL text of their definitions here to be able to restore
178
+ * them.
179
+ */
180
+ eventDescriptors: Record<string, string[]>;
181
+ }
182
+
157
183
  export function updateSyncRulesFromYaml(
158
184
  content: string,
159
185
  options?: Omit<UpdateSyncRulesOptions, 'config'> & { validate?: boolean }
@@ -168,8 +194,25 @@ export function updateSyncRulesFromYaml(
168
194
  return updateSyncRulesFromConfig(config, options);
169
195
  }
170
196
 
171
- export function updateSyncRulesFromConfig(parsed: SyncConfig, options?: Omit<UpdateSyncRulesOptions, 'config'>) {
172
- return { config: { yaml: parsed.content }, ...options };
197
+ export function updateSyncRulesFromConfig(
198
+ parsed: SyncConfig,
199
+ options?: Omit<UpdateSyncRulesOptions, 'config'>
200
+ ): UpdateSyncRulesOptions {
201
+ let plan: SerializedSyncPlan | null = null;
202
+ if (parsed instanceof PrecompiledSyncConfig) {
203
+ const eventDescriptors: Record<string, string[]> = {};
204
+ for (const event of parsed.eventDescriptors) {
205
+ eventDescriptors[event.name] = event.sourceQueries.map((q) => q.sql);
206
+ }
207
+
208
+ plan = {
209
+ compatibility: parsed.compatibility.serialize(),
210
+ plan: serializeSyncPlan(parsed.plan),
211
+ eventDescriptors
212
+ };
213
+ }
214
+
215
+ return { config: { yaml: parsed.content, plan }, ...options };
173
216
  }
174
217
 
175
218
  export interface GetIntanceOptions {
@@ -1,8 +1,13 @@
1
1
  import {
2
+ CompatibilityContext,
2
3
  CompatibilityOption,
3
4
  DEFAULT_HYDRATION_STATE,
5
+ deserializeSyncPlan,
4
6
  HydratedSyncRules,
5
7
  HydrationState,
8
+ javaScriptExpressionEngine,
9
+ PrecompiledSyncConfig,
10
+ SqlEventDescriptor,
6
11
  SqlSyncRules,
7
12
  SyncConfigWithErrors,
8
13
  versionedHydrationState
@@ -10,7 +15,7 @@ import {
10
15
  import { ReplicationLock } from './ReplicationLock.js';
11
16
  import { STORAGE_VERSION_CONFIG, StorageVersionConfig } from './StorageVersionConfig.js';
12
17
  import { ErrorCode, ServiceError } from '@powersync/lib-services-framework';
13
- import { UpdateSyncRulesOptions } from './BucketStorageFactory.js';
18
+ import { SerializedSyncPlan, UpdateSyncRulesOptions } from './BucketStorageFactory.js';
14
19
 
15
20
  export interface ParseSyncRulesOptions {
16
21
  defaultSchema: string;
@@ -19,6 +24,7 @@ export interface ParseSyncRulesOptions {
19
24
  export interface PersistedSyncRulesContentData {
20
25
  readonly id: number;
21
26
  readonly sync_rules_content: string;
27
+ readonly compiled_plan: SerializedSyncPlan | null;
22
28
  readonly slot_name: string;
23
29
  /**
24
30
  * True if this is the "active" copy of the sync rules.
@@ -37,6 +43,7 @@ export interface PersistedSyncRulesContentData {
37
43
  export abstract class PersistedSyncRulesContent implements PersistedSyncRulesContentData {
38
44
  readonly id!: number;
39
45
  readonly sync_rules_content!: string;
46
+ readonly compiled_plan!: SerializedSyncPlan | null;
40
47
  readonly slot_name!: string;
41
48
  readonly active!: boolean;
42
49
  readonly storageVersion!: number;
@@ -72,11 +79,37 @@ export abstract class PersistedSyncRulesContent implements PersistedSyncRulesCon
72
79
 
73
80
  parsed(options: ParseSyncRulesOptions): PersistedSyncRules {
74
81
  let hydrationState: HydrationState;
75
- const syncRules = SqlSyncRules.fromYaml(this.sync_rules_content, options);
82
+
83
+ // Do we have a compiled sync plan? If so, restore from there instead of parsing everything again.
84
+ let config: SyncConfigWithErrors;
85
+ if (this.compiled_plan != null) {
86
+ const plan = deserializeSyncPlan(this.compiled_plan.plan);
87
+ const compatibility = CompatibilityContext.deserialize(this.compiled_plan.compatibility);
88
+ const eventDefinitions: SqlEventDescriptor[] = [];
89
+ for (const [name, queries] of Object.entries(this.compiled_plan.eventDescriptors)) {
90
+ const descriptor = new SqlEventDescriptor(name, compatibility);
91
+ for (const query of queries) {
92
+ descriptor.addSourceQuery(query, options);
93
+ }
94
+
95
+ eventDefinitions.push(descriptor);
96
+ }
97
+
98
+ const precompiled = new PrecompiledSyncConfig(plan, compatibility, eventDefinitions, {
99
+ defaultSchema: options.defaultSchema,
100
+ engine: javaScriptExpressionEngine(compatibility),
101
+ sourceText: this.sync_rules_content
102
+ });
103
+
104
+ config = { config: precompiled, errors: [] };
105
+ } else {
106
+ config = SqlSyncRules.fromYaml(this.sync_rules_content, options);
107
+ }
108
+
76
109
  const storageConfig = this.getStorageConfig();
77
110
  if (
78
111
  storageConfig.versionedBuckets ||
79
- syncRules.config.compatibility.isEnabled(CompatibilityOption.versionedBucketIds)
112
+ config.config.compatibility.isEnabled(CompatibilityOption.versionedBucketIds)
80
113
  ) {
81
114
  hydrationState = versionedHydrationState(this.id);
82
115
  } else {
@@ -86,16 +119,16 @@ export abstract class PersistedSyncRulesContent implements PersistedSyncRulesCon
86
119
  return {
87
120
  id: this.id,
88
121
  slot_name: this.slot_name,
89
- sync_rules: syncRules,
122
+ sync_rules: config,
90
123
  hydratedSyncRules: () => {
91
- return syncRules.config.hydrate({ hydrationState });
124
+ return config.config.hydrate({ hydrationState });
92
125
  }
93
126
  };
94
127
  }
95
128
 
96
129
  asUpdateOptions(options?: Omit<UpdateSyncRulesOptions, 'config'>): UpdateSyncRulesOptions {
97
130
  return {
98
- config: { yaml: this.sync_rules_content },
131
+ config: { yaml: this.sync_rules_content, plan: this.compiled_plan },
99
132
  ...options
100
133
  };
101
134
  }
@@ -40,6 +40,16 @@ export abstract class ConfigCollector {
40
40
  */
41
41
  const decoded = this.decode(serialized);
42
42
  this.validate(decoded);
43
+
44
+ /**
45
+ * For internal convenience, we duplicate sync_rules and sync_config. Making them interchangeable.
46
+ * Note, we only do this after validation (which only allows one option to be present)
47
+ */
48
+ if (decoded.sync_config) {
49
+ decoded.sync_rules = decoded.sync_config;
50
+ } else if (decoded.sync_rules) {
51
+ decoded.sync_config = decoded.sync_rules;
52
+ }
43
53
  return decoded;
44
54
  }
45
55
 
@@ -52,6 +62,12 @@ export abstract class ConfigCollector {
52
62
  if (!valid.valid) {
53
63
  throw new Error(`Failed to validate PowerSync config: ${valid.errors.join(', ')}`);
54
64
  }
65
+
66
+ if (config.sync_config && config.sync_rules) {
67
+ throw new Error(
68
+ 'Both `sync_config` and `sync_rules` are present in the service configuration. Please consolidate into one sync_config.'
69
+ );
70
+ }
55
71
  }
56
72
 
57
73
  decode(encoded: configFile.SerializedPowerSyncConfig): configFile.PowerSyncConfig {
@@ -1,6 +1,6 @@
1
+ import { configFile } from '@powersync/service-types';
1
2
  import { RunnerConfig, SyncRulesConfig } from '../../types.js';
2
3
  import { SyncRulesCollector } from '../sync-collector.js';
3
- import { configFile } from '@powersync/service-types';
4
4
 
5
5
  export class Base64SyncRulesCollector extends SyncRulesCollector {
6
6
  get name(): string {
@@ -8,15 +8,15 @@ export class Base64SyncRulesCollector extends SyncRulesCollector {
8
8
  }
9
9
 
10
10
  async collect(baseConfig: configFile.PowerSyncConfig, runnerConfig: RunnerConfig): Promise<SyncRulesConfig | null> {
11
- const { sync_rules_base64 } = runnerConfig;
12
- if (!sync_rules_base64) {
11
+ const { sync_config_base64 } = runnerConfig;
12
+ if (!sync_config_base64) {
13
13
  return null;
14
14
  }
15
15
 
16
16
  return {
17
17
  present: true,
18
- exit_on_error: baseConfig.sync_rules?.exit_on_error ?? true,
19
- content: Buffer.from(sync_rules_base64, 'base64').toString()
18
+ exit_on_error: baseConfig.sync_config?.exit_on_error ?? true,
19
+ content: Buffer.from(sync_config_base64, 'base64').toString()
20
20
  };
21
21
  }
22
22
  }
@@ -1,7 +1,7 @@
1
+ import { configFile } from '@powersync/service-types';
1
2
  import * as path from 'path';
2
3
  import { RunnerConfig, SyncRulesConfig } from '../../types.js';
3
4
  import { SyncRulesCollector } from '../sync-collector.js';
4
- import { configFile } from '@powersync/service-types';
5
5
 
6
6
  export class FileSystemSyncRulesCollector extends SyncRulesCollector {
7
7
  get name(): string {
@@ -9,7 +9,7 @@ export class FileSystemSyncRulesCollector extends SyncRulesCollector {
9
9
  }
10
10
 
11
11
  async collect(baseConfig: configFile.PowerSyncConfig, runnerConfig: RunnerConfig): Promise<SyncRulesConfig | null> {
12
- const sync_path = baseConfig.sync_rules?.path;
12
+ const sync_path = baseConfig.sync_config?.path;
13
13
  if (!sync_path) {
14
14
  return null;
15
15
  }
@@ -20,7 +20,7 @@ export class FileSystemSyncRulesCollector extends SyncRulesCollector {
20
20
  // Only persist the path here, and load on demand using `loadSyncRules()`.
21
21
  return {
22
22
  present: true,
23
- exit_on_error: baseConfig.sync_rules?.exit_on_error ?? true,
23
+ exit_on_error: baseConfig.sync_config?.exit_on_error ?? true,
24
24
  path: config_path ? path.resolve(path.dirname(config_path), sync_path) : sync_path
25
25
  };
26
26
  }
@@ -1,6 +1,6 @@
1
+ import { configFile } from '@powersync/service-types';
1
2
  import { SyncRulesConfig } from '../../types.js';
2
3
  import { SyncRulesCollector } from '../sync-collector.js';
3
- import { configFile } from '@powersync/service-types';
4
4
 
5
5
  export class InlineSyncRulesCollector extends SyncRulesCollector {
6
6
  get name(): string {
@@ -8,15 +8,15 @@ export class InlineSyncRulesCollector extends SyncRulesCollector {
8
8
  }
9
9
 
10
10
  async collect(baseConfig: configFile.PowerSyncConfig): Promise<SyncRulesConfig | null> {
11
- const content = baseConfig.sync_rules?.content;
11
+ const content = baseConfig?.sync_config?.content;
12
12
  if (!content) {
13
13
  return null;
14
14
  }
15
15
 
16
16
  return {
17
17
  present: true,
18
- exit_on_error: true,
19
- ...baseConfig.sync_rules
18
+ exit_on_error: baseConfig.sync_config?.exit_on_error ?? true,
19
+ ...baseConfig.sync_config
20
20
  };
21
21
  }
22
22
  }
@@ -1,6 +1,5 @@
1
1
  import { configFile } from '@powersync/service-types';
2
2
  import { CompoundKeyCollector } from '../../auth/CompoundKeyCollector.js';
3
- import { KeySpec } from '../../auth/KeySpec.js';
4
3
  import { KeyStore } from '../../auth/KeyStore.js';
5
4
 
6
5
  export enum ServiceRunner {
@@ -12,7 +11,7 @@ export enum ServiceRunner {
12
11
  export type RunnerConfig = {
13
12
  config_path?: string;
14
13
  config_base64?: string;
15
- sync_rules_base64?: string;
14
+ sync_config_base64?: string;
16
15
  };
17
16
 
18
17
  export type MigrationContext = {
package/src/util/env.ts CHANGED
@@ -12,9 +12,14 @@ export const env = utils.collectEnvironmentVariables({
12
12
  */
13
13
  POWERSYNC_CONFIG_B64: utils.type.string.optional(),
14
14
  /**
15
+ * @deprecated use POWERSYNC_SYNC_CONFIG_B64 instead.
15
16
  * Base64 encoded contents of sync rules YAML
16
17
  */
17
18
  POWERSYNC_SYNC_RULES_B64: utils.type.string.optional(),
19
+ /**
20
+ * Base64 encoded contents of sync config YAML
21
+ */
22
+ POWERSYNC_SYNC_CONFIG_B64: utils.type.string.optional(),
18
23
  /**
19
24
  * Runner to be started in this process
20
25
  */
@@ -69,6 +69,7 @@ describe('Config', () => {
69
69
 
70
70
  expect(config.api_parameters.max_buckets_per_connection).toBe(1);
71
71
  });
72
+
72
73
  it('should throw YAML validation error for invalid base64 config', {}, async () => {
73
74
  const yamlConfig = /* yaml */ `
74
75
  # PowerSync config
@@ -86,4 +87,118 @@ describe('Config', () => {
86
87
  })
87
88
  ).rejects.toThrow(/YAML Error:[\s\S]*Attempting to substitute environment variable INVALID_VAR/);
88
89
  });
90
+
91
+ it('should resolve inline sync config', async () => {
92
+ const yamlConfig = /* yaml */ `
93
+ # PowerSync config
94
+ replication:
95
+ connections: []
96
+ storage:
97
+ type: mongodb
98
+ sync_config:
99
+ content: |
100
+ config:
101
+ edition: 2
102
+ streams:
103
+ a:
104
+ query: SELECT * FROM users
105
+ `;
106
+
107
+ const collector = new CompoundConfigCollector();
108
+
109
+ const result = await collector.collectConfig({
110
+ config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
111
+ });
112
+
113
+ expect(result.sync_rules).toEqual({
114
+ present: true,
115
+ exit_on_error: true,
116
+ content: expect.stringContaining('edition: 2')
117
+ });
118
+ });
119
+
120
+ it('should still resolve inline sync rules', async () => {
121
+ const yamlConfig = /* yaml */ `
122
+ # PowerSync config
123
+ replication:
124
+ connections: []
125
+ storage:
126
+ type: mongodb
127
+ sync_rules:
128
+ content: |
129
+ config:
130
+ edition: 2
131
+ streams:
132
+ a:
133
+ query: SELECT * FROM users
134
+ `;
135
+
136
+ const collector = new CompoundConfigCollector();
137
+
138
+ const result = await collector.collectConfig({
139
+ config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
140
+ });
141
+
142
+ expect(result.sync_rules).toEqual({
143
+ present: true,
144
+ exit_on_error: true,
145
+ content: expect.stringContaining('edition: 2')
146
+ });
147
+ });
148
+
149
+ it('should resolve base64 sync config', async () => {
150
+ const yamlConfig = /* yaml */ `
151
+ # PowerSync config
152
+ replication:
153
+ connections: []
154
+ storage:
155
+ type: mongodb
156
+ `;
157
+ const yamlSyncConfig = /* yaml */ `
158
+ config:
159
+ edition: 2
160
+ streams:
161
+ a:
162
+ query: SELECT * FROM users
163
+ `;
164
+
165
+ const collector = new CompoundConfigCollector();
166
+
167
+ const result = await collector.collectConfig({
168
+ config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64'),
169
+ sync_config_base64: Buffer.from(yamlSyncConfig, 'utf-8').toString('base64')
170
+ });
171
+
172
+ expect(result.sync_rules).toEqual({
173
+ present: true,
174
+ exit_on_error: true,
175
+ content: expect.stringContaining('edition: 2')
176
+ });
177
+ });
178
+
179
+ it('should not allow both sync_config and sync_rules', async () => {
180
+ const yamlConfig = /* yaml */ `
181
+ # PowerSync config
182
+ replication:
183
+ connections: []
184
+ storage:
185
+ type: mongodb
186
+ sync_config:
187
+ content: |
188
+ config:
189
+ edition: 2
190
+ sync_rules:
191
+ content: |
192
+ config:
193
+ edition: 2
194
+ `;
195
+
196
+ const collector = new CompoundConfigCollector();
197
+
198
+ await expect(
199
+ collector.collectConfig({
200
+ config_base64: Buffer.from(yamlConfig, 'utf-8').toString('base64')
201
+ })
202
+ ).rejects.toThrow(/Both `sync_config` and `sync_rules` are present/);
203
+ });
89
204
  });