@powersync/service-core 0.0.0-dev-20260803144812 → 0.0.0-dev-20260929095716

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +114 -5
  2. package/dist/api/diagnostics.js +7 -2
  3. package/dist/api/diagnostics.js.map +1 -1
  4. package/dist/entry/commands/compact-action.js +29 -25
  5. package/dist/entry/commands/compact-action.js.map +1 -1
  6. package/dist/entry/commands/config-command.js +1 -1
  7. package/dist/entry/commands/config-command.js.map +1 -1
  8. package/dist/metrics/metrics-interfaces.d.ts +5 -1
  9. package/dist/metrics/metrics-interfaces.js.map +1 -1
  10. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.d.ts +36 -0
  11. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js +70 -0
  12. package/dist/metrics/open-telemetry/MetricAttributeFilteringExporter.js.map +1 -0
  13. package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js +6 -1
  14. package/dist/metrics/open-telemetry/OpenTelemetryMetricsFactory.js.map +1 -1
  15. package/dist/metrics/open-telemetry/util.js +7 -3
  16. package/dist/metrics/open-telemetry/util.js.map +1 -1
  17. package/dist/migrations/PowerSyncMigrationManager.js +2 -1
  18. package/dist/migrations/PowerSyncMigrationManager.js.map +1 -1
  19. package/dist/replication/AbstractReplicator.d.ts +5 -0
  20. package/dist/replication/AbstractReplicator.js +31 -13
  21. package/dist/replication/AbstractReplicator.js.map +1 -1
  22. package/dist/replication/ReplicationModule.d.ts +0 -7
  23. package/dist/replication/ReplicationModule.js +0 -1
  24. package/dist/replication/ReplicationModule.js.map +1 -1
  25. package/dist/routes/configure-fastify.d.ts +12 -3
  26. package/dist/routes/endpoints/admin.d.ts +24 -6
  27. package/dist/routes/endpoints/admin.js +17 -11
  28. package/dist/routes/endpoints/admin.js.map +1 -1
  29. package/dist/routes/endpoints/socket-route.js +7 -5
  30. package/dist/routes/endpoints/socket-route.js.map +1 -1
  31. package/dist/routes/endpoints/sync-rules.js +18 -10
  32. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  33. package/dist/storage/BucketStorageBatch.d.ts +2 -1
  34. package/dist/storage/BucketStorageBatch.js.map +1 -1
  35. package/dist/storage/BucketStorageFactory.d.ts +49 -6
  36. package/dist/storage/BucketStorageFactory.js +25 -8
  37. package/dist/storage/BucketStorageFactory.js.map +1 -1
  38. package/dist/storage/PersistedReplicationStream.d.ts +2 -1
  39. package/dist/storage/PersistedReplicationStream.js.map +1 -1
  40. package/dist/storage/PersistedSyncConfigContent.d.ts +6 -4
  41. package/dist/storage/PersistedSyncConfigContent.js +34 -14
  42. package/dist/storage/PersistedSyncConfigContent.js.map +1 -1
  43. package/dist/storage/ReplicationEventPayload.d.ts +6 -1
  44. package/dist/storage/SourceEntity.d.ts +7 -2
  45. package/dist/storage/SourceTable.d.ts +37 -6
  46. package/dist/storage/SourceTable.js +42 -10
  47. package/dist/storage/SourceTable.js.map +1 -1
  48. package/dist/storage/SourceTableReconciler.d.ts +83 -0
  49. package/dist/storage/SourceTableReconciler.js +95 -0
  50. package/dist/storage/SourceTableReconciler.js.map +1 -0
  51. package/dist/storage/StorageEngine.d.ts +4 -0
  52. package/dist/storage/StorageEngine.js +7 -1
  53. package/dist/storage/StorageEngine.js.map +1 -1
  54. package/dist/storage/StorageProvider.d.ts +8 -0
  55. package/dist/storage/StorageVersionConfig.d.ts +4 -0
  56. package/dist/storage/StorageVersionConfig.js +10 -1
  57. package/dist/storage/StorageVersionConfig.js.map +1 -1
  58. package/dist/storage/SyncConfigParser.d.ts +44 -0
  59. package/dist/storage/SyncConfigParser.js +70 -0
  60. package/dist/storage/SyncConfigParser.js.map +1 -0
  61. package/dist/storage/SyncRulesBucketStorage.d.ts +48 -8
  62. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  63. package/dist/storage/WriteCheckpointAPI.d.ts +25 -3
  64. package/dist/storage/WriteCheckpointAPI.js.map +1 -1
  65. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +23 -7
  66. package/dist/storage/implementation/BucketDefinitionMapping.js +88 -14
  67. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -1
  68. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +9 -5
  69. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -1
  70. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +9 -1
  71. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -1
  72. package/dist/storage/storage-index.d.ts +2 -0
  73. package/dist/storage/storage-index.js +2 -0
  74. package/dist/storage/storage-index.js.map +1 -1
  75. package/dist/storage/storage-metrics.js +120 -4
  76. package/dist/storage/storage-metrics.js.map +1 -1
  77. package/dist/sync/BucketChecksumState.d.ts +2 -2
  78. package/dist/sync/BucketChecksumState.js +5 -4
  79. package/dist/sync/BucketChecksumState.js.map +1 -1
  80. package/dist/sync/sync.js +37 -9
  81. package/dist/sync/sync.js.map +1 -1
  82. package/dist/sync/util.d.ts +1 -1
  83. package/dist/sync/util.js +13 -1
  84. package/dist/sync/util.js.map +1 -1
  85. package/dist/system/ServiceContext.d.ts +20 -0
  86. package/dist/system/ServiceContext.js +29 -1
  87. package/dist/system/ServiceContext.js.map +1 -1
  88. package/dist/util/config/compound-config-collector.js +5 -0
  89. package/dist/util/config/compound-config-collector.js.map +1 -1
  90. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
  91. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
  92. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
  93. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
  94. package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
  95. package/dist/util/config/sync-rules/sync-rules-provider.js +3 -0
  96. package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
  97. package/dist/util/config/types.d.ts +1 -0
  98. package/dist/util/param-logging.d.ts +5 -2
  99. package/dist/util/param-logging.js +17 -9
  100. package/dist/util/param-logging.js.map +1 -1
  101. package/dist/util/protocol-types.d.ts +11 -11
  102. package/dist/util/protocol-types.js +6 -5
  103. package/dist/util/protocol-types.js.map +1 -1
  104. package/dist/util/utils.d.ts +2 -1
  105. package/dist/util/utils.js +16 -1
  106. package/dist/util/utils.js.map +1 -1
  107. package/package.json +6 -5
  108. package/src/api/diagnostics.ts +8 -2
  109. package/src/entry/commands/compact-action.ts +33 -25
  110. package/src/entry/commands/config-command.ts +1 -1
  111. package/src/metrics/metrics-interfaces.ts +6 -1
  112. package/src/metrics/open-telemetry/MetricAttributeFilteringExporter.ts +85 -0
  113. package/src/metrics/open-telemetry/OpenTelemetryMetricsFactory.ts +7 -2
  114. package/src/metrics/open-telemetry/util.ts +7 -3
  115. package/src/migrations/PowerSyncMigrationManager.ts +2 -1
  116. package/src/replication/AbstractReplicator.ts +42 -13
  117. package/src/replication/ReplicationModule.ts +0 -10
  118. package/src/routes/endpoints/admin.ts +17 -17
  119. package/src/routes/endpoints/socket-route.ts +9 -6
  120. package/src/routes/endpoints/sync-rules.ts +21 -12
  121. package/src/storage/BucketStorageBatch.ts +2 -1
  122. package/src/storage/BucketStorageFactory.ts +77 -14
  123. package/src/storage/PersistedReplicationStream.ts +2 -1
  124. package/src/storage/PersistedSyncConfigContent.ts +42 -19
  125. package/src/storage/ReplicationEventPayload.ts +6 -1
  126. package/src/storage/SourceEntity.ts +6 -2
  127. package/src/storage/SourceTable.ts +68 -11
  128. package/src/storage/SourceTableReconciler.ts +188 -0
  129. package/src/storage/StorageEngine.ts +10 -1
  130. package/src/storage/StorageProvider.ts +8 -0
  131. package/src/storage/StorageVersionConfig.ts +11 -1
  132. package/src/storage/SyncConfigParser.ts +121 -0
  133. package/src/storage/SyncRulesBucketStorage.ts +56 -8
  134. package/src/storage/WriteCheckpointAPI.ts +32 -3
  135. package/src/storage/implementation/BucketDefinitionMapping.ts +120 -17
  136. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +14 -5
  137. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +22 -5
  138. package/src/storage/storage-index.ts +2 -0
  139. package/src/storage/storage-metrics.ts +154 -8
  140. package/src/sync/BucketChecksumState.ts +8 -5
  141. package/src/sync/sync.ts +40 -11
  142. package/src/sync/util.ts +25 -9
  143. package/src/system/ServiceContext.ts +47 -1
  144. package/src/util/config/compound-config-collector.ts +6 -0
  145. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
  146. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
  147. package/src/util/config/sync-rules/sync-rules-provider.ts +5 -0
  148. package/src/util/config/types.ts +1 -0
  149. package/src/util/param-logging.ts +21 -14
  150. package/src/util/protocol-types.ts +8 -7
  151. package/src/util/utils.ts +15 -1
  152. package/test/src/AbstractReplicator.test.ts +62 -0
  153. package/test/src/MetricAttributeFilteringExporter.test.ts +96 -0
  154. package/test/src/PersistedSyncConfigContent.test.ts +154 -0
  155. package/test/src/SyncConfigParser.test.ts +330 -0
  156. package/test/src/broadcast_iterable.test.ts +26 -8
  157. package/test/src/config.test.ts +40 -0
  158. package/test/src/diagnostics.test.ts +48 -0
  159. package/test/src/routes/admin.test.ts +30 -2
  160. package/test/src/routes/mocks.ts +2 -0
  161. package/test/src/routes/stream.test.ts +123 -2
  162. package/test/src/source-table-reconciler.test.ts +244 -0
  163. package/test/src/storage/SourceTable.test.ts +4 -1
  164. package/test/src/storage-metrics.test.ts +148 -0
  165. package/test/src/sync/BucketChecksumState.test.ts +195 -6
  166. package/test/src/sync/util.test.ts +34 -0
  167. package/test/src/util/param-logging.test.ts +59 -0
  168. package/test/src/util/utils.test.ts +23 -0
  169. package/tsconfig.tsbuildinfo +1 -1
package/src/sync/sync.ts CHANGED
@@ -119,9 +119,14 @@ async function* streamResponseInner(
119
119
  syncRequest: params,
120
120
  logger: logger
121
121
  });
122
+ // The checkpoint iterator can have a pending next() while a data batch fails.
123
+ // Aborting this on cleanup makes that pending next() settle, so the watcher subscription
124
+ // is released instead of staying open until another checkpoint arrives. See the cleanup
125
+ // in the finally block below.
126
+ const checkpointWatchController = new AbortController();
122
127
  const stream = bucketStorage.watchCheckpointChanges({
123
128
  user_id: checkpointUserId,
124
- signal
129
+ signal: AbortSignal.any([signal, checkpointWatchController.signal])
125
130
  });
126
131
  const newCheckpoints = stream[Symbol.asyncIterator]();
127
132
 
@@ -170,6 +175,16 @@ async function* streamResponseInner(
170
175
  }
171
176
  }
172
177
 
178
+ function checkpointLogDetails(cp: storage.ReplicationCheckpoint) {
179
+ return {
180
+ checkpoint: cp.checkpoint,
181
+ user_id: tokenPayload.userIdJson,
182
+ ...tracker.getIncrementalCheckpointStats()
183
+ };
184
+ }
185
+
186
+ let activeCheckpoint: { checkpoint: storage.ReplicationCheckpoint; trace: ActiveCheckpointTrace } | null = null;
187
+
173
188
  try {
174
189
  let nextCheckpointPromise: Promise<PromiseSettledResult<IteratorResult<CheckpointAndLine>>> | undefined;
175
190
 
@@ -195,6 +210,7 @@ async function* streamResponseInner(
195
210
  const trace = next.value.value.trace!;
196
211
  const checkpoint = next.value.value.checkpoint;
197
212
  const tracer = trace.tracer;
213
+ activeCheckpoint = { checkpoint, trace };
198
214
 
199
215
  const { checkpointLine, bucketsToFetch, bucketDataRequestHint } = line;
200
216
 
@@ -266,14 +282,6 @@ async function* streamResponseInner(
266
282
  maybeRaceForNewCheckpoint();
267
283
  }
268
284
 
269
- function checkpointLogDetails(cp: storage.ReplicationCheckpoint) {
270
- return {
271
- checkpoint: cp.checkpoint,
272
- user_id: tokenPayload.userIdJson,
273
- ...tracker.getIncrementalCheckpointStats()
274
- };
275
- }
276
-
277
285
  // This incrementally updates dataBuckets with each individual bucket position.
278
286
  // At the end of this, we can be sure that all buckets have data up to the checkpoint.
279
287
  for (const [priority, buckets] of priorityBatches) {
@@ -328,13 +336,34 @@ async function* streamResponseInner(
328
336
  ms: getCheckpointTraceTimings(trace.span)
329
337
  });
330
338
  }
339
+ if (checkpointResult != null) {
340
+ activeCheckpoint = null;
341
+ }
331
342
 
332
343
  if (!abortCheckpointSignal.aborted) {
333
344
  await new Promise((resolve) => setTimeout(resolve, 10));
334
345
  }
335
346
  } while (!signal.aborted);
336
347
  } finally {
337
- await newCheckpoints.return?.();
348
+ if (activeCheckpoint != null) {
349
+ const { checkpoint, trace } = activeCheckpoint;
350
+ logger.info(`checkpoint_interrupted: ${checkpoint.checkpoint}`, {
351
+ ...checkpointLogDetails(checkpoint),
352
+ ms: getCheckpointTraceTimings(trace.span)
353
+ });
354
+ }
355
+
356
+ // The abort makes a pending next() settle as soon as the storage watcher observes it,
357
+ // releasing the subscription. return() is still needed for the case where there is no
358
+ // pending next(): the watcher is then suspended at a yield and never observes the abort.
359
+ // Neither is awaited: async generators queue return() behind a pending next(), so
360
+ // awaiting it here would keep the connection open until the next checkpoint arrives.
361
+ checkpointWatchController.abort();
362
+ newCheckpoints.return?.().catch((e) => {
363
+ if (!isAbortError(e)) {
364
+ logger.warn('Error while closing the checkpoint watcher', e);
365
+ }
366
+ });
338
367
  }
339
368
  }
340
369
 
@@ -437,7 +466,6 @@ async function* bucketDataBatch(
437
466
  } = request;
438
467
 
439
468
  const tracer = request.tracer;
440
-
441
469
  let checkpointInvalidated = false;
442
470
 
443
471
  const acquired = await tracer.span('acquiring_lock').with(async () => {
@@ -456,6 +484,7 @@ async function* bucketDataBatch(
456
484
  const filteredBuckets = checkpointLine.getFilteredBucketPositions(bucketsToFetch);
457
485
  const dataBatches = storage.getBucketDataBatch(checkpoint, filteredBuckets, {
458
486
  requestHint,
487
+ tracer,
459
488
  // Checkpoint supersession is a cooperative batch handoff. Only abort
460
489
  // in-flight storage work when the connection itself is closed.
461
490
  signal: abort_connection
package/src/sync/util.ts CHANGED
@@ -144,9 +144,19 @@ export async function* transformToBytesTracked(
144
144
 
145
145
  export function acquireSemaphoreAbortable(
146
146
  semaphone: SemaphoreInterface,
147
- abort: AbortSignal
147
+ abort?: AbortSignal
148
148
  ): Promise<[number, SemaphoreInterface.Releaser] | 'aborted'> {
149
+ if (abort == null) {
150
+ return semaphone.acquire();
151
+ }
149
152
  return new Promise((resolve, reject) => {
153
+ // An already-aborted signal never fires its listener, and we would wait for the semaphore
154
+ // indefinitely.
155
+ if (abort.aborted) {
156
+ resolve('aborted');
157
+ return;
158
+ }
159
+
150
160
  let aborted = false;
151
161
  let hasSemaphore = false;
152
162
 
@@ -159,16 +169,22 @@ export function acquireSemaphoreAbortable(
159
169
  };
160
170
  abort.addEventListener('abort', listener);
161
171
 
162
- semaphone.acquire().then((acquired) => {
163
- hasSemaphore = true;
164
- if (aborted) {
165
- // Release semaphore, already aborted
166
- acquired[1]();
167
- } else {
172
+ semaphone.acquire().then(
173
+ (acquired) => {
174
+ hasSemaphore = true;
175
+ if (aborted) {
176
+ // Release semaphore, already aborted
177
+ acquired[1]();
178
+ } else {
179
+ abort.removeEventListener('abort', listener);
180
+ resolve(acquired);
181
+ }
182
+ },
183
+ (error) => {
168
184
  abort.removeEventListener('abort', listener);
169
- resolve(acquired);
185
+ reject(error);
170
186
  }
171
- }, reject);
187
+ );
172
188
  });
173
189
  }
174
190
 
@@ -1,4 +1,5 @@
1
1
  import { container, LifeCycledSystem, MigrationManager, ServiceIdentifier } from '@powersync/lib-services-framework';
2
+ import type { AdditionalSyncConfigParser } from '@powersync/service-sync-rules';
2
3
 
3
4
  import { EventsEngine } from '../events/EventsEngine.js';
4
5
  import { framework } from '../index.js';
@@ -10,6 +11,16 @@ import * as storage from '../storage/storage-index.js';
10
11
  import { SyncContext } from '../sync/SyncContext.js';
11
12
  import * as utils from '../util/util-index.js';
12
13
 
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
+
13
24
  export interface ServiceContext {
14
25
  configuration: utils.ResolvedPowerSyncConfig;
15
26
  lifeCycleEngine: LifeCycledSystem;
@@ -22,6 +33,11 @@ export interface ServiceContext {
22
33
  writeCheckpointBatcher: utils.WriteCheckpointBatcher;
23
34
  serviceMode: ServiceContextMode;
24
35
  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;
25
41
  }
26
42
 
27
43
  export enum ServiceContextMode {
@@ -53,16 +69,20 @@ export class ServiceContextContainer implements ServiceContext {
53
69
  routerEngine: routes.RouterEngine;
54
70
  writeCheckpointBatcher: utils.WriteCheckpointBatcher;
55
71
  serviceMode: ServiceContextMode;
72
+ readonly #syncConfigParser: ServiceContextSyncConfigParser;
56
73
 
57
74
  constructor(options: ServiceContextOptions) {
58
75
  this.serviceMode = options.serviceMode;
59
76
  const { configuration } = options;
60
77
  this.configuration = configuration;
61
78
 
79
+ this.#syncConfigParser = new ServiceContextSyncConfigParserImpl(() => this.storageEngine.started);
80
+
62
81
  this.lifeCycleEngine = new LifeCycledSystem();
63
82
 
64
83
  this.storageEngine = new storage.StorageEngine({
65
- configuration
84
+ configuration,
85
+ syncConfigParser: this.#syncConfigParser
66
86
  });
67
87
  this.storageEngine.registerListener({
68
88
  storageFatalError: (error) => {
@@ -114,6 +134,13 @@ export class ServiceContextContainer implements ServiceContext {
114
134
  return container.getOptional(replication.ReplicationEngine);
115
135
  }
116
136
 
137
+ /**
138
+ * Returns the service-wide parser shared by routes, replication, and storage.
139
+ */
140
+ get syncConfigParser(): ServiceContextSyncConfigParser {
141
+ return this.#syncConfigParser;
142
+ }
143
+
117
144
  get metricsEngine(): metrics.MetricsEngine {
118
145
  return container.getImplementation(metrics.MetricsEngine);
119
146
  }
@@ -137,3 +164,22 @@ export class ServiceContextContainer implements ServiceContext {
137
164
  return container.getImplementation(identifier);
138
165
  }
139
166
  }
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,4 +1,5 @@
1
1
  import { logger, LookupOptions } from '@powersync/lib-services-framework';
2
+ import { validateStorageVersion } from '@powersync/service-sync-rules';
2
3
  import { configFile } from '@powersync/service-types';
3
4
  import * as auth from '../../auth/auth-index.js';
4
5
  import { ConfigCollector } from './collectors/config-collector.js';
@@ -62,6 +63,11 @@ export class CompoundConfigCollector {
62
63
  async collectConfig(runnerConfig: RunnerConfig = {}): Promise<ResolvedPowerSyncConfig> {
63
64
  const baseConfig = await this.collectBaseConfig(runnerConfig);
64
65
 
66
+ const defaultStorageVersion = baseConfig.storage?.default_storage_version;
67
+ if (defaultStorageVersion != null && validateStorageVersion(defaultStorageVersion) == null) {
68
+ throw new Error(`Storage version ${defaultStorageVersion} is not supported`);
69
+ }
70
+
65
71
  const dataSources = baseConfig.replication?.connections ?? [];
66
72
  if (dataSources.length > 1) {
67
73
  throw new Error('Only a single replication data source is supported currently');
@@ -15,6 +15,7 @@ export class Base64SyncRulesCollector extends SyncRulesCollector {
15
15
 
16
16
  return {
17
17
  present: true,
18
+ version_label: baseConfig.sync_config?.version_label,
18
19
  exit_on_error: baseConfig.sync_config?.exit_on_error ?? true,
19
20
  content: Buffer.from(sync_config_base64, 'base64').toString()
20
21
  };
@@ -20,6 +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
+ version_label: baseConfig.sync_config?.version_label,
23
24
  exit_on_error: baseConfig.sync_config?.exit_on_error ?? true,
24
25
  path: config_path ? path.resolve(path.dirname(config_path), sync_path) : sync_path
25
26
  };
@@ -5,6 +5,7 @@ export interface SyncRulesProvider {
5
5
  get(): Promise<string | undefined>;
6
6
 
7
7
  readonly exitOnError: boolean;
8
+ readonly versionLabel: string | undefined;
8
9
  }
9
10
 
10
11
  export class ConfigurationFileSyncRulesProvider implements SyncRulesProvider {
@@ -21,4 +22,8 @@ export class ConfigurationFileSyncRulesProvider implements SyncRulesProvider {
21
22
  get exitOnError() {
22
23
  return this.config.exit_on_error;
23
24
  }
25
+
26
+ get versionLabel() {
27
+ return this.config.version_label;
28
+ }
24
29
  }
@@ -22,6 +22,7 @@ export type Runner = (config: RunnerConfig) => Promise<void>;
22
22
 
23
23
  export type SyncRulesConfig = {
24
24
  present: boolean;
25
+ version_label?: string;
25
26
  content?: string;
26
27
  path?: string;
27
28
  exit_on_error: boolean;
@@ -18,8 +18,9 @@ export const DEFAULT_PARAM_LOGGING_FORMAT_OPTIONS: ParamLoggingFormatOptions = {
18
18
  * Formats potentially arbitrary parameters for logging.
19
19
  * This limits the number of keys and strings to a maximum length.
20
20
  * A warning key-value is added if the number of keys exceeds the maximum.
21
- * String values exceeding the maximum length are truncated.
21
+ * Keys and string values exceeding the maximum length are truncated.
22
22
  * Non-String values are stringified, the maximum length is then applied.
23
+ * Values that cannot be serialized are replaced with a placeholder.
23
24
  * @param params - The parameters to format.
24
25
  * @param options - The options to use.
25
26
  * @default DEFAULT_PARAM_LOGGING_FORMAT_OPTIONS
@@ -41,20 +42,26 @@ export function limitParamsForLogging(
41
42
  return value;
42
43
  }
43
44
 
44
- return Object.fromEntries(
45
- Object.entries(params).map(([key, value], index) => {
46
- if (index == maxKeyCount) {
47
- return ['⚠️', 'Additional parameters omitted'];
48
- }
45
+ function formatValue(value: unknown): string {
46
+ if (typeof value == 'string') {
47
+ return trimString(value);
48
+ }
49
+ try {
50
+ return trimString(JSON.stringify(value) ?? '[undefined]');
51
+ } catch {
52
+ return trimString('[unserializable]');
53
+ }
54
+ }
49
55
 
50
- if (index > maxKeyCount) {
51
- return [];
52
- }
56
+ return Object.fromEntries(
57
+ Object.entries(params)
58
+ .slice(0, maxKeyCount + 1)
59
+ .map(([key, value], index) => {
60
+ if (index == maxKeyCount) {
61
+ return ['⚠️', 'Additional parameters omitted'];
62
+ }
53
63
 
54
- if (typeof value == 'string') {
55
- return [key, trimString(value)];
56
- }
57
- return [key, trimString(JSON.stringify(value))];
58
- })
64
+ return [trimString(key), formatValue(value)];
65
+ })
59
66
  );
60
67
  }
@@ -1,5 +1,6 @@
1
1
  import { JsonContainer } from '@powersync/service-jsonbig';
2
2
  import { BucketPriority, SqliteJsonRow } from '@powersync/service-sync-rules';
3
+ import { orNull } from '@powersync/service-types';
3
4
  import * as t from 'ts-codec';
4
5
 
5
6
  export const BucketRequest = t.object({
@@ -18,20 +19,20 @@ export type BucketRequest = t.Decoded<typeof BucketRequest>;
18
19
  */
19
20
  export const RequestedStreamSubscription = t.object({
20
21
  /**
21
- * The defined name of the stream as it appears in sync stream definitions.
22
+ * The defined name of the stream as it appears in Sync Stream definitions.
22
23
  */
23
24
  stream: t.string,
24
25
  /**
25
26
  * An optional dictionary of parameters to pass to this specific stream.
26
27
  */
27
- parameters: t.union(t.record(t.any), t.Null),
28
+ parameters: orNull(t.record(t.any)),
28
29
  /**
29
30
  * Set when the client wishes to re-assign a different priority to this stream.
30
31
  *
31
- * Streams and sync rules can also assign a default priority, but clients are allowed to override those. This can be
32
+ * Sync Streams and legacy bucket definitions can also assign a default priority, but clients are allowed to override those. This can be
32
33
  * useful when the priority for partial syncs depends on e.g. the current page opened in a client.
33
34
  */
34
- override_priority: t.union(t.number, t.Null)
35
+ override_priority: orNull(t.number)
35
36
  });
36
37
 
37
38
  export type RequestedStreamSubscription = t.Decoded<typeof RequestedStreamSubscription>;
@@ -48,7 +49,7 @@ export const StreamSubscriptionRequest = t.object({
48
49
  include_defaults: t.boolean.optional(),
49
50
 
50
51
  /**
51
- * An array of sync streams the client has opened explicitly.
52
+ * An array of Sync Streams the client has opened explicitly.
52
53
  */
53
54
  subscriptions: t.array(RequestedStreamSubscription)
54
55
  });
@@ -252,8 +253,8 @@ export interface BucketChecksum {
252
253
  /**
253
254
  * The reason a particular bucket is included in a checkpoint.
254
255
  *
255
- * This information allows clients to associate individual buckets with sync streams they're subscribed to. Having that
256
- * association is useful because it enables clients to track progress for individual sync streams.
256
+ * This information allows clients to associate individual buckets with Sync Streams they're subscribed to. Having that
257
+ * association is useful because it enables clients to track progress for individual Sync Streams.
257
258
  */
258
259
  export type BucketSubscriptionReason = BucketDerivedFromDefaultStream | BucketDerivedFromExplicitSubscription;
259
260
 
package/src/util/utils.ts CHANGED
@@ -33,7 +33,7 @@ export interface PartialChecksum {
33
33
  */
34
34
  export type InternalOpId = bigint;
35
35
 
36
- export const ID_NAMESPACE = 'a396dd91-09fc-4017-a28d-3df722f651e9';
36
+ export const ID_NAMESPACE = uuid.parse('a396dd91-09fc-4017-a28d-3df722f651e9');
37
37
 
38
38
  export function escapeIdentifier(identifier: string) {
39
39
  return `"${identifier.replace(/"/g, '""').replace(/\./g, '"."')}"`;
@@ -309,3 +309,17 @@ export function estimateRowSize(record: sync_rules.ToastableSqliteRow | undefine
309
309
  }
310
310
  return size;
311
311
  }
312
+
313
+ export function formatBytes(bytes: number | bigint): string {
314
+ if (typeof bytes == 'bigint') {
315
+ bytes = Number(bytes); // We round either way
316
+ }
317
+ if (bytes >= 1024 * 1024 * 1024) {
318
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;
319
+ } else if (bytes >= 1024 * 1024) {
320
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
321
+ } else if (bytes >= 1024) {
322
+ return `${(bytes / 1024).toFixed(1)}KB`;
323
+ }
324
+ return `${bytes}B`;
325
+ }
@@ -40,8 +40,48 @@ class TestReplicator extends AbstractReplicator {
40
40
  addClearingJob(replicationStreamId: number, promise: Promise<void>): void {
41
41
  this.clearingJobs.set(replicationStreamId, promise);
42
42
  }
43
+
44
+ get heartbeatIntervalNanosForTest(): bigint | null {
45
+ return (this as any).heartbeatIntervalNanos;
46
+ }
47
+
48
+ shouldHandleStreamForTest(
49
+ replicationStream: PersistedReplicationStream,
50
+ loadedSyncRules: string | undefined,
51
+ loadedVersionLabel: string | undefined
52
+ ): boolean {
53
+ return (this as any).shouldHandleReplicationStream(replicationStream, loadedSyncRules, loadedVersionLabel);
54
+ }
43
55
  }
44
56
 
57
+ describe('AbstractReplicator heartbeat interval', () => {
58
+ const options: AbstractReplicatorOptions = {
59
+ id: 'test',
60
+ storageEngine: {} as AbstractReplicatorOptions['storageEngine'],
61
+ metricsEngine: {} as AbstractReplicatorOptions['metricsEngine'],
62
+ syncRuleProvider: {} as AbstractReplicatorOptions['syncRuleProvider'],
63
+ rateLimiter: {} as AbstractReplicatorOptions['rateLimiter']
64
+ };
65
+
66
+ it.each([undefined, null])('uses the default for %s', (heartbeatIntervalSeconds) => {
67
+ const replicator = new TestReplicator(async () => {}, { ...options, heartbeatIntervalSeconds });
68
+
69
+ expect(replicator.heartbeatIntervalNanosForTest).toBe(60_000_000_000n);
70
+ });
71
+
72
+ it('disables the heartbeat interval with 0', () => {
73
+ const replicator = new TestReplicator(async () => {}, { ...options, heartbeatIntervalSeconds: 0 });
74
+
75
+ expect(replicator.heartbeatIntervalNanosForTest).toBeNull();
76
+ });
77
+
78
+ it('converts a positive heartbeat interval to nanoseconds', () => {
79
+ const replicator = new TestReplicator(async () => {}, { ...options, heartbeatIntervalSeconds: 5 });
80
+
81
+ expect(replicator.heartbeatIntervalNanosForTest).toBe(5_000_000_000n);
82
+ });
83
+ });
84
+
45
85
  describe('AbstractReplicator stopped stream cleanup', () => {
46
86
  it('holds the replication stream lock across source and storage cleanup', async () => {
47
87
  const calls: string[] = [];
@@ -113,3 +153,25 @@ describe('AbstractReplicator stopped stream cleanup', () => {
113
153
  expect(stopped).toBe(true);
114
154
  });
115
155
  });
156
+
157
+ describe('AbstractReplicator rolling deployment config matching', () => {
158
+ const processingStream = (version_label: string | undefined): PersistedReplicationStream =>
159
+ ({
160
+ syncConfigContent: [
161
+ {
162
+ syncConfigState: 'PROCESSING',
163
+ sync_rules_content: 'bucket_definitions: {}',
164
+ version_label
165
+ }
166
+ ]
167
+ }) as unknown as PersistedReplicationStream;
168
+
169
+ it('requires both YAML and version label to match a processing config', () => {
170
+ const replicator = new TestReplicator(async () => {});
171
+ const stream = processingStream('v2');
172
+
173
+ expect(replicator.shouldHandleStreamForTest(stream, 'bucket_definitions: {}', 'v2')).toBe(true);
174
+ expect(replicator.shouldHandleStreamForTest(stream, 'bucket_definitions: {}', 'v1')).toBe(false);
175
+ expect(replicator.shouldHandleStreamForTest(stream, 'bucket_definitions: {}', undefined)).toBe(false);
176
+ });
177
+ });
@@ -0,0 +1,96 @@
1
+ import { MetricAttributeFilteringExporter } from '@/metrics/open-telemetry/MetricAttributeFilteringExporter.js';
2
+ import { Attributes } from '@opentelemetry/api';
3
+ import { ExportResult } from '@opentelemetry/core';
4
+ import { DataPointType, PushMetricExporter, ResourceMetrics } from '@opentelemetry/sdk-metrics';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+
7
+ type ExportMetrics = (metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void) => void;
8
+
9
+ describe('MetricAttributeFilteringExporter', () => {
10
+ it('filters configured attributes without changing the collected metrics', () => {
11
+ const exportMetrics = vi.fn<ExportMetrics>();
12
+ const delegate = {
13
+ export: exportMetrics,
14
+ forceFlush: vi.fn(async () => {}),
15
+ shutdown: vi.fn(async () => {})
16
+ } satisfies PushMetricExporter;
17
+ const exporter = new MetricAttributeFilteringExporter(delegate, new Set(['version_label']));
18
+ const attributes: Attributes = {
19
+ sync_config_id: 'config-a',
20
+ sync_config_state: 'ACTIVE',
21
+ version_label: 'customer-version'
22
+ };
23
+ const metrics = {
24
+ resource: {},
25
+ scopeMetrics: [
26
+ {
27
+ scope: {},
28
+ metrics: [
29
+ {
30
+ dataPointType: DataPointType.GAUGE,
31
+ dataPoints: [{ attributes, value: 100 }]
32
+ }
33
+ ]
34
+ }
35
+ ]
36
+ } as unknown as ResourceMetrics;
37
+ const callback = vi.fn();
38
+
39
+ exporter.export(metrics, callback);
40
+
41
+ expect(exportMetrics).toHaveBeenCalledWith(
42
+ expect.objectContaining({
43
+ scopeMetrics: [
44
+ expect.objectContaining({
45
+ metrics: [
46
+ expect.objectContaining({
47
+ dataPoints: [
48
+ expect.objectContaining({
49
+ attributes: { sync_config_id: 'config-a', sync_config_state: 'ACTIVE' }
50
+ })
51
+ ]
52
+ })
53
+ ]
54
+ })
55
+ ]
56
+ }),
57
+ callback
58
+ );
59
+ expect(metrics.scopeMetrics[0].metrics[0].dataPoints[0].attributes).toBe(attributes);
60
+ });
61
+
62
+ it('forwards rather than merges data points whose attributes become identical', () => {
63
+ const exportMetrics = vi.fn<ExportMetrics>();
64
+ const delegate = {
65
+ export: exportMetrics,
66
+ forceFlush: vi.fn(async () => {}),
67
+ shutdown: vi.fn(async () => {})
68
+ } satisfies PushMetricExporter;
69
+ const exporter = new MetricAttributeFilteringExporter(delegate, new Set(['filtered']));
70
+ const metrics = {
71
+ resource: {},
72
+ scopeMetrics: [
73
+ {
74
+ scope: {},
75
+ metrics: [
76
+ {
77
+ dataPointType: DataPointType.GAUGE,
78
+ dataPoints: [
79
+ { attributes: { retained: 'same', filtered: 'a' }, value: 10 },
80
+ { attributes: { retained: 'same', filtered: 'b' }, value: 20 }
81
+ ]
82
+ }
83
+ ]
84
+ }
85
+ ]
86
+ } as unknown as ResourceMetrics;
87
+
88
+ exporter.export(metrics, vi.fn());
89
+
90
+ const exported = exportMetrics.mock.calls[0][0];
91
+ expect(exported.scopeMetrics[0].metrics[0].dataPoints).toMatchObject([
92
+ { attributes: { retained: 'same' }, value: 10 },
93
+ { attributes: { retained: 'same' }, value: 20 }
94
+ ]);
95
+ });
96
+ });