@powersync/service-core 0.0.0-dev-20260515144844 → 0.0.0-dev-20260602073133

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 (66) hide show
  1. package/CHANGELOG.md +24 -5
  2. package/dist/api/diagnostics.js +1 -1
  3. package/dist/api/diagnostics.js.map +1 -1
  4. package/dist/auth/RemoteJWKSCollector.js +3 -2
  5. package/dist/auth/RemoteJWKSCollector.js.map +1 -1
  6. package/dist/replication/RelationCache.d.ts +9 -2
  7. package/dist/replication/RelationCache.js +21 -2
  8. package/dist/replication/RelationCache.js.map +1 -1
  9. package/dist/routes/configure-fastify.js +3 -1
  10. package/dist/routes/configure-fastify.js.map +1 -1
  11. package/dist/routes/endpoints/admin.js +9 -5
  12. package/dist/routes/endpoints/admin.js.map +1 -1
  13. package/dist/routes/endpoints/sync-rules.js +1 -1
  14. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  15. package/dist/routes/route-register.d.ts +2 -0
  16. package/dist/routes/route-register.js +65 -3
  17. package/dist/routes/route-register.js.map +1 -1
  18. package/dist/storage/BucketStorageBatch.d.ts +29 -0
  19. package/dist/storage/BucketStorageBatch.js.map +1 -1
  20. package/dist/storage/BucketStorageFactory.d.ts +4 -0
  21. package/dist/storage/BucketStorageFactory.js +1 -1
  22. package/dist/storage/BucketStorageFactory.js.map +1 -1
  23. package/dist/storage/PersistedSyncRulesContent.d.ts +3 -3
  24. package/dist/storage/PersistedSyncRulesContent.js +6 -6
  25. package/dist/storage/PersistedSyncRulesContent.js.map +1 -1
  26. package/dist/storage/SourceEntity.d.ts +2 -1
  27. package/dist/storage/SourceTable.d.ts +17 -8
  28. package/dist/storage/SourceTable.js +25 -12
  29. package/dist/storage/SourceTable.js.map +1 -1
  30. package/dist/storage/SyncRulesBucketStorage.d.ts +26 -13
  31. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  32. package/dist/sync/BucketChecksumState.d.ts +4 -4
  33. package/dist/sync/BucketChecksumState.js +1 -1
  34. package/dist/sync/BucketChecksumState.js.map +1 -1
  35. package/dist/sync/sync.d.ts +2 -2
  36. package/dist/sync/sync.js.map +1 -1
  37. package/dist/util/util-index.d.ts +1 -0
  38. package/dist/util/util-index.js +1 -0
  39. package/dist/util/util-index.js.map +1 -1
  40. package/dist/util/utils.d.ts +5 -0
  41. package/dist/util/utils.js +7 -0
  42. package/dist/util/utils.js.map +1 -1
  43. package/package.json +5 -5
  44. package/src/api/diagnostics.ts +3 -3
  45. package/src/auth/RemoteJWKSCollector.ts +3 -1
  46. package/src/replication/RelationCache.ts +23 -4
  47. package/src/routes/configure-fastify.ts +8 -1
  48. package/src/routes/endpoints/admin.ts +10 -5
  49. package/src/routes/endpoints/sync-rules.ts +1 -1
  50. package/src/routes/route-register.ts +73 -4
  51. package/src/storage/BucketStorageBatch.ts +32 -0
  52. package/src/storage/BucketStorageFactory.ts +6 -1
  53. package/src/storage/PersistedSyncRulesContent.ts +9 -9
  54. package/src/storage/SourceEntity.ts +3 -1
  55. package/src/storage/SourceTable.ts +39 -19
  56. package/src/storage/SyncRulesBucketStorage.ts +28 -15
  57. package/src/sync/BucketChecksumState.ts +5 -5
  58. package/src/sync/sync.ts +3 -3
  59. package/src/util/util-index.ts +1 -0
  60. package/src/util/utils.ts +8 -0
  61. package/test/src/auth.test.ts +11 -0
  62. package/test/src/diagnostics.test.ts +10 -6
  63. package/test/src/routes/error-handler.integration.test.ts +275 -0
  64. package/test/src/routes/stream.test.ts +15 -4
  65. package/test/src/sync/BucketChecksumState.test.ts +25 -17
  66. package/tsconfig.tsbuildinfo +1 -1
@@ -5,6 +5,7 @@ import fetch from 'node-fetch';
5
5
  import {
6
6
  AuthorizationError,
7
7
  ErrorCode,
8
+ hostnameFromSocketAddress,
8
9
  LookupOptions,
9
10
  makeHostnameLookupFunction,
10
11
  ServiceAssertionError,
@@ -140,7 +141,8 @@ export class RemoteJWKSCollector implements KeyCollector {
140
141
  */
141
142
  resolveAgent(): http.Agent | https.Agent {
142
143
  const lookupOptions = this.options?.lookupOptions ?? { reject_ip_ranges: [] };
143
- const lookup = makeHostnameLookupFunction(this.url.hostname, lookupOptions);
144
+ const hostname = hostnameFromSocketAddress(this.url.hostname);
145
+ const lookup = makeHostnameLookupFunction(hostname, lookupOptions);
144
146
 
145
147
  const options: http.AgentOptions = {
146
148
  lookup
@@ -1,24 +1,43 @@
1
1
  import { SourceTable } from '../storage/SourceTable.js';
2
2
 
3
3
  export class RelationCache<T> {
4
- private cache = new Map<string | number, SourceTable>();
4
+ private cache = new Map<string | number, SourceTable[]>();
5
5
  private idFunction: (item: T | SourceTable) => string | number;
6
6
 
7
7
  constructor(idFunction: (item: T | SourceTable) => string | number) {
8
8
  this.idFunction = idFunction;
9
9
  }
10
10
 
11
+ /**
12
+ * Update a single table in-place - use when the snapshot status of the table has changed.
13
+ */
11
14
  update(table: SourceTable) {
12
15
  const id = this.idFunction(table);
13
- this.cache.set(id, table);
16
+ const existing = this.cache.get(id) ?? [];
17
+ const replacementIndex = existing.findIndex((candidate) => candidate.id == table.id);
18
+ if (replacementIndex == -1) {
19
+ this.cache.set(id, [...existing, table]);
20
+ } else {
21
+ const next = [...existing];
22
+ next[replacementIndex] = table;
23
+ this.cache.set(id, next);
24
+ }
14
25
  }
15
26
 
16
- get(source: T | SourceTable): SourceTable | undefined {
27
+ /**
28
+ * Set the full set of tables for a specific reference.
29
+ */
30
+ updateAll(ref: T, tables: SourceTable[]) {
31
+ const id = this.idFunction(ref);
32
+ this.cache.set(id, tables);
33
+ }
34
+
35
+ getAll(source: T | SourceTable): SourceTable[] | undefined {
17
36
  const id = this.idFunction(source);
18
37
  return this.cache.get(id);
19
38
  }
20
39
 
21
- delete(source: T | SourceTable): boolean {
40
+ delete(source: T): boolean {
22
41
  const id = this.idFunction(source);
23
42
  return this.cache.delete(id);
24
43
  }
@@ -1,6 +1,10 @@
1
1
  import type fastify from 'fastify';
2
2
 
3
- import { registerFastifyNotFoundHandler, registerFastifyRoutes } from './route-register.js';
3
+ import {
4
+ registerFastifyErrorHandler,
5
+ registerFastifyNotFoundHandler,
6
+ registerFastifyRoutes
7
+ } from './route-register.js';
4
8
 
5
9
  import * as system from '../system/system-index.js';
6
10
 
@@ -66,6 +70,9 @@ export function configureFastifyServer(server: fastify.FastifyInstance, options:
66
70
  };
67
71
  };
68
72
 
73
+ // Set on the outer server so both child scopes inherit.
74
+ registerFastifyErrorHandler(server);
75
+
69
76
  /**
70
77
  * Fastify creates an encapsulated context for each `.register` call.
71
78
  * Creating a separate context here to separate the concurrency limits for Admin APIs
@@ -1,5 +1,7 @@
1
+ import * as sqlite from 'node:sqlite';
2
+
1
3
  import { ErrorCode, errors, router, schema } from '@powersync/lib-services-framework';
2
- import { SourceSchema, SqlSyncRules, StaticSchema } from '@powersync/service-sync-rules';
4
+ import { nodeSqlite, SourceSchema, SqlSyncRules, StaticSchema } from '@powersync/service-sync-rules';
3
5
  import { internal_routes } from '@powersync/service-types';
4
6
 
5
7
  import { DEFAULT_HYDRATION_STATE } from '@powersync/service-sync-rules';
@@ -136,7 +138,7 @@ export const reprocess = routeDefinition({
136
138
  // 2. If the source does not set the storage version, this will update it do the current version.
137
139
  // We can consider tweaking this behavior in the future.
138
140
  const new_rules = await activeBucketStorage.updateSyncRules(
139
- storage.updateSyncRulesFromYaml(active.sync_rules.config.content, {
141
+ storage.updateSyncRulesFromYaml(active.syncConfigWithErrors.config.content, {
140
142
  // This sync config already passed validation. But if the config is not valid anymore due
141
143
  // to a service change, we do want to report the error here.
142
144
  validate: true
@@ -176,13 +178,16 @@ class FakeSyncRulesContentForValidation extends storage.PersistedSyncRulesConten
176
178
  parsed(options: storage.ParseSyncRulesOptions): storage.PersistedSyncRules {
177
179
  return {
178
180
  ...this,
179
- sync_rules: SqlSyncRules.fromYaml(this.sync_rules_content, {
181
+ syncConfigWithErrors: SqlSyncRules.fromYaml(this.sync_rules_content, {
180
182
  ...this.apiHandler.getParseSyncRulesOptions(),
181
183
  schema: this.schema
182
184
  }),
183
185
  hydrationState: DEFAULT_HYDRATION_STATE,
184
- hydratedSyncRules() {
185
- return this.sync_rules.config.hydrate({ hydrationState: DEFAULT_HYDRATION_STATE });
186
+ hydratedSyncConfig() {
187
+ return this.syncConfigWithErrors.config.hydrate({
188
+ hydrationState: DEFAULT_HYDRATION_STATE,
189
+ sqlite: nodeSqlite(sqlite)
190
+ });
186
191
  }
187
192
  };
188
193
  }
@@ -167,7 +167,7 @@ export const reprocessSyncRules = routeDefinition({
167
167
  }
168
168
 
169
169
  const new_rules = await activeBucketStorage.updateSyncRules(
170
- updateSyncRulesFromYaml(sync_rules.sync_rules.config.content, {
170
+ updateSyncRulesFromYaml(sync_rules.syncConfigWithErrors.config.content, {
171
171
  // This sync config already passed validation. But if the rules are not valid anymore due
172
172
  // to a service change, we do want to report the error here.
173
173
  validate: true
@@ -1,7 +1,8 @@
1
1
  import type fastify from 'fastify';
2
+ import * as zlib from 'node:zlib';
2
3
  import * as uuid from 'uuid';
3
4
 
4
- import { errors, HTTPMethod, logger, RouteNotFound, router, ServiceError } from '@powersync/lib-services-framework';
5
+ import { errors, HTTPMethod, logger, RouteNotFound, router } from '@powersync/lib-services-framework';
5
6
  import { FastifyReply } from 'fastify';
6
7
  import { Context, ContextProvider, RequestEndpoint, RequestEndpointHandlerPayload } from './router.js';
7
8
 
@@ -105,18 +106,86 @@ export function registerFastifyNotFoundHandler(app: fastify.FastifyInstance) {
105
106
  });
106
107
  }
107
108
 
108
- function serviceErrorToResponse(error: ServiceError): router.RouterResponse {
109
+ /** Registers a custom error handler that emits service-error JSON honouring any negotiated `Content-Encoding`. */
110
+ export function registerFastifyErrorHandler(app: fastify.FastifyInstance) {
111
+ app.setErrorHandler<Error>(async (error, _request, reply) => {
112
+ if (reply.raw.headersSent) {
113
+ // Headers already flushed - reply.code/header would throw ERR_HTTP_HEADERS_SENT.
114
+ reply.raw.destroy(error);
115
+ return;
116
+ }
117
+
118
+ const { status, data } = fastifyErrorToResponse(error);
119
+ if (status >= 500) {
120
+ logger.error('Request failed', error);
121
+ } else {
122
+ logger.warn(`Request failed: ${error.message}`, {
123
+ status,
124
+ code: data.error.code
125
+ });
126
+ }
127
+
128
+ const json = JSON.stringify(data);
129
+
130
+ // Fastify's default handler leaves `content-encoding` intact when it rewrites the body.
131
+ const encoding = reply.getHeader('content-encoding');
132
+ let body: string | Buffer = json;
133
+ if (encoding === 'gzip') {
134
+ body = zlib.gzipSync(json);
135
+ } else if (encoding === 'zstd') {
136
+ body = zlib.zstdCompressSync(json);
137
+ } else {
138
+ reply.removeHeader('content-encoding');
139
+ }
140
+
141
+ reply
142
+ .code(status)
143
+ .header('content-type', 'application/json; charset=utf-8')
144
+ .header('content-length', Buffer.byteLength(body))
145
+ .send(body);
146
+ });
147
+ }
148
+
149
+ type ErrorResponseData = { error: errors.ErrorData };
150
+
151
+ function serviceErrorToResponse(serviceError: errors.ServiceError): router.RouterResponse<ErrorResponseData> {
109
152
  return new router.RouterResponse({
110
- status: error.errorData.status || 500,
153
+ status: serviceError.errorData.status || 500,
111
154
  headers: {
112
155
  'Content-Type': 'application/json'
113
156
  },
114
157
  data: {
115
- error: error.errorData
158
+ error: serviceError.errorData
116
159
  }
117
160
  });
118
161
  }
119
162
 
163
+ function fastifyErrorToResponse(error: any): router.RouterResponse<ErrorResponseData> {
164
+ // Preserve 4xx status from Fastify built-ins (validation, invalid JSON body, etc.) instead of collapsing to 500.
165
+ if (
166
+ typeof error?.statusCode === 'number' &&
167
+ error.statusCode >= 400 &&
168
+ error.statusCode < 500 &&
169
+ typeof error.code === 'string'
170
+ ) {
171
+ return new router.RouterResponse({
172
+ status: error.statusCode,
173
+ headers: {
174
+ 'Content-Type': 'application/json'
175
+ },
176
+ data: {
177
+ error: {
178
+ name: error.name,
179
+ code: error.code,
180
+ status: error.statusCode,
181
+ description: error.message
182
+ }
183
+ }
184
+ });
185
+ }
186
+ return serviceErrorToResponse(errors.asServiceError(error));
187
+ }
188
+
120
189
  async function respond(reply: FastifyReply, response: router.RouterResponse) {
121
190
  Object.keys(response.headers).forEach((key) => {
122
191
  reply.header(key, response.headers[key]);
@@ -5,6 +5,7 @@ import { InternalOpId } from '../util/utils.js';
5
5
  import { ReplicationEventPayload } from './ReplicationEventPayload.js';
6
6
  import { SourceTable, TableSnapshotStatus } from './SourceTable.js';
7
7
  import { BatchedCustomWriteCheckpointOptions } from './storage-index.js';
8
+ import { ResolveTablesOptions, ResolveTablesResult } from './SyncRulesBucketStorage.js';
8
9
 
9
10
  export const DEFAULT_BUCKET_BATCH_COMMIT_OPTIONS: ResolvedBucketBatchCommitOptions = {
10
11
  createEmptyCheckpoints: true,
@@ -22,6 +23,11 @@ export interface BucketStorageBatch extends ObserverClient<BucketBatchStorageLis
22
23
  */
23
24
  last_flushed_op: InternalOpId | null;
24
25
 
26
+ /**
27
+ * True for snapshot batches that should skip rows already present in current_data.
28
+ */
29
+ readonly skipExistingRows: boolean;
30
+
25
31
  /**
26
32
  * Save an op, and potentially flush.
27
33
  *
@@ -91,10 +97,36 @@ export interface BucketStorageBatch extends ObserverClient<BucketBatchStorageLis
91
97
 
92
98
  markTableSnapshotDone(tables: SourceTable[], no_checkpoint_before_lsn?: string): Promise<SourceTable[]>;
93
99
  markTableSnapshotRequired(table: SourceTable): Promise<void>;
100
+
101
+ /**
102
+ * Mark the full replication snapshot as done without validating individual source table snapshot state.
103
+ *
104
+ * This is primarily intended for storage tests and setup helpers that manually construct storage state.
105
+ * Replicators should use `markSnapshotDone()` instead, because that validates that all known source tables
106
+ * have completed snapshotting before allowing checkpoints to be unblocked.
107
+ */
94
108
  markAllSnapshotDone(no_checkpoint_before_lsn: string): Promise<void>;
95
109
 
110
+ /**
111
+ * Mark the full replication snapshot as done after validating that all known source tables have completed snapshotting.
112
+ *
113
+ * Replicators should use this method when completing an initial snapshot. The validation prevents races where
114
+ * new source tables are marked as requiring a snapshot while global snapshot finalization is running.
115
+ *
116
+ * If `throwOnConflict` is false, this will instead return early without throwing if there are source tables that still require snapshotting.
117
+ * Use that only in cases where concurrency is expected, and can automatically retry/continue.
118
+ */
119
+ markSnapshotDone(no_checkpoint_before_lsn: string, options?: { throwOnConflict?: boolean }): Promise<void>;
120
+
96
121
  updateTableProgress(table: SourceTable, progress: Partial<TableSnapshotStatus>): Promise<SourceTable>;
97
122
 
123
+ /**
124
+ * Get the current status for an existing source table without creating or resolving a replacement table.
125
+ */
126
+ getSourceTableStatus(table: SourceTable): Promise<SourceTable | null>;
127
+
128
+ resolveTables(options: ResolveTablesOptions): Promise<ResolveTablesResult>;
129
+
98
130
  /**
99
131
  * Queues the creation of a custom Write Checkpoint. This will be persisted after operations are flushed.
100
132
  */
@@ -170,6 +170,11 @@ export interface UpdateSyncRulesOptions {
170
170
  };
171
171
  lock?: boolean;
172
172
  storageVersion?: number;
173
+
174
+ /**
175
+ * Only relevant if the result is used. This does not affect the persisted config.
176
+ */
177
+ defaultSchema?: string;
173
178
  }
174
179
 
175
180
  export interface SerializedSyncPlan {
@@ -196,7 +201,7 @@ export function updateSyncRulesFromYaml(
196
201
  const config = SqlSyncRules.fromYaml(content, {
197
202
  // No schema-based validation at this point
198
203
  schema: undefined,
199
- defaultSchema: 'not_applicable', // Not needed for validation
204
+ defaultSchema: options?.defaultSchema ?? 'not_applicable', // Not needed for validation
200
205
  throwOnError: options?.validate ?? false
201
206
  });
202
207
 
@@ -5,9 +5,9 @@ import {
5
5
  DEFAULT_HYDRATION_STATE,
6
6
  deserializeSyncPlan,
7
7
  ErrorLocation,
8
- HydratedSyncRules,
8
+ HydratedSyncConfig,
9
9
  HydrationState,
10
- javaScriptExpressionEngine,
10
+ nodeSqlite,
11
11
  PrecompiledSyncConfig,
12
12
  SqlEventDescriptor,
13
13
  SqlSyncRules,
@@ -15,6 +15,7 @@ import {
15
15
  versionedHydrationState,
16
16
  YamlError
17
17
  } from '@powersync/service-sync-rules';
18
+ import * as sqlite from 'node:sqlite';
18
19
  import { SerializedSyncPlan, UpdateSyncRulesOptions } from './BucketStorageFactory.js';
19
20
  import { ReplicationLock } from './ReplicationLock.js';
20
21
  import { STORAGE_VERSION_CONFIG, StorageVersionConfig } from './StorageVersionConfig.js';
@@ -101,7 +102,6 @@ export abstract class PersistedSyncRulesContent implements PersistedSyncRulesCon
101
102
 
102
103
  const precompiled = new PrecompiledSyncConfig(plan, compatibility, eventDefinitions, {
103
104
  defaultSchema: options.defaultSchema,
104
- engine: javaScriptExpressionEngine(compatibility),
105
105
  sourceText: this.sync_rules_content
106
106
  });
107
107
 
@@ -141,10 +141,10 @@ export abstract class PersistedSyncRulesContent implements PersistedSyncRulesCon
141
141
  return {
142
142
  id: this.id,
143
143
  slot_name: this.slot_name,
144
- sync_rules: config,
144
+ syncConfigWithErrors: config,
145
145
  hydrationState,
146
- hydratedSyncRules: () => {
147
- return config.config.hydrate({ hydrationState });
146
+ hydratedSyncConfig: () => {
147
+ return config.config.hydrate({ hydrationState, sqlite: nodeSqlite(sqlite) });
148
148
  }
149
149
  };
150
150
  }
@@ -153,7 +153,7 @@ export abstract class PersistedSyncRulesContent implements PersistedSyncRulesCon
153
153
  // defaultSchema is not relevant for the parsed version here
154
154
  const parsed = this.parsed({ defaultSchema: 'not_applicable' });
155
155
  return {
156
- config: { yaml: this.sync_rules_content, plan: this.compiled_plan, parsed: parsed.sync_rules },
156
+ config: { yaml: this.sync_rules_content, plan: this.compiled_plan, parsed: parsed.syncConfigWithErrors },
157
157
  ...options
158
158
  };
159
159
  }
@@ -163,12 +163,12 @@ export abstract class PersistedSyncRulesContent implements PersistedSyncRulesCon
163
163
 
164
164
  export interface PersistedSyncRules {
165
165
  readonly id: number;
166
- readonly sync_rules: SyncConfigWithErrors;
166
+ readonly syncConfigWithErrors: SyncConfigWithErrors;
167
167
  readonly slot_name: string;
168
168
  /**
169
169
  * For testing only.
170
170
  */
171
171
  readonly hydrationState: HydrationState;
172
172
 
173
- hydratedSyncRules(): HydratedSyncRules;
173
+ hydratedSyncConfig(): HydratedSyncConfig;
174
174
  }
@@ -1,3 +1,5 @@
1
+ import { SourceTableRef } from '@powersync/service-sync-rules';
2
+
1
3
  export interface ColumnDescriptor {
2
4
  name: string;
3
5
  /**
@@ -10,7 +12,7 @@ export interface ColumnDescriptor {
10
12
  typeId?: number;
11
13
  }
12
14
 
13
- export interface SourceEntityDescriptor {
15
+ export interface SourceEntityDescriptor extends SourceTableRef {
14
16
  /**
15
17
  * The internal id of the source entity structure in the database.
16
18
  * If undefined, the schema and name are used as the identifier.
@@ -1,7 +1,12 @@
1
- import { DEFAULT_TAG } from '@powersync/service-sync-rules';
1
+ import {
2
+ BucketDataSource,
3
+ DEFAULT_TAG,
4
+ ParameterIndexLookupCreator,
5
+ SourceTableRef
6
+ } from '@powersync/service-sync-rules';
2
7
  import { bson } from '../index.js';
3
8
  import * as util from '../util/util-index.js';
4
- import { ColumnDescriptor, SourceEntityDescriptor } from './SourceEntity.js';
9
+ import { ColumnDescriptor } from './SourceEntity.js';
5
10
 
6
11
  /**
7
12
  * Format of the id depends on the bucket storage module. It should be consistent within the module.
@@ -10,12 +15,12 @@ export type SourceTableId = string | bson.ObjectId;
10
15
 
11
16
  export interface SourceTableOptions {
12
17
  id: SourceTableId;
13
- connectionTag: string;
18
+ ref: SourceTableRef;
14
19
  objectId: number | string | undefined;
15
- schema: string;
16
- name: string;
17
20
  replicaIdColumns: ColumnDescriptor[];
18
21
  snapshotComplete: boolean;
22
+ bucketDataSources: BucketDataSource[];
23
+ parameterLookupSources: ParameterIndexLookupCreator[];
19
24
  }
20
25
 
21
26
  export interface TableSnapshotStatus {
@@ -24,7 +29,13 @@ export interface TableSnapshotStatus {
24
29
  lastKey: Uint8Array | null;
25
30
  }
26
31
 
27
- export class SourceTable implements SourceEntityDescriptor {
32
+ /**
33
+ * Represents a resolved source table.
34
+ *
35
+ * There could be multiple of these for the same SourceTableRef.
36
+ * For that reason, we do not implement the SourceTableRef interface, to ensure that the two are not used interchangably.
37
+ */
38
+ export class SourceTable {
28
39
  static readonly DEFAULT_TAG = DEFAULT_TAG;
29
40
 
30
41
  /**
@@ -71,31 +82,39 @@ export class SourceTable implements SourceEntityDescriptor {
71
82
  return this.options.id;
72
83
  }
73
84
 
74
- get connectionTag() {
75
- return this.options.connectionTag;
76
- }
77
-
78
85
  get objectId() {
79
86
  return this.options.objectId;
80
87
  }
81
88
 
82
89
  get schema() {
83
- return this.options.schema;
90
+ return this.options.ref.schema;
84
91
  }
85
92
  get name() {
86
- return this.options.name;
93
+ return this.options.ref.name;
94
+ }
95
+
96
+ get ref() {
97
+ return this.options.ref;
87
98
  }
88
99
 
89
100
  get replicaIdColumns() {
90
101
  return this.options.replicaIdColumns;
91
102
  }
92
103
 
104
+ get bucketDataSources() {
105
+ return this.options.bucketDataSources;
106
+ }
107
+
108
+ get parameterLookupSources() {
109
+ return this.options.parameterLookupSources;
110
+ }
111
+
93
112
  /**
94
- * Sanitized name of the entity in the format of "{schema}.{entity name}"
95
- * Suitable for safe use in Postgres queries.
113
+ * Sanitized name of the entity in the format of "{schema}.{entity name}".
114
+ * Suitable for safe use in Postgres queries.
96
115
  */
97
116
  get qualifiedName() {
98
- return `${util.escapeIdentifier(this.schema)}.${util.escapeIdentifier(this.name)}`;
117
+ return util.qualifiedName(this.ref);
99
118
  }
100
119
 
101
120
  get syncAny() {
@@ -108,15 +127,16 @@ export class SourceTable implements SourceEntityDescriptor {
108
127
  clone() {
109
128
  const copy = new SourceTable({
110
129
  id: this.id,
111
- connectionTag: this.connectionTag,
130
+ ref: this.options.ref,
112
131
  objectId: this.objectId,
113
- schema: this.schema,
114
- name: this.name,
115
132
  replicaIdColumns: this.replicaIdColumns,
116
- snapshotComplete: this.snapshotComplete
133
+ snapshotComplete: this.snapshotComplete,
134
+ bucketDataSources: this.bucketDataSources,
135
+ parameterLookupSources: this.parameterLookupSources
117
136
  });
118
137
  copy.syncData = this.syncData;
119
138
  copy.syncParameters = this.syncParameters;
139
+ copy.syncEvent = this.syncEvent;
120
140
  copy.snapshotStatus = this.snapshotStatus;
121
141
  return copy;
122
142
  }
@@ -1,10 +1,11 @@
1
1
  import { Logger, ObserverClient } from '@powersync/lib-services-framework';
2
2
  import {
3
3
  BucketDataSource,
4
- HydratedSyncRules,
4
+ HydratedSyncConfig,
5
5
  ParameterLookupRows,
6
6
  ScopedParameterLookup
7
7
  } from '@powersync/service-sync-rules';
8
+ import * as bson from 'bson';
8
9
  import { PerformanceTracer } from '../tracing/PerformanceTracer.js';
9
10
  import * as util from '../util/util-index.js';
10
11
  import { BucketStorageBatch, FlushedResult, SaveUpdate } from './BucketStorageBatch.js';
@@ -12,6 +13,7 @@ import { BucketStorageFactory } from './BucketStorageFactory.js';
12
13
  import { ParseSyncRulesOptions } from './PersistedSyncRulesContent.js';
13
14
  import { SourceEntityDescriptor } from './SourceEntity.js';
14
15
  import { SourceTable } from './SourceTable.js';
16
+ import { StorageVersionConfig } from './StorageVersionConfig.js';
15
17
  import { SyncStorageWriteCheckpointAPI } from './WriteCheckpointAPI.js';
16
18
 
17
19
  /**
@@ -22,15 +24,11 @@ export interface SyncRulesBucketStorage
22
24
  SyncStorageWriteCheckpointAPI {
23
25
  readonly group_id: number;
24
26
  readonly slot_name: string;
27
+ readonly storageConfig: StorageVersionConfig;
25
28
 
26
29
  readonly factory: BucketStorageFactory;
27
30
  readonly logger: Logger;
28
31
 
29
- /**
30
- * Resolve a table, keeping track of it internally.
31
- */
32
- resolveTable(options: ResolveTableOptions): Promise<ResolveTableResult>;
33
-
34
32
  /**
35
33
  * Create a new writer.
36
34
  *
@@ -46,7 +44,7 @@ export interface SyncRulesBucketStorage
46
44
  callback: (batch: BucketStorageBatch) => Promise<void>
47
45
  ): Promise<FlushedResult | null>;
48
46
 
49
- getParsedSyncRules(options: ParseSyncRulesOptions): HydratedSyncRules;
47
+ getParsedSyncRules(options: ParseSyncRulesOptions): HydratedSyncConfig;
50
48
 
51
49
  /**
52
50
  * Terminate the replication stream.
@@ -156,18 +154,26 @@ export interface SyncRuleStatus {
156
154
  active: boolean;
157
155
  snapshot_done: boolean;
158
156
  snapshot_lsn: string | null;
157
+ /**
158
+ * Last persisted operation that must be included in the next checkpoint once checkpointing is unblocked.
159
+ */
160
+ keepalive_op: util.InternalOpId | null;
159
161
  }
160
- export interface ResolveTableOptions {
161
- group_id: number;
162
+ export interface ResolveTablesOptions {
162
163
  connection_id: number;
163
- connection_tag: string;
164
- entity_descriptor: SourceEntityDescriptor;
165
-
166
- sync_rules: HydratedSyncRules;
164
+ source: SourceEntityDescriptor;
165
+ /**
166
+ * For tests only - custom id generator for stable ids.
167
+ */
168
+ idGenerator?: () => string | bson.ObjectId;
169
+ /**
170
+ * For tests only - override the sync rules used.
171
+ */
172
+ syncRules?: HydratedSyncConfig;
167
173
  }
168
174
 
169
- export interface ResolveTableResult {
170
- table: SourceTable;
175
+ export interface ResolveTablesResult {
176
+ tables: SourceTable[];
171
177
  dropTables: SourceTable[];
172
178
  }
173
179
 
@@ -198,11 +204,18 @@ export interface CreateWriterOptions extends ParseSyncRulesOptions {
198
204
  */
199
205
  markRecordUnavailable?: BucketStorageMarkRecordUnavailable;
200
206
 
207
+ hooks?: StorageHooks;
208
+
201
209
  tracer?: PerformanceTracer<'storage' | 'evaluate'>;
202
210
 
203
211
  logger?: Logger;
204
212
  }
205
213
 
214
+ export interface StorageHooks {
215
+ beforeBatchFlush?: (batch: BucketStorageBatch) => Promise<void>;
216
+ afterBatchFlush?: (batch: BucketStorageBatch) => Promise<void>;
217
+ }
218
+
206
219
  /**
207
220
  * @deprecated Use `CreateWriterOptions`.
208
221
  */
@@ -2,7 +2,7 @@ import {
2
2
  BucketParameterQuerier,
3
3
  BucketPriority,
4
4
  BucketSource,
5
- HydratedSyncRules,
5
+ HydratedSyncConfig,
6
6
  mergeBuckets,
7
7
  QuerierError,
8
8
  RequestedStream,
@@ -28,7 +28,7 @@ import { getIntersection, hasIntersection } from './util.js';
28
28
  export interface BucketChecksumStateOptions {
29
29
  syncContext: SyncContext;
30
30
  bucketStorage: BucketChecksumStateStorage;
31
- syncRules: HydratedSyncRules;
31
+ syncRules: HydratedSyncConfig;
32
32
  tokenPayload: JwtPayload;
33
33
  syncRequest: util.StreamingSyncRequest;
34
34
  logger?: Logger;
@@ -285,7 +285,7 @@ export class BucketChecksumState {
285
285
  const streamNameToIndex = new Map<string, number>();
286
286
  this.streamNameToIndex = streamNameToIndex;
287
287
 
288
- for (const source of this.parameterState.syncRules.definition.bucketSources) {
288
+ for (const source of this.parameterState.syncRules.bucketSourceDefinitions) {
289
289
  if (this.parameterState.isSubscribedToStream(source)) {
290
290
  streamNameToIndex.set(source.name, subscriptions.length);
291
291
 
@@ -416,7 +416,7 @@ export interface CheckpointUpdate {
416
416
  export class BucketParameterState {
417
417
  private readonly context: SyncContext;
418
418
  public readonly bucketStorage: BucketChecksumStateStorage;
419
- public readonly syncRules: HydratedSyncRules;
419
+ public readonly syncRules: HydratedSyncConfig;
420
420
  public readonly syncParams: RequestParameters;
421
421
  private readonly querier: BucketParameterQuerier;
422
422
  /**
@@ -439,7 +439,7 @@ export class BucketParameterState {
439
439
  constructor(
440
440
  context: SyncContext,
441
441
  bucketStorage: BucketChecksumStateStorage,
442
- syncRules: HydratedSyncRules,
442
+ syncRules: HydratedSyncConfig,
443
443
  tokenPayload: JwtPayload,
444
444
  request: util.StreamingSyncRequest,
445
445
  logger: Logger
package/src/sync/sync.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { JSONBig, JsonContainer } from '@powersync/service-jsonbig';
2
- import { BucketPriority, HydratedSyncRules, ResolvedBucket, SqliteJsonValue } from '@powersync/service-sync-rules';
2
+ import { BucketPriority, HydratedSyncConfig, ResolvedBucket, SqliteJsonValue } from '@powersync/service-sync-rules';
3
3
 
4
4
  import { AbortError } from 'ix/aborterror.js';
5
5
 
@@ -17,7 +17,7 @@ import { TokenStreamOptions, acquireSemaphoreAbortable, settledPromise, tokenStr
17
17
  export interface SyncStreamParameters {
18
18
  syncContext: SyncContext;
19
19
  bucketStorage: storage.SyncRulesBucketStorage;
20
- syncRules: HydratedSyncRules;
20
+ syncRules: HydratedSyncConfig;
21
21
  params: util.StreamingSyncRequest;
22
22
  token: auth.JwtPayload;
23
23
  logger?: Logger;
@@ -94,7 +94,7 @@ export async function* streamResponse(
94
94
  async function* streamResponseInner(
95
95
  syncContext: SyncContext,
96
96
  bucketStorage: storage.SyncRulesBucketStorage,
97
- syncRules: HydratedSyncRules,
97
+ syncRules: HydratedSyncConfig,
98
98
  params: util.StreamingSyncRequest,
99
99
  tokenPayload: auth.JwtPayload,
100
100
  tracker: RequestTracker,