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

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 (183) hide show
  1. package/CHANGELOG.md +83 -4
  2. package/dist/api/RouteAPI.d.ts +42 -14
  3. package/dist/api/diagnostics.d.ts +12 -1
  4. package/dist/api/diagnostics.js +34 -22
  5. package/dist/api/diagnostics.js.map +1 -1
  6. package/dist/entry/commands/compact-action.js +5 -1
  7. package/dist/entry/commands/compact-action.js.map +1 -1
  8. package/dist/modules/AbstractModule.d.ts +6 -2
  9. package/dist/modules/AbstractModule.js.map +1 -1
  10. package/dist/replication/AbstractReplicator.d.ts +26 -7
  11. package/dist/replication/AbstractReplicator.js +148 -68
  12. package/dist/replication/AbstractReplicator.js.map +1 -1
  13. package/dist/replication/ReplicationModule.d.ts +3 -3
  14. package/dist/replication/ReplicationModule.js.map +1 -1
  15. package/dist/routes/RouterEngine.d.ts +1 -0
  16. package/dist/routes/RouterEngine.js +6 -1
  17. package/dist/routes/RouterEngine.js.map +1 -1
  18. package/dist/routes/configure-fastify.d.ts +95 -56
  19. package/dist/routes/configure-fastify.js +15 -2
  20. package/dist/routes/configure-fastify.js.map +1 -1
  21. package/dist/routes/endpoints/admin.d.ts +24 -24
  22. package/dist/routes/endpoints/admin.js +46 -35
  23. package/dist/routes/endpoints/admin.js.map +1 -1
  24. package/dist/routes/endpoints/checkpointing.d.ts +62 -0
  25. package/dist/routes/endpoints/checkpointing.js +65 -7
  26. package/dist/routes/endpoints/checkpointing.js.map +1 -1
  27. package/dist/routes/endpoints/socket-route.js +3 -2
  28. package/dist/routes/endpoints/socket-route.js.map +1 -1
  29. package/dist/routes/endpoints/sync-rules.js +22 -13
  30. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  31. package/dist/routes/endpoints/sync-stream.js +1 -1
  32. package/dist/routes/endpoints/sync-stream.js.map +1 -1
  33. package/dist/runner/teardown.js +8 -8
  34. package/dist/runner/teardown.js.map +1 -1
  35. package/dist/storage/BucketStorageBatch.d.ts +63 -17
  36. package/dist/storage/BucketStorageBatch.js.map +1 -1
  37. package/dist/storage/BucketStorageFactory.d.ts +22 -27
  38. package/dist/storage/BucketStorageFactory.js +4 -18
  39. package/dist/storage/BucketStorageFactory.js.map +1 -1
  40. package/dist/storage/CheckpointChecksumInvalidatedError.d.ts +12 -0
  41. package/dist/storage/CheckpointChecksumInvalidatedError.js +17 -0
  42. package/dist/storage/CheckpointChecksumInvalidatedError.js.map +1 -0
  43. package/dist/storage/ChecksumCache.d.ts +11 -6
  44. package/dist/storage/ChecksumCache.js +5 -4
  45. package/dist/storage/ChecksumCache.js.map +1 -1
  46. package/dist/storage/ParsedSyncConfigSet.d.ts +23 -0
  47. package/dist/storage/ParsedSyncConfigSet.js +2 -0
  48. package/dist/storage/ParsedSyncConfigSet.js.map +1 -0
  49. package/dist/storage/PersistedReplicationStream.d.ts +32 -0
  50. package/dist/storage/PersistedReplicationStream.js +26 -0
  51. package/dist/storage/PersistedReplicationStream.js.map +1 -0
  52. package/dist/storage/PersistedSyncConfigContent.d.ts +63 -0
  53. package/dist/storage/PersistedSyncConfigContent.js +125 -0
  54. package/dist/storage/PersistedSyncConfigContent.js.map +1 -0
  55. package/dist/storage/PersistedSyncConfigStatus.d.ts +13 -0
  56. package/dist/storage/PersistedSyncConfigStatus.js +2 -0
  57. package/dist/storage/PersistedSyncConfigStatus.js.map +1 -0
  58. package/dist/storage/SourceEntity.d.ts +6 -0
  59. package/dist/storage/SourceTable.d.ts +21 -3
  60. package/dist/storage/SourceTable.js +26 -3
  61. package/dist/storage/SourceTable.js.map +1 -1
  62. package/dist/storage/SyncRulesBucketStorage.d.ts +119 -21
  63. package/dist/storage/SyncRulesBucketStorage.js +3 -0
  64. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  65. package/dist/storage/WriteCheckpointAPI.d.ts +60 -3
  66. package/dist/storage/WriteCheckpointAPI.js +33 -0
  67. package/dist/storage/WriteCheckpointAPI.js.map +1 -1
  68. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +117 -0
  69. package/dist/storage/implementation/BucketDefinitionMapping.js +277 -0
  70. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -0
  71. package/dist/storage/implementation/IncrementalReprocessingCompatibility.d.ts +6 -0
  72. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +31 -0
  73. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -0
  74. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.d.ts +17 -0
  75. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +62 -0
  76. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -0
  77. package/dist/storage/implementation/ReplicationStreamStorageIds.d.ts +15 -0
  78. package/dist/storage/implementation/ReplicationStreamStorageIds.js +20 -0
  79. package/dist/storage/implementation/ReplicationStreamStorageIds.js.map +1 -0
  80. package/dist/storage/storage-index.d.ts +9 -1
  81. package/dist/storage/storage-index.js +9 -1
  82. package/dist/storage/storage-index.js.map +1 -1
  83. package/dist/sync/BucketChecksumState.d.ts +12 -2
  84. package/dist/sync/BucketChecksumState.js +69 -21
  85. package/dist/sync/BucketChecksumState.js.map +1 -1
  86. package/dist/sync/RequestTracker.d.ts +7 -0
  87. package/dist/sync/RequestTracker.js +12 -0
  88. package/dist/sync/RequestTracker.js.map +1 -1
  89. package/dist/sync/sync.js +154 -41
  90. package/dist/sync/sync.js.map +1 -1
  91. package/dist/sync/util.d.ts +5 -0
  92. package/dist/sync/util.js +9 -0
  93. package/dist/sync/util.js.map +1 -1
  94. package/dist/system/ServiceContext.d.ts +2 -0
  95. package/dist/system/ServiceContext.js +2 -0
  96. package/dist/system/ServiceContext.js.map +1 -1
  97. package/dist/tracing/PerformanceTracer.d.ts +23 -1
  98. package/dist/tracing/PerformanceTracer.js +11 -0
  99. package/dist/tracing/PerformanceTracer.js.map +1 -1
  100. package/dist/util/checkpointing.d.ts +4 -8
  101. package/dist/util/checkpointing.js +1 -16
  102. package/dist/util/checkpointing.js.map +1 -1
  103. package/dist/util/config/compound-config-collector.js +18 -2
  104. package/dist/util/config/compound-config-collector.js.map +1 -1
  105. package/dist/util/config/defaults.d.ts +2 -0
  106. package/dist/util/config/defaults.js +2 -0
  107. package/dist/util/config/defaults.js.map +1 -1
  108. package/dist/util/config/types.d.ts +3 -1
  109. package/dist/util/lsn.d.ts +4 -0
  110. package/dist/util/lsn.js +10 -0
  111. package/dist/util/lsn.js.map +1 -1
  112. package/dist/util/util-index.d.ts +1 -0
  113. package/dist/util/util-index.js +1 -0
  114. package/dist/util/util-index.js.map +1 -1
  115. package/dist/util/utils.d.ts +1 -1
  116. package/dist/util/utils.js +1 -1
  117. package/dist/util/write-checkpoint-batcher.d.ts +19 -0
  118. package/dist/util/write-checkpoint-batcher.js +100 -0
  119. package/dist/util/write-checkpoint-batcher.js.map +1 -0
  120. package/package.json +6 -7
  121. package/src/api/RouteAPI.ts +43 -14
  122. package/src/api/diagnostics.ts +43 -26
  123. package/src/entry/commands/compact-action.ts +7 -1
  124. package/src/modules/AbstractModule.ts +6 -2
  125. package/src/replication/AbstractReplicator.ts +181 -72
  126. package/src/replication/ReplicationModule.ts +2 -3
  127. package/src/routes/RouterEngine.ts +7 -1
  128. package/src/routes/configure-fastify.ts +25 -2
  129. package/src/routes/endpoints/admin.ts +72 -50
  130. package/src/routes/endpoints/checkpointing.ts +79 -8
  131. package/src/routes/endpoints/socket-route.ts +3 -2
  132. package/src/routes/endpoints/sync-rules.ts +23 -13
  133. package/src/routes/endpoints/sync-stream.ts +1 -1
  134. package/src/runner/teardown.ts +8 -8
  135. package/src/storage/BucketStorageBatch.ts +64 -18
  136. package/src/storage/BucketStorageFactory.ts +30 -39
  137. package/src/storage/CheckpointChecksumInvalidatedError.ts +17 -0
  138. package/src/storage/ChecksumCache.ts +27 -14
  139. package/src/storage/ParsedSyncConfigSet.ts +25 -0
  140. package/src/storage/PersistedReplicationStream.ts +55 -0
  141. package/src/storage/PersistedSyncConfigContent.ts +192 -0
  142. package/src/storage/PersistedSyncConfigStatus.ts +14 -0
  143. package/src/storage/SourceEntity.ts +6 -0
  144. package/src/storage/SourceTable.ts +34 -3
  145. package/src/storage/SyncRulesBucketStorage.ts +138 -22
  146. package/src/storage/WriteCheckpointAPI.ts +108 -3
  147. package/src/storage/implementation/BucketDefinitionMapping.ts +436 -0
  148. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +41 -0
  149. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +109 -0
  150. package/src/storage/implementation/ReplicationStreamStorageIds.ts +21 -0
  151. package/src/storage/storage-index.ts +10 -1
  152. package/src/sync/BucketChecksumState.ts +103 -21
  153. package/src/sync/RequestTracker.ts +20 -0
  154. package/src/sync/sync.ts +183 -48
  155. package/src/sync/util.ts +12 -0
  156. package/src/system/ServiceContext.ts +7 -0
  157. package/src/tracing/PerformanceTracer.ts +41 -1
  158. package/src/util/checkpointing.ts +4 -22
  159. package/src/util/config/compound-config-collector.ts +25 -1
  160. package/src/util/config/defaults.ts +2 -0
  161. package/src/util/config/types.ts +3 -1
  162. package/src/util/lsn.ts +9 -0
  163. package/src/util/util-index.ts +1 -0
  164. package/src/util/utils.ts +1 -1
  165. package/src/util/write-checkpoint-batcher.ts +142 -0
  166. package/test/src/AbstractReplicator.test.ts +115 -0
  167. package/test/src/checksum_cache.test.ts +22 -0
  168. package/test/src/config.test.ts +102 -0
  169. package/test/src/diagnostics.test.ts +62 -34
  170. package/test/src/module-loader.test.ts +33 -1
  171. package/test/src/routes/admin.test.ts +182 -18
  172. package/test/src/routes/checkpointing.test.ts +54 -0
  173. package/test/src/routes/mocks.ts +6 -2
  174. package/test/src/storage/SourceTable.test.ts +89 -0
  175. package/test/src/sync/BucketChecksumState.test.ts +98 -12
  176. package/test/src/sync/util.test.ts +13 -1
  177. package/test/src/util/checkpointing.test.ts +249 -0
  178. package/tsconfig.json +1 -4
  179. package/tsconfig.tsbuildinfo +1 -1
  180. package/dist/storage/PersistedSyncRulesContent.d.ts +0 -59
  181. package/dist/storage/PersistedSyncRulesContent.js +0 -100
  182. package/dist/storage/PersistedSyncRulesContent.js.map +0 -1
  183. package/src/storage/PersistedSyncRulesContent.ts +0 -174
package/src/sync/sync.ts CHANGED
@@ -1,18 +1,25 @@
1
1
  import { JSONBig, JsonContainer } from '@powersync/service-jsonbig';
2
2
  import { BucketPriority, HydratedSyncConfig, ResolvedBucket, SqliteJsonValue } from '@powersync/service-sync-rules';
3
3
 
4
- import { AbortError } from 'ix/aborterror.js';
5
-
6
4
  import * as auth from '../auth/auth-index.js';
7
5
  import * as storage from '../storage/storage-index.js';
8
6
  import * as util from '../util/util-index.js';
9
7
 
10
8
  import { Logger, logger as defaultLogger } from '@powersync/lib-services-framework';
9
+ import { isBatchEnd } from '../storage/storage-index.js';
11
10
  import { mergeAsyncIterables } from '../streams/streams-index.js';
12
- import { BucketChecksumState, CheckpointLine } from './BucketChecksumState.js';
11
+ import { PerformanceTracer, type Span } from '../tracing/PerformanceTracer.js';
12
+ import { BucketChecksumState, CheckpointLine, type SyncCheckpointTraceCategory } from './BucketChecksumState.js';
13
13
  import { OperationsSentStats, RequestTracker, statsForBatch } from './RequestTracker.js';
14
14
  import { SyncContext } from './SyncContext.js';
15
- import { TokenStreamOptions, acquireSemaphoreAbortable, settledPromise, tokenStream } from './util.js';
15
+ import { TokenStreamOptions, acquireSemaphoreAbortable, isAbortError, settledPromise, tokenStream } from './util.js';
16
+
17
+ type CheckpointTiming = Record<string, number>;
18
+
19
+ interface ActiveCheckpointTrace {
20
+ tracer: PerformanceTracer<SyncCheckpointTraceCategory>;
21
+ span: Span;
22
+ }
16
23
 
17
24
  export interface SyncStreamParameters {
18
25
  syncContext: SyncContext;
@@ -79,7 +86,7 @@ export async function* streamResponse(
79
86
  try {
80
87
  yield* merged;
81
88
  } catch (e) {
82
- if (e instanceof AbortError) {
89
+ if (isAbortError(e)) {
83
90
  return;
84
91
  } else {
85
92
  throw e;
@@ -119,8 +126,9 @@ async function* streamResponseInner(
119
126
  const newCheckpoints = stream[Symbol.asyncIterator]();
120
127
 
121
128
  type CheckpointAndLine = {
122
- checkpoint: bigint;
129
+ checkpoint: storage.ReplicationCheckpoint;
123
130
  line: CheckpointLine | null;
131
+ trace: ActiveCheckpointTrace | null;
124
132
  };
125
133
 
126
134
  async function waitForNewCheckpointLine(): Promise<IteratorResult<CheckpointAndLine>> {
@@ -128,9 +136,38 @@ async function* streamResponseInner(
128
136
  if (next.done) {
129
137
  return { done: true, value: undefined };
130
138
  }
139
+ const cp = next.value.base;
140
+
141
+ const tracer = new PerformanceTracer<SyncCheckpointTraceCategory>(`sync checkpoint ${cp.checkpoint}`);
142
+ const trace = {
143
+ tracer,
144
+ span: tracer.span('checkpoint')
145
+ };
131
146
 
132
- const line = await checksumState.buildNextCheckpointLine(next.value);
133
- return { done: false, value: { checkpoint: next.value.base.checkpoint, line } };
147
+ try {
148
+ const line = await checksumState.buildNextCheckpointLine(next.value, trace.tracer);
149
+ return { done: false, value: { checkpoint: cp, line, trace: line == null ? null : trace } };
150
+ } catch (e) {
151
+ if (e instanceof storage.CheckpointChecksumInvalidatedError) {
152
+ // The checksum was not usable, so buildNextCheckpointLine has not advanced
153
+ // the connection state. Drop this candidate and wait for a checkpoint that
154
+ // is not split by a compaction-produced bucket-data document.
155
+ // This is different from other checkpoint_invalidated cases in that we hit
156
+ // this during checksum calculation, instead of on data read.
157
+ trace.span.end();
158
+ checksumState.invalidateChecksumBaseline();
159
+ logger.info(`checkpoint_invalidated: ${cp.checkpoint}`, {
160
+ reason: 'compacted_before_checkpoint_line',
161
+ bucket: e.bucket,
162
+ checkpoint: cp.checkpoint,
163
+ user_id: tokenPayload.userIdJson
164
+ });
165
+ return { done: false, value: { checkpoint: cp, line: null, trace: null } };
166
+ }
167
+ // Only end the span if we error. If we return normally, we pass ownership on to the caller.
168
+ trace.span.end();
169
+ throw e;
170
+ }
134
171
  }
135
172
 
136
173
  try {
@@ -155,12 +192,18 @@ async function* streamResponseInner(
155
192
  // No update to sync
156
193
  continue;
157
194
  }
195
+ const trace = next.value.value.trace!;
196
+ const checkpoint = next.value.value.checkpoint;
197
+ const tracer = trace.tracer;
158
198
 
159
- const { checkpointLine, bucketsToFetch } = line;
199
+ const { checkpointLine, bucketsToFetch, bucketDataRequestHint } = line;
160
200
 
161
201
  // Since yielding can block, we update the state just before yielding the line.
162
202
  line.advance();
163
- yield checkpointLine;
203
+ {
204
+ using _ = tracer.span('sending', 'checkpoint');
205
+ yield checkpointLine;
206
+ }
164
207
 
165
208
  // Start syncing data for buckets up to the checkpoint. As soon as we have completed at least one priority and
166
209
  // at least 1000 operations, we also start listening for new checkpoints concurrently. When a new checkpoint comes
@@ -169,6 +212,8 @@ async function* streamResponseInner(
169
212
  const abortCheckpointController = new AbortController();
170
213
  let syncedOperations = 0;
171
214
 
215
+ let checkpointResult: CheckpointResult | null = null;
216
+
172
217
  const abortCheckpointSignal = AbortSignal.any([abortCheckpointController.signal, signal]);
173
218
 
174
219
  const bucketsByPriority = [...Map.groupBy(bucketsToFetch, (bucket) => bucket.priority).entries()];
@@ -190,6 +235,11 @@ async function* streamResponseInner(
190
235
  while (true) {
191
236
  const next = await settledPromise(waitForNewCheckpointLine());
192
237
  if (next.status == 'rejected') {
238
+ if (isAbortError(next.reason)) {
239
+ checkpointResult = { result: 'invalidated', invalidationReason: 'checkpoint_cancelled' };
240
+ } else {
241
+ checkpointResult = { result: 'invalidated', invalidationReason: 'checkpoint_error' };
242
+ }
193
243
  abortCheckpointController.abort();
194
244
  } else if (!next.value.done) {
195
245
  if (next.value.value.line == null) {
@@ -200,6 +250,7 @@ async function* streamResponseInner(
200
250
 
201
251
  // A new sync line can be emitted. Stop running the bucketDataInBatches() iterations, making the
202
252
  // main flow reach the new checkpoint.
253
+ checkpointResult = { result: 'invalidated', invalidationReason: 'checkpoint_superseded' };
203
254
  abortCheckpointController.abort();
204
255
  }
205
256
 
@@ -215,6 +266,14 @@ async function* streamResponseInner(
215
266
  maybeRaceForNewCheckpoint();
216
267
  }
217
268
 
269
+ function checkpointLogDetails(cp: storage.ReplicationCheckpoint) {
270
+ return {
271
+ checkpoint: cp.checkpoint,
272
+ user_id: tokenPayload.userIdJson,
273
+ ...tracker.getIncrementalCheckpointStats()
274
+ };
275
+ }
276
+
218
277
  // This incrementally updates dataBuckets with each individual bucket position.
219
278
  // At the end of this, we can be sure that all buckets have data up to the checkpoint.
220
279
  for (const [priority, buckets] of priorityBatches) {
@@ -223,11 +282,12 @@ async function* streamResponseInner(
223
282
  break;
224
283
  }
225
284
 
226
- yield* bucketDataInBatches({
285
+ const batchResult = yield* bucketDataInBatches({
227
286
  syncContext: syncContext,
228
287
  bucketStorage: bucketStorage,
229
- checkpoint: next.value.value.checkpoint,
288
+ checkpoint,
230
289
  bucketsToFetch: buckets,
290
+ requestHint: bucketDataRequestHint,
231
291
  checkpointLine: line,
232
292
  legacyDataLines: !isEncodingAsBson && params.raw_data != true,
233
293
  onRowsSent: markOperationsSent,
@@ -237,7 +297,35 @@ async function* streamResponseInner(
237
297
  // Passing null here will emit a full sync complete message at the end. If we pass a priority, we'll emit a partial
238
298
  // sync complete message instead.
239
299
  forPriority: !isLast ? priority : null,
240
- logger
300
+ logger,
301
+ tracer
302
+ });
303
+ if (batchResult?.result == 'partial_checkpoint_complete') {
304
+ // We don't specifically include timing details here, since that would end the span.
305
+ // Timings are included in the checkpoint_complete following this.
306
+ logger.info(`partial_checkpoint_complete: ${checkpoint.checkpoint}`, {
307
+ priority,
308
+ ...checkpointLogDetails(checkpoint)
309
+ });
310
+ } else if (batchResult?.result != null) {
311
+ checkpointResult = batchResult;
312
+ break;
313
+ }
314
+ }
315
+
316
+ if (checkpointResult?.result == 'checkpoint_complete') {
317
+ logger.info(`checkpoint_complete: ${checkpoint.checkpoint}`, {
318
+ // Incremental stats since the last checkpoint_complete, partial_checkpoint_complete or checkpoint_invalidated
319
+ ...checkpointLogDetails(checkpoint),
320
+ // Timings since the last checkpoint or checkpoint_diff
321
+ ms: getCheckpointTraceTimings(trace.span)
322
+ });
323
+ } else if (checkpointResult?.result == 'invalidated') {
324
+ // A new checkpoint and checkpoint_complete should follow soon, but we log the stats already
325
+ logger.info(`checkpoint_invalidated: ${checkpoint.checkpoint}`, {
326
+ reason: checkpointResult.invalidationReason,
327
+ ...checkpointLogDetails(checkpoint),
328
+ ms: getCheckpointTraceTimings(trace.span)
241
329
  });
242
330
  }
243
331
 
@@ -253,7 +341,8 @@ async function* streamResponseInner(
253
341
  interface BucketDataRequest {
254
342
  syncContext: SyncContext;
255
343
  bucketStorage: storage.SyncRulesBucketStorage;
256
- checkpoint: util.InternalOpId;
344
+ checkpoint: storage.ReplicationCheckpoint;
345
+ requestHint: storage.BucketRequestHint;
257
346
  /** Contains current bucket state. Modified by the request as data is sent. */
258
347
  checkpointLine: CheckpointLine;
259
348
  /** Subset of checkpointLine.bucketsToFetch, filtered by priority. */
@@ -272,9 +361,20 @@ interface BucketDataRequest {
272
361
  forPriority: BucketPriority | null;
273
362
  onRowsSent: (stats: OperationsSentStats) => void;
274
363
  logger: Logger;
364
+ tracer: PerformanceTracer<SyncCheckpointTraceCategory>;
275
365
  }
276
366
 
277
- async function* bucketDataInBatches(request: BucketDataRequest) {
367
+ type CheckpointResult =
368
+ | { result: 'partial_checkpoint_complete' }
369
+ | { result: 'checkpoint_complete' }
370
+ | {
371
+ result: 'invalidated';
372
+ invalidationReason: 'compacted' | 'checkpoint_error' | 'checkpoint_superseded' | 'checkpoint_cancelled';
373
+ };
374
+
375
+ async function* bucketDataInBatches(
376
+ request: BucketDataRequest
377
+ ): AsyncGenerator<util.StreamingSyncLine | string | null, CheckpointResult | null> {
278
378
  let isDone = false;
279
379
  while (!request.abort_batch.aborted && !isDone) {
280
380
  // The code below is functionally the same as this for-await loop below.
@@ -291,9 +391,13 @@ async function* bucketDataInBatches(request: BucketDataRequest) {
291
391
  while (true) {
292
392
  const { value, done: iterDone } = await iter.next();
293
393
  if (iterDone) {
394
+ if (value != null) {
395
+ return value;
396
+ }
294
397
  break;
295
398
  } else {
296
399
  const { done, data } = value;
400
+ using _ = request.tracer.span('sending', 'data');
297
401
  yield data;
298
402
  if (done) {
299
403
  isDone = true;
@@ -301,9 +405,10 @@ async function* bucketDataInBatches(request: BucketDataRequest) {
301
405
  }
302
406
  }
303
407
  } finally {
304
- await iter.return();
408
+ await iter.return(null);
305
409
  }
306
410
  }
411
+ return null;
307
412
  }
308
413
 
309
414
  interface BucketDataBatchResult {
@@ -314,11 +419,14 @@ interface BucketDataBatchResult {
314
419
  /**
315
420
  * Extracted as a separate internal function just to avoid memory leaks.
316
421
  */
317
- async function* bucketDataBatch(request: BucketDataRequest): AsyncGenerator<BucketDataBatchResult, void> {
422
+ async function* bucketDataBatch(
423
+ request: BucketDataRequest
424
+ ): AsyncGenerator<BucketDataBatchResult, CheckpointResult | null> {
318
425
  const {
319
426
  syncContext,
320
427
  bucketStorage: storage,
321
428
  checkpoint,
429
+ requestHint,
322
430
  bucketsToFetch,
323
431
  checkpointLine,
324
432
  legacyDataLines,
@@ -328,45 +436,57 @@ async function* bucketDataBatch(request: BucketDataRequest): AsyncGenerator<Buck
328
436
  logger
329
437
  } = request;
330
438
 
439
+ const tracer = request.tracer;
440
+
331
441
  let checkpointInvalidated = false;
332
442
 
333
- if (syncContext.syncSemaphore.isLocked()) {
334
- logger.info('Sync concurrency limit reached, waiting for lock', { user_id: request.userIdForLogs });
335
- }
336
- const acquired = await acquireSemaphoreAbortable(syncContext.syncSemaphore, AbortSignal.any([abort_batch]));
443
+ const acquired = await tracer.span('acquiring_lock').with(async () => {
444
+ return acquireSemaphoreAbortable(syncContext.syncSemaphore, AbortSignal.any([abort_batch]));
445
+ });
337
446
  if (acquired === 'aborted') {
338
- return;
447
+ return null;
339
448
  }
340
449
 
341
- const [value, release] = acquired;
450
+ const [, release] = acquired;
342
451
  try {
343
- if (value <= 3) {
344
- // This can be noisy, so we only log when we get close to the
345
- // concurrency limit.
346
- logger.info(`Got sync lock. Slots available: ${value - 1}`, {
347
- user_id: request.userIdForLogs,
348
- sync_data_slots: value - 1
349
- });
350
- }
452
+ using _ = tracer.span('bucket_data');
453
+ let has_more = false;
351
454
  // Optimization: Only fetch buckets for which the checksums have changed since the last checkpoint
352
455
  // For the first batch, this will be all buckets.
353
456
  const filteredBuckets = checkpointLine.getFilteredBucketPositions(bucketsToFetch);
354
- const dataBatches = storage.getBucketDataBatch(checkpoint, filteredBuckets);
355
-
356
- let has_more = false;
357
-
358
- for await (let { chunkData: r, targetOp } of dataBatches) {
457
+ const dataBatches = storage.getBucketDataBatch(checkpoint, filteredBuckets, {
458
+ requestHint,
459
+ // Checkpoint supersession is a cooperative batch handoff. Only abort
460
+ // in-flight storage work when the connection itself is closed.
461
+ signal: abort_connection
462
+ });
463
+ for await (let chunk of dataBatches) {
359
464
  // Abort in current batch if the connection is closed
360
465
  if (abort_connection.aborted) {
361
- return;
466
+ return null;
362
467
  }
468
+ if (isBatchEnd(chunk)) {
469
+ // This replaces any other has_more value, since the batch end is the last chunk.
470
+ has_more = chunk.hasMore;
471
+ break;
472
+ }
473
+ const { chunkData: r, targetOp } = chunk;
363
474
  if (r.has_more) {
364
475
  has_more = true;
365
476
  }
366
- if (targetOp != null && targetOp > checkpoint) {
477
+ if (targetOp != null && targetOp > checkpoint.checkpoint) {
367
478
  checkpointInvalidated = true;
368
479
  }
369
480
  if (r.data.length == 0) {
481
+ // An empty chunk is not sent to the client, but may still report progress:
482
+ // storage can emit an empty chunk for a bucket that has no operations in the
483
+ // requested range, and its position must advance so the bucket is not
484
+ // re-requested indefinitely.
485
+ checkpointLine.updateBucketPosition({
486
+ bucket: r.bucket,
487
+ nextAfter: BigInt(r.next_after),
488
+ hasMore: r.has_more
489
+ });
370
490
  continue;
371
491
  }
372
492
  logger.debug(`Sending data for ${r.bucket}`);
@@ -393,7 +513,7 @@ async function* bucketDataBatch(request: BucketDataRequest): AsyncGenerator<Buck
393
513
  // Check if syncing bucket data is supposed to stop before fetching more data
394
514
  // from storage.
395
515
  if (abort_batch.aborted) {
396
- return;
516
+ return null;
397
517
  }
398
518
  }
399
519
 
@@ -403,35 +523,50 @@ async function* bucketDataBatch(request: BucketDataRequest): AsyncGenerator<Buck
403
523
  // Don't send the checkpoint_complete line in this case.
404
524
  // More data should be available immediately for a new checkpoint.
405
525
  yield { data: null, done: true };
526
+ return { result: 'invalidated', invalidationReason: 'compacted' };
406
527
  } else {
407
528
  if (request.forPriority != null) {
408
529
  const line: util.StreamingSyncCheckpointPartiallyComplete = {
409
530
  partial_checkpoint_complete: {
410
- last_op_id: util.internalToExternalOpId(checkpoint),
531
+ last_op_id: util.internalToExternalOpId(checkpoint.checkpoint),
411
532
  priority: request.forPriority
412
533
  }
413
534
  };
414
535
  yield { data: line, done: true };
536
+ return { result: 'partial_checkpoint_complete' };
415
537
  } else {
416
538
  const line: util.StreamingSyncCheckpointComplete = {
417
539
  checkpoint_complete: {
418
- last_op_id: util.internalToExternalOpId(checkpoint)
540
+ last_op_id: util.internalToExternalOpId(checkpoint.checkpoint)
419
541
  }
420
542
  };
421
543
  yield { data: line, done: true };
544
+ return { result: 'checkpoint_complete' };
422
545
  }
423
546
  }
424
547
  }
425
548
  } finally {
426
- if (value <= 3) {
427
- // This can be noisy, so we only log when we get close to the
428
- // concurrency limit.
429
- logger.info(`Releasing sync lock`, {
430
- user_id: request.userIdForLogs
431
- });
432
- }
433
549
  release();
434
550
  }
551
+ return null;
552
+ }
553
+
554
+ function getCheckpointTraceTimings(span: Span): CheckpointTiming {
555
+ const timings = span.end();
556
+ const result: CheckpointTiming = {};
557
+ for (let key in timings) {
558
+ addTiming(result, key, timings[key]);
559
+ }
560
+ addTiming(result, 'other', span.selfDuration);
561
+ addTiming(result, 'total', span.endAt - span.startAt);
562
+ return result;
563
+ }
564
+
565
+ function addTiming(timings: CheckpointTiming, key: string, durationMicros: number) {
566
+ const ms = Math.round(durationMicros / 1000);
567
+ if (ms > 0) {
568
+ timings[key] = (timings[key] ?? 0) + ms;
569
+ }
435
570
  }
436
571
 
437
572
  function transformLegacyResponse(bucketData: util.SyncBucketData): util.SyncBucketData<util.ProtocolOplogData> {
package/src/sync/util.ts CHANGED
@@ -2,6 +2,7 @@ import * as timers from 'timers/promises';
2
2
 
3
3
  import { SemaphoreInterface } from 'async-mutex';
4
4
  import { serialize } from 'bson';
5
+ import { AbortError } from 'ix/aborterror.js';
5
6
  import * as util from '../util/util-index.js';
6
7
  import { RequestTracker } from './RequestTracker.js';
7
8
 
@@ -23,6 +24,17 @@ const DEFAULT_TOKEN_STREAM_OPTIONS: TokenStreamOptions = {
23
24
  expire_warning_period: 20_000
24
25
  };
25
26
 
27
+ /**
28
+ * Recognize both ix's AbortError and native abort errors, which Node represents
29
+ * as DOMExceptions with the name "AbortError".
30
+ */
31
+ export function isAbortError(error: unknown): boolean {
32
+ return (
33
+ error instanceof AbortError ||
34
+ (typeof error == 'object' && error != null && 'name' in error && error.name === 'AbortError')
35
+ );
36
+ }
37
+
26
38
  /**
27
39
  * An iterator that periodically yields token and optionally keepalive events, and returns once the
28
40
  * provided token expiry is reached.
@@ -19,6 +19,7 @@ export interface ServiceContext {
19
19
  storageEngine: storage.StorageEngine;
20
20
  migrations: PowerSyncMigrationManager;
21
21
  syncContext: SyncContext;
22
+ writeCheckpointBatcher: utils.WriteCheckpointBatcher;
22
23
  serviceMode: ServiceContextMode;
23
24
  eventsEngine: EventsEngine;
24
25
  }
@@ -50,6 +51,7 @@ export class ServiceContextContainer implements ServiceContext {
50
51
  eventsEngine: EventsEngine;
51
52
  syncContext: SyncContext;
52
53
  routerEngine: routes.RouterEngine;
54
+ writeCheckpointBatcher: utils.WriteCheckpointBatcher;
53
55
  serviceMode: ServiceContextMode;
54
56
 
55
57
  constructor(options: ServiceContextOptions) {
@@ -84,6 +86,11 @@ export class ServiceContextContainer implements ServiceContext {
84
86
  stop: (routerEngine) => routerEngine.shutDown()
85
87
  });
86
88
 
89
+ this.writeCheckpointBatcher = new utils.WriteCheckpointBatcher(
90
+ () => this.routerEngine.getAPI(),
91
+ () => this.storageEngine.activeBucketStorage
92
+ );
93
+
87
94
  this.syncContext = new SyncContext({
88
95
  maxDataFetchConcurrency: configuration.api_parameters.max_data_fetch_concurrency,
89
96
  maxBuckets: configuration.api_parameters.max_buckets_per_connection,
@@ -2,21 +2,48 @@ import { traceWriter } from './TraceWriter.js';
2
2
 
3
3
  export interface Span extends Disposable {
4
4
  name: string;
5
+ /**
6
+ * Start time in microseconds since an arbitrary epoch.
7
+ */
5
8
  startAt: number;
9
+ /**
10
+ * End time in microseconds since an arbitrary epoch.
11
+ *
12
+ * 0 if the span hasn't ended yet.
13
+ */
6
14
  endAt: number;
15
+
16
+ /**
17
+ * Time spent not in nested spans, in microseconds.
18
+ */
7
19
  selfDuration: number;
20
+
8
21
  nestedSince: number | undefined;
9
22
  subtrackFromSelf: number;
23
+
24
+ /**
25
+ * Durations spent in nested spans, in microseconds.
26
+ */
10
27
  nestedDurations: Record<string, number>;
11
28
 
29
+ /**
30
+ * Total duration of this span in milliseconds, rounded up. Only valid after the span has ended.
31
+ */
32
+ durationMillis: number;
33
+
12
34
  /**
13
35
  * End the span - same as [Symbol.dispose]().
14
36
  *
15
37
  * Safe to call multiple times. Any nested spans will automatically end as well.
16
38
  *
17
- * Returns an aggregate record of category -> "selfDuration".
39
+ * Returns an aggregate record of category -> "selfDuration", in microseconds.
18
40
  */
19
41
  end(): Record<string, number>;
42
+
43
+ /**
44
+ * Call a nested function, then end the span, returning the function's result.
45
+ */
46
+ with<T>(cb: () => Promise<T>): Promise<T>;
20
47
  }
21
48
 
22
49
  function now() {
@@ -115,8 +142,21 @@ export class PerformanceTracer<K extends string> {
115
142
  }
116
143
  return this.nestedDurations;
117
144
  },
145
+
146
+ get durationMillis() {
147
+ return Math.ceil((this.endAt - this.startAt) / 1000);
148
+ },
149
+
118
150
  [Symbol.dispose]() {
119
151
  this.end();
152
+ },
153
+
154
+ async with<T>(cb: () => Promise<T>): Promise<T> {
155
+ try {
156
+ return await cb();
157
+ } finally {
158
+ this.end();
159
+ }
120
160
  }
121
161
  };
122
162
  this.stack.push(s);
@@ -1,33 +1,15 @@
1
- import { ErrorCode, ServiceError } from '@powersync/lib-services-framework';
2
- import { RouteAPI } from '../api/RouteAPI.js';
3
- import { BucketStorageFactory } from '../storage/storage-index.js';
1
+ import { WriteCheckpointBatcher } from './write-checkpoint-batcher.js';
4
2
 
5
3
  export interface CreateWriteCheckpointOptions {
6
4
  userId: string | undefined;
7
5
  clientId: string | undefined;
8
- api: RouteAPI;
9
- storage: BucketStorageFactory;
6
+ checkpointRequestId?: bigint;
7
+ batcher: WriteCheckpointBatcher;
10
8
  }
11
9
  export async function createWriteCheckpoint(options: CreateWriteCheckpointOptions) {
12
10
  const full_user_id = checkpointUserId(options.userId, options.clientId);
13
11
 
14
- const syncBucketStorage = await options.storage.getActiveStorage();
15
- if (!syncBucketStorage) {
16
- throw new ServiceError(ErrorCode.PSYNC_S2302, `Cannot create Write Checkpoint since no sync config is active.`);
17
- }
18
-
19
- const { writeCheckpoint, currentCheckpoint } = await options.api.createReplicationHead(async (currentCheckpoint) => {
20
- const writeCheckpoint = await syncBucketStorage.createManagedWriteCheckpoint({
21
- user_id: full_user_id,
22
- heads: { '1': currentCheckpoint }
23
- });
24
- return { writeCheckpoint, currentCheckpoint };
25
- });
26
-
27
- return {
28
- writeCheckpoint: String(writeCheckpoint),
29
- replicationHead: currentCheckpoint
30
- };
12
+ return options.batcher.enqueue(full_user_id, options.checkpointRequestId);
31
13
  }
32
14
 
33
15
  export function checkpointUserId(user_id: string | undefined, client_id: string | undefined) {
@@ -6,6 +6,8 @@ import { Base64ConfigCollector } from './collectors/impl/base64-config-collector
6
6
  import { FallbackConfigCollector } from './collectors/impl/fallback-config-collector.js';
7
7
  import { FileSystemConfigCollector } from './collectors/impl/filesystem-config-collector.js';
8
8
  import {
9
+ DEFAULT_CHECKPOINT_REQUEST_RETENTION_MINUTES,
10
+ DEFAULT_CHECKSUM_CACHE_TTL_MINUTES,
9
11
  DEFAULT_MAX_BUCKETS_PER_CONNECTION,
10
12
  DEFAULT_MAX_CONCURRENT_CONNECTIONS,
11
13
  DEFAULT_MAX_DATA_FETCH_CONCURRENCY,
@@ -193,7 +195,13 @@ export class CompoundConfigCollector {
193
195
  max_concurrent_connections:
194
196
  baseConfig.api?.parameters?.max_concurrent_connections ?? DEFAULT_MAX_CONCURRENT_CONNECTIONS,
195
197
  max_data_fetch_concurrency:
196
- baseConfig.api?.parameters?.max_data_fetch_concurrency ?? DEFAULT_MAX_DATA_FETCH_CONCURRENCY
198
+ baseConfig.api?.parameters?.max_data_fetch_concurrency ?? DEFAULT_MAX_DATA_FETCH_CONCURRENCY,
199
+ checkpoint_request_retention_minutes: normalizeCheckpointRequestRetentionMinutes(
200
+ baseConfig.api?.parameters?.checkpoint_request_retention_minutes
201
+ ),
202
+ bucket_count_cache_ttl_minutes: normalizeChecksumCacheTtlMinutes(
203
+ baseConfig.api?.parameters?.bucket_count_cache_ttl_minutes
204
+ )
197
205
  },
198
206
  // TODO maybe move this out of the connection or something
199
207
  slot_name_prefix: baseConfig.replication?.connections?.[0]?.slot_name_prefix ?? 'powersync_',
@@ -249,3 +257,19 @@ export class CompoundConfigCollector {
249
257
  };
250
258
  }
251
259
  }
260
+
261
+ function normalizeChecksumCacheTtlMinutes(ttlMinutes: number | undefined): number {
262
+ const normalized = ttlMinutes ?? DEFAULT_CHECKSUM_CACHE_TTL_MINUTES;
263
+ if (!Number.isFinite(normalized) || !Number.isInteger(normalized) || normalized < 1) {
264
+ throw new Error('api.parameters.bucket_count_cache_ttl_minutes must be a positive integer');
265
+ }
266
+ return normalized;
267
+ }
268
+
269
+ function normalizeCheckpointRequestRetentionMinutes(retentionMinutes: number | undefined): number {
270
+ const normalized = retentionMinutes ?? DEFAULT_CHECKPOINT_REQUEST_RETENTION_MINUTES;
271
+ if (!Number.isFinite(normalized) || !Number.isInteger(normalized) || normalized < 1) {
272
+ throw new Error('api.parameters.checkpoint_request_retention_minutes must be a positive integer');
273
+ }
274
+ return normalized;
275
+ }
@@ -3,3 +3,5 @@ export const DEFAULT_MAX_CONCURRENT_CONNECTIONS = 200;
3
3
  export const DEFAULT_MAX_DATA_FETCH_CONCURRENCY = 10;
4
4
  export const DEFAULT_MAX_BUCKETS_PER_CONNECTION = 1000;
5
5
  export const DEFAULT_MAX_PARAMETER_QUERY_RESULTS = 1000;
6
+ export const DEFAULT_CHECKPOINT_REQUEST_RETENTION_MINUTES = 60;
7
+ export const DEFAULT_CHECKSUM_CACHE_TTL_MINUTES = 1 * 60;
@@ -53,9 +53,11 @@ export type ResolvedPowerSyncConfig = {
53
53
  max_data_fetch_concurrency: number;
54
54
  max_buckets_per_connection: number;
55
55
  max_parameter_query_results: number;
56
+ checkpoint_request_retention_minutes: number;
57
+ bucket_count_cache_ttl_minutes: number;
56
58
  };
57
59
 
58
- /** Prefix for postgres replication slot names. May eventually be connection-specific. */
60
+ /** Prefix for postgres replication slot names, as well as replication stream names. */
59
61
  slot_name_prefix: string;
60
62
 
61
63
  healthcheck: {
package/src/util/lsn.ts CHANGED
@@ -6,3 +6,12 @@ export function maxLsn(a: string | null | undefined, b: string | null | undefine
6
6
  if (b == null) return a;
7
7
  return a > b ? a : b;
8
8
  }
9
+
10
+ /**
11
+ * Return the smaller of two LSNs, ignoring nulls.
12
+ */
13
+ export function minLsn(a: string | null | undefined, b: string | null | undefined): string | null {
14
+ if (a == null) return b ?? null;
15
+ if (b == null) return a;
16
+ return a < b ? a : b;
17
+ }
@@ -8,6 +8,7 @@ export * from './protocol-types.js';
8
8
  export * from './secs.js';
9
9
  export * from './utils.js';
10
10
  export * from './version.js';
11
+ export * from './write-checkpoint-batcher.js';
11
12
 
12
13
  export * from './config.js';
13
14
  export * from './config/compound-config-collector.js';