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

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 (230) hide show
  1. package/CHANGELOG.md +152 -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 +36 -22
  5. package/dist/api/diagnostics.js.map +1 -1
  6. package/dist/entry/commands/compact-action.js +30 -22
  7. package/dist/entry/commands/compact-action.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/modules/AbstractModule.d.ts +6 -2
  18. package/dist/modules/AbstractModule.js.map +1 -1
  19. package/dist/replication/AbstractReplicator.d.ts +31 -7
  20. package/dist/replication/AbstractReplicator.js +168 -74
  21. package/dist/replication/AbstractReplicator.js.map +1 -1
  22. package/dist/replication/ReplicationModule.d.ts +3 -3
  23. package/dist/replication/ReplicationModule.js.map +1 -1
  24. package/dist/routes/RouterEngine.d.ts +1 -0
  25. package/dist/routes/RouterEngine.js +6 -1
  26. package/dist/routes/RouterEngine.js.map +1 -1
  27. package/dist/routes/configure-fastify.d.ts +104 -56
  28. package/dist/routes/configure-fastify.js +15 -2
  29. package/dist/routes/configure-fastify.js.map +1 -1
  30. package/dist/routes/endpoints/admin.d.ts +42 -24
  31. package/dist/routes/endpoints/admin.js +49 -36
  32. package/dist/routes/endpoints/admin.js.map +1 -1
  33. package/dist/routes/endpoints/checkpointing.d.ts +62 -0
  34. package/dist/routes/endpoints/checkpointing.js +65 -7
  35. package/dist/routes/endpoints/checkpointing.js.map +1 -1
  36. package/dist/routes/endpoints/socket-route.js +3 -2
  37. package/dist/routes/endpoints/socket-route.js.map +1 -1
  38. package/dist/routes/endpoints/sync-rules.js +25 -14
  39. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  40. package/dist/routes/endpoints/sync-stream.js +1 -1
  41. package/dist/routes/endpoints/sync-stream.js.map +1 -1
  42. package/dist/runner/teardown.js +8 -8
  43. package/dist/runner/teardown.js.map +1 -1
  44. package/dist/storage/BucketStorageBatch.d.ts +64 -17
  45. package/dist/storage/BucketStorageBatch.js.map +1 -1
  46. package/dist/storage/BucketStorageFactory.d.ts +50 -31
  47. package/dist/storage/BucketStorageFactory.js +10 -20
  48. package/dist/storage/BucketStorageFactory.js.map +1 -1
  49. package/dist/storage/CheckpointChecksumInvalidatedError.d.ts +12 -0
  50. package/dist/storage/CheckpointChecksumInvalidatedError.js +17 -0
  51. package/dist/storage/CheckpointChecksumInvalidatedError.js.map +1 -0
  52. package/dist/storage/ChecksumCache.d.ts +11 -6
  53. package/dist/storage/ChecksumCache.js +5 -4
  54. package/dist/storage/ChecksumCache.js.map +1 -1
  55. package/dist/storage/ParsedSyncConfigSet.d.ts +23 -0
  56. package/dist/storage/ParsedSyncConfigSet.js +2 -0
  57. package/dist/storage/ParsedSyncConfigSet.js.map +1 -0
  58. package/dist/storage/PersistedReplicationStream.d.ts +32 -0
  59. package/dist/storage/PersistedReplicationStream.js +26 -0
  60. package/dist/storage/PersistedReplicationStream.js.map +1 -0
  61. package/dist/storage/PersistedSyncConfigContent.d.ts +65 -0
  62. package/dist/storage/PersistedSyncConfigContent.js +138 -0
  63. package/dist/storage/PersistedSyncConfigContent.js.map +1 -0
  64. package/dist/storage/PersistedSyncConfigStatus.d.ts +13 -0
  65. package/dist/storage/PersistedSyncConfigStatus.js +2 -0
  66. package/dist/storage/PersistedSyncConfigStatus.js.map +1 -0
  67. package/dist/storage/ReplicationEventPayload.d.ts +6 -1
  68. package/dist/storage/SourceEntity.d.ts +13 -2
  69. package/dist/storage/SourceTable.d.ts +53 -4
  70. package/dist/storage/SourceTable.js +62 -7
  71. package/dist/storage/SourceTable.js.map +1 -1
  72. package/dist/storage/SourceTableReconciler.d.ts +83 -0
  73. package/dist/storage/SourceTableReconciler.js +95 -0
  74. package/dist/storage/SourceTableReconciler.js.map +1 -0
  75. package/dist/storage/StorageVersionConfig.d.ts +4 -0
  76. package/dist/storage/StorageVersionConfig.js +10 -1
  77. package/dist/storage/StorageVersionConfig.js.map +1 -1
  78. package/dist/storage/SyncRulesBucketStorage.d.ts +162 -26
  79. package/dist/storage/SyncRulesBucketStorage.js +3 -0
  80. package/dist/storage/SyncRulesBucketStorage.js.map +1 -1
  81. package/dist/storage/WriteCheckpointAPI.d.ts +85 -6
  82. package/dist/storage/WriteCheckpointAPI.js +33 -0
  83. package/dist/storage/WriteCheckpointAPI.js.map +1 -1
  84. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +133 -0
  85. package/dist/storage/implementation/BucketDefinitionMapping.js +351 -0
  86. package/dist/storage/implementation/BucketDefinitionMapping.js.map +1 -0
  87. package/dist/storage/implementation/IncrementalReprocessingCompatibility.d.ts +6 -0
  88. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js +31 -0
  89. package/dist/storage/implementation/IncrementalReprocessingCompatibility.js.map +1 -0
  90. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.d.ts +17 -0
  91. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js +70 -0
  92. package/dist/storage/implementation/IncrementalReprocessingSyncConfigLog.js.map +1 -0
  93. package/dist/storage/implementation/ReplicationStreamStorageIds.d.ts +15 -0
  94. package/dist/storage/implementation/ReplicationStreamStorageIds.js +20 -0
  95. package/dist/storage/implementation/ReplicationStreamStorageIds.js.map +1 -0
  96. package/dist/storage/storage-index.d.ts +10 -1
  97. package/dist/storage/storage-index.js +10 -1
  98. package/dist/storage/storage-index.js.map +1 -1
  99. package/dist/storage/storage-metrics.js +120 -4
  100. package/dist/storage/storage-metrics.js.map +1 -1
  101. package/dist/sync/BucketChecksumState.d.ts +12 -2
  102. package/dist/sync/BucketChecksumState.js +69 -21
  103. package/dist/sync/BucketChecksumState.js.map +1 -1
  104. package/dist/sync/RequestTracker.d.ts +7 -0
  105. package/dist/sync/RequestTracker.js +12 -0
  106. package/dist/sync/RequestTracker.js.map +1 -1
  107. package/dist/sync/sync.js +184 -43
  108. package/dist/sync/sync.js.map +1 -1
  109. package/dist/sync/util.d.ts +5 -0
  110. package/dist/sync/util.js +19 -1
  111. package/dist/sync/util.js.map +1 -1
  112. package/dist/system/ServiceContext.d.ts +2 -0
  113. package/dist/system/ServiceContext.js +2 -0
  114. package/dist/system/ServiceContext.js.map +1 -1
  115. package/dist/tracing/PerformanceTracer.d.ts +23 -1
  116. package/dist/tracing/PerformanceTracer.js +11 -0
  117. package/dist/tracing/PerformanceTracer.js.map +1 -1
  118. package/dist/util/checkpointing.d.ts +4 -8
  119. package/dist/util/checkpointing.js +1 -16
  120. package/dist/util/checkpointing.js.map +1 -1
  121. package/dist/util/config/compound-config-collector.js +23 -2
  122. package/dist/util/config/compound-config-collector.js.map +1 -1
  123. package/dist/util/config/defaults.d.ts +2 -0
  124. package/dist/util/config/defaults.js +2 -0
  125. package/dist/util/config/defaults.js.map +1 -1
  126. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
  127. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
  128. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
  129. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
  130. package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
  131. package/dist/util/config/sync-rules/sync-rules-provider.js +3 -0
  132. package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
  133. package/dist/util/config/types.d.ts +4 -1
  134. package/dist/util/lsn.d.ts +4 -0
  135. package/dist/util/lsn.js +10 -0
  136. package/dist/util/lsn.js.map +1 -1
  137. package/dist/util/protocol-types.d.ts +4 -4
  138. package/dist/util/protocol-types.js +3 -2
  139. package/dist/util/protocol-types.js.map +1 -1
  140. package/dist/util/util-index.d.ts +1 -0
  141. package/dist/util/util-index.js +1 -0
  142. package/dist/util/util-index.js.map +1 -1
  143. package/dist/util/utils.d.ts +3 -2
  144. package/dist/util/utils.js +17 -2
  145. package/dist/util/utils.js.map +1 -1
  146. package/dist/util/write-checkpoint-batcher.d.ts +19 -0
  147. package/dist/util/write-checkpoint-batcher.js +100 -0
  148. package/dist/util/write-checkpoint-batcher.js.map +1 -0
  149. package/package.json +7 -7
  150. package/src/api/RouteAPI.ts +43 -14
  151. package/src/api/diagnostics.ts +45 -26
  152. package/src/entry/commands/compact-action.ts +37 -23
  153. package/src/metrics/metrics-interfaces.ts +6 -1
  154. package/src/metrics/open-telemetry/MetricAttributeFilteringExporter.ts +85 -0
  155. package/src/metrics/open-telemetry/OpenTelemetryMetricsFactory.ts +7 -2
  156. package/src/metrics/open-telemetry/util.ts +7 -3
  157. package/src/modules/AbstractModule.ts +6 -2
  158. package/src/replication/AbstractReplicator.ts +212 -78
  159. package/src/replication/ReplicationModule.ts +2 -3
  160. package/src/routes/RouterEngine.ts +7 -1
  161. package/src/routes/configure-fastify.ts +25 -2
  162. package/src/routes/endpoints/admin.ts +75 -51
  163. package/src/routes/endpoints/checkpointing.ts +79 -8
  164. package/src/routes/endpoints/socket-route.ts +3 -2
  165. package/src/routes/endpoints/sync-rules.ts +26 -14
  166. package/src/routes/endpoints/sync-stream.ts +1 -1
  167. package/src/runner/teardown.ts +8 -8
  168. package/src/storage/BucketStorageBatch.ts +65 -18
  169. package/src/storage/BucketStorageFactory.ts +73 -46
  170. package/src/storage/CheckpointChecksumInvalidatedError.ts +17 -0
  171. package/src/storage/ChecksumCache.ts +27 -14
  172. package/src/storage/ParsedSyncConfigSet.ts +25 -0
  173. package/src/storage/PersistedReplicationStream.ts +55 -0
  174. package/src/storage/PersistedSyncConfigContent.ts +207 -0
  175. package/src/storage/PersistedSyncConfigStatus.ts +14 -0
  176. package/src/storage/ReplicationEventPayload.ts +6 -1
  177. package/src/storage/SourceEntity.ts +12 -2
  178. package/src/storage/SourceTable.ts +96 -8
  179. package/src/storage/SourceTableReconciler.ts +188 -0
  180. package/src/storage/StorageVersionConfig.ts +11 -1
  181. package/src/storage/SyncRulesBucketStorage.ts +189 -27
  182. package/src/storage/WriteCheckpointAPI.ts +140 -6
  183. package/src/storage/implementation/BucketDefinitionMapping.ts +539 -0
  184. package/src/storage/implementation/IncrementalReprocessingCompatibility.ts +41 -0
  185. package/src/storage/implementation/IncrementalReprocessingSyncConfigLog.ts +126 -0
  186. package/src/storage/implementation/ReplicationStreamStorageIds.ts +21 -0
  187. package/src/storage/storage-index.ts +11 -1
  188. package/src/storage/storage-metrics.ts +154 -8
  189. package/src/sync/BucketChecksumState.ts +105 -21
  190. package/src/sync/RequestTracker.ts +20 -0
  191. package/src/sync/sync.ts +214 -50
  192. package/src/sync/util.ts +33 -8
  193. package/src/system/ServiceContext.ts +7 -0
  194. package/src/tracing/PerformanceTracer.ts +41 -1
  195. package/src/util/checkpointing.ts +4 -22
  196. package/src/util/config/compound-config-collector.ts +31 -1
  197. package/src/util/config/defaults.ts +2 -0
  198. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
  199. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
  200. package/src/util/config/sync-rules/sync-rules-provider.ts +5 -0
  201. package/src/util/config/types.ts +4 -1
  202. package/src/util/lsn.ts +9 -0
  203. package/src/util/protocol-types.ts +3 -2
  204. package/src/util/util-index.ts +1 -0
  205. package/src/util/utils.ts +16 -2
  206. package/src/util/write-checkpoint-batcher.ts +142 -0
  207. package/test/src/AbstractReplicator.test.ts +177 -0
  208. package/test/src/MetricAttributeFilteringExporter.test.ts +96 -0
  209. package/test/src/PersistedSyncConfigContent.test.ts +152 -0
  210. package/test/src/checksum_cache.test.ts +22 -0
  211. package/test/src/config.test.ts +142 -0
  212. package/test/src/diagnostics.test.ts +87 -34
  213. package/test/src/module-loader.test.ts +33 -1
  214. package/test/src/routes/admin.test.ts +188 -18
  215. package/test/src/routes/checkpointing.test.ts +54 -0
  216. package/test/src/routes/mocks.ts +6 -2
  217. package/test/src/routes/stream.test.ts +123 -2
  218. package/test/src/source-table-reconciler.test.ts +244 -0
  219. package/test/src/storage/SourceTable.test.ts +92 -0
  220. package/test/src/storage-metrics.test.ts +148 -0
  221. package/test/src/sync/BucketChecksumState.test.ts +98 -12
  222. package/test/src/sync/util.test.ts +28 -1
  223. package/test/src/util/checkpointing.test.ts +249 -0
  224. package/test/src/util/utils.test.ts +23 -0
  225. package/tsconfig.json +1 -4
  226. package/tsconfig.tsbuildinfo +1 -1
  227. package/dist/storage/PersistedSyncRulesContent.d.ts +0 -59
  228. package/dist/storage/PersistedSyncRulesContent.js +0 -100
  229. package/dist/storage/PersistedSyncRulesContent.js.map +0 -1
  230. package/src/storage/PersistedSyncRulesContent.ts +0 -174
@@ -31,6 +31,7 @@ export type RouteRegistrationOptions = {
31
31
  */
32
32
  export type RouteDefinitions = {
33
33
  api?: Partial<RouteRegistrationOptions>;
34
+ checkpointing?: Partial<RouteRegistrationOptions>;
34
35
  sync_stream?: Partial<RouteRegistrationOptions>;
35
36
  };
36
37
 
@@ -41,12 +42,20 @@ export type FastifyServerConfig = {
41
42
 
42
43
  export const DEFAULT_ROUTE_OPTIONS = {
43
44
  api: {
44
- routes: [...ADMIN_ROUTES, ...CHECKPOINT_ROUTES, ...SYNC_RULES_ROUTES, ...PROBES_ROUTES],
45
+ routes: [...ADMIN_ROUTES, ...SYNC_RULES_ROUTES, ...PROBES_ROUTES],
45
46
  queue_options: {
46
47
  concurrency: 10,
47
48
  max_queue_depth: 20
48
49
  }
49
50
  },
51
+ checkpointing: {
52
+ routes: [...CHECKPOINT_ROUTES],
53
+ queue_options: {
54
+ // Note that the values here has an effect on WriteCheckpointBatcher
55
+ concurrency: 100,
56
+ max_queue_depth: 100
57
+ }
58
+ },
50
59
  sync_stream: {
51
60
  routes: [...SYNC_STREAM_ROUTES],
52
61
  queue_options: {
@@ -72,6 +81,7 @@ export function configureFastifyServer(server: fastify.FastifyInstance, options:
72
81
 
73
82
  // Set on the outer server so both child scopes inherit.
74
83
  registerFastifyErrorHandler(server);
84
+ registerFastifyNotFoundHandler(server);
75
85
 
76
86
  /**
77
87
  * Fastify creates an encapsulated context for each `.register` call.
@@ -81,7 +91,6 @@ export function configureFastifyServer(server: fastify.FastifyInstance, options:
81
91
  */
82
92
  server.register(async function (childContext) {
83
93
  registerFastifyRoutes(childContext, generateContext, routes.api?.routes ?? DEFAULT_ROUTE_OPTIONS.api.routes);
84
- registerFastifyNotFoundHandler(childContext);
85
94
 
86
95
  // Limit the active concurrent requests
87
96
  childContext.addHook(
@@ -90,6 +99,20 @@ export function configureFastifyServer(server: fastify.FastifyInstance, options:
90
99
  );
91
100
  });
92
101
 
102
+ server.register(async function (childContext) {
103
+ registerFastifyRoutes(
104
+ childContext,
105
+ generateContext,
106
+ routes.checkpointing?.routes ?? DEFAULT_ROUTE_OPTIONS.checkpointing.routes
107
+ );
108
+
109
+ // Limit the active concurrent requests
110
+ childContext.addHook(
111
+ 'onRequest',
112
+ createRequestQueueHook(routes.checkpointing?.queue_options ?? DEFAULT_ROUTE_OPTIONS.checkpointing.queue_options)
113
+ );
114
+ });
115
+
93
116
  // Create a separate context for concurrency queueing
94
117
  server.register(async function (childContext) {
95
118
  registerFastifyRoutes(
@@ -1,7 +1,13 @@
1
1
  import * as sqlite from 'node:sqlite';
2
2
 
3
3
  import { ErrorCode, errors, router, schema } from '@powersync/lib-services-framework';
4
- import { nodeSqlite, SourceSchema, SqlSyncRules, StaticSchema } from '@powersync/service-sync-rules';
4
+ import {
5
+ HydratedSyncConfig,
6
+ nodeSqlite,
7
+ SourceSchema,
8
+ SqlSyncRules,
9
+ StaticSchema
10
+ } from '@powersync/service-sync-rules';
5
11
  import { internal_routes } from '@powersync/service-types';
6
12
 
7
13
  import { DEFAULT_HYDRATION_STATE } from '@powersync/service-sync-rules';
@@ -65,20 +71,35 @@ export const diagnostics = routeDefinition({
65
71
  const {
66
72
  storageEngine: { activeBucketStorage }
67
73
  } = service_context;
68
- const active = await activeBucketStorage.getActiveSyncRulesContent();
69
- const next = await activeBucketStorage.getNextSyncRulesContent();
74
+ const active = await activeBucketStorage.getActiveSyncConfig();
75
+ const deploying = await activeBucketStorage.getDeployingSyncConfig();
70
76
 
71
- const active_status = await api.getSyncRulesStatus(activeBucketStorage, apiHandler, active, {
72
- include_content,
73
- check_connection: status.connected,
74
- live_status: true
75
- });
77
+ const active_status = await api.getSyncRulesStatus(
78
+ apiHandler,
79
+ active?.content ?? null,
80
+ {
81
+ include_content,
82
+ check_connection: status.connected,
83
+ live_status: true,
84
+ active: true
85
+ },
86
+ active?.storage
87
+ );
76
88
 
77
- const next_status = await api.getSyncRulesStatus(activeBucketStorage, apiHandler, next, {
78
- include_content,
79
- check_connection: status.connected,
80
- live_status: true
81
- });
89
+ const deploying_status =
90
+ deploying == null
91
+ ? undefined
92
+ : await api.getSyncRulesStatus(
93
+ apiHandler,
94
+ deploying.content,
95
+ {
96
+ include_content,
97
+ check_connection: status.connected,
98
+ live_status: true,
99
+ active: false
100
+ },
101
+ deploying.storage
102
+ );
82
103
 
83
104
  return internal_routes.DiagnosticsResponse.encode({
84
105
  connections: [
@@ -89,7 +110,7 @@ export const diagnostics = routeDefinition({
89
110
  }
90
111
  ],
91
112
  active_sync_rules: active_status,
92
- deploying_sync_rules: next_status
113
+ deploying_sync_rules: deploying_status
93
114
  });
94
115
  }
95
116
  });
@@ -119,12 +140,16 @@ export const reprocess = routeDefinition({
119
140
  storageEngine: { activeBucketStorage }
120
141
  } = service_context;
121
142
  const apiHandler = service_context.routerEngine.getAPI();
122
- const next = await activeBucketStorage.getNextSyncRules(apiHandler.getParseSyncRulesOptions());
143
+ const next = await activeBucketStorage.getDeployingSyncConfig();
123
144
  if (next != null) {
124
- throw new Error(`Busy processing sync config - cannot reprocess`);
145
+ throw new errors.ServiceError({
146
+ status: 409,
147
+ code: ErrorCode.PSYNC_S4106,
148
+ description: 'Busy processing sync config - cannot reprocess'
149
+ });
125
150
  }
126
151
 
127
- const active = await activeBucketStorage.getActiveSyncRules(apiHandler.getParseSyncRulesOptions());
152
+ const active = await activeBucketStorage.getActiveSyncConfig();
128
153
  if (active == null) {
129
154
  throw new errors.ServiceError({
130
155
  status: 422,
@@ -132,16 +157,17 @@ export const reprocess = routeDefinition({
132
157
  description: 'No active sync config'
133
158
  });
134
159
  }
135
-
136
160
  // There are some differences between this and using asUpdateOptions():
137
161
  // 1. This always re-parses the source YAML. If there are changes to the sync stream compiler, that can affect the sync plan.
138
162
  // 2. If the source does not set the storage version, this will update it do the current version.
139
163
  // We can consider tweaking this behavior in the future.
140
164
  const new_rules = await activeBucketStorage.updateSyncRules(
141
- storage.updateSyncRulesFromYaml(active.syncConfigWithErrors.config.content, {
165
+ storage.updateSyncRulesFromYaml(active.content.sync_rules_content, {
142
166
  // This sync config already passed validation. But if the config is not valid anymore due
143
167
  // to a service change, we do want to report the error here.
144
- validate: true
168
+ validate: true,
169
+ version_label: active.content.version_label,
170
+ forceNewReplicationStream: true
145
171
  })
146
172
  );
147
173
 
@@ -153,44 +179,47 @@ export const reprocess = routeDefinition({
153
179
  // Previously the connection was asserted with `!`
154
180
  tag: baseConfig.tag,
155
181
  id: baseConfig.id,
156
- slot_name: new_rules.slot_name
182
+ slot_name: new_rules.replicationStreamName
157
183
  }
158
184
  ]
159
185
  });
160
186
  }
161
187
  });
162
188
 
163
- class FakeSyncRulesContentForValidation extends storage.PersistedSyncRulesContent {
189
+ class FakeSyncRulesContentForValidation extends storage.PersistedSyncConfigContent {
164
190
  constructor(
165
191
  private readonly apiHandler: api.RouteAPI,
166
192
  private readonly schema: SourceSchema,
167
- data: storage.PersistedSyncRulesContentData
193
+ data: storage.PersistedSyncConfigContentData
168
194
  ) {
169
195
  super(data);
170
196
  }
171
197
 
172
- current_lock: storage.ReplicationLock | null = null;
173
-
174
- async lock(): Promise<storage.ReplicationLock> {
175
- throw new Error('Lock not implemented');
176
- }
198
+ parsed(options: storage.ParseSyncConfigOptions): storage.ParsedSyncConfigSet {
199
+ const syncConfig = SqlSyncRules.fromYaml(this.sync_rules_content, {
200
+ ...this.apiHandler.getParseSyncRulesOptions(),
201
+ schema: this.schema
202
+ });
177
203
 
178
- parsed(options: storage.ParseSyncRulesOptions): storage.PersistedSyncRules {
204
+ let hydrated: HydratedSyncConfig | undefined;
179
205
  return {
180
- ...this,
181
- syncConfigWithErrors: SqlSyncRules.fromYaml(this.sync_rules_content, {
182
- ...this.apiHandler.getParseSyncRulesOptions(),
183
- schema: this.schema
184
- }),
206
+ replicationStreamId: this.replicationStreamId,
207
+ replicationStreamName: this.replicationStreamName,
208
+ syncConfigs: [syncConfig],
185
209
  hydrationState: DEFAULT_HYDRATION_STATE,
186
- hydratedSyncConfig() {
187
- return this.syncConfigWithErrors.config.hydrate({
210
+ get hydratedSyncConfig(): HydratedSyncConfig {
211
+ hydrated ??= syncConfig.config.hydrate({
188
212
  hydrationState: DEFAULT_HYDRATION_STATE,
189
213
  sqlite: nodeSqlite(sqlite)
190
214
  });
215
+ return hydrated;
191
216
  }
192
217
  };
193
218
  }
219
+
220
+ async getSyncConfigStatus(): Promise<storage.PersistedSyncConfigStatus | null> {
221
+ return null;
222
+ }
194
223
  }
195
224
 
196
225
  export const validate = routeDefinition({
@@ -210,13 +239,12 @@ export const validate = routeDefinition({
210
239
 
211
240
  const sync_rules = new FakeSyncRulesContentForValidation(apiHandler, schema, {
212
241
  // Dummy values
213
- id: 0,
214
- slot_name: '',
215
- active: false,
216
- last_checkpoint_lsn: '',
242
+ replicationStreamId: 0,
243
+ replicationStreamName: '',
217
244
  storageVersion: storage.LEGACY_STORAGE_VERSION,
218
245
  sync_rules_content: content,
219
- compiled_plan: null
246
+ compiled_plan: null,
247
+ syncConfigState: storage.SyncRuleState.PROCESSING
220
248
  });
221
249
 
222
250
  const connectionStatus = await apiHandler.getConnectionStatus();
@@ -227,16 +255,12 @@ export const validate = routeDefinition({
227
255
  });
228
256
  }
229
257
 
230
- const status = (await api.getSyncRulesStatus(
231
- service_context.storageEngine.activeBucketStorage,
232
- apiHandler,
233
- sync_rules,
234
- {
235
- include_content: false,
236
- check_connection: connectionStatus.connected,
237
- live_status: false
238
- }
239
- ))!;
258
+ const status = (await api.getSyncRulesStatus(apiHandler, sync_rules, {
259
+ include_content: false,
260
+ check_connection: connectionStatus.connected,
261
+ live_status: false,
262
+ active: false
263
+ }))!;
240
264
 
241
265
  if (connectionStatus == null) {
242
266
  status.errors.push({ level: 'fatal', message: 'No connection configured', ts: new Date().toISOString() });
@@ -1,10 +1,49 @@
1
- import { logger, router, schema } from '@powersync/lib-services-framework';
1
+ import { codecs, logger, router, schema } from '@powersync/lib-services-framework';
2
2
  import * as t from 'ts-codec';
3
3
 
4
4
  import * as util from '../../util/util-index.js';
5
5
  import { authUser } from '../auth.js';
6
6
  import { routeDefinition } from '../router.js';
7
7
 
8
+ const CHECKPOINT_REQUEST_ID_MAX = 9_223_372_036_854_775_807n;
9
+
10
+ function isValidCheckpointRequestId(value: bigint) {
11
+ return value > 0n && value <= CHECKPOINT_REQUEST_ID_MAX;
12
+ }
13
+
14
+ export const CheckpointRequestPayload = t.object({
15
+ client_id: t.string,
16
+ // Positive int64, matching the managed write checkpoint id. Clients should
17
+ // send values larger than Number.MAX_SAFE_INTEGER as strings, since JSON
18
+ // numbers are only validated up to the safe-integer range.
19
+ checkpoint_request_id: codecs.bigint
20
+ });
21
+
22
+ const CheckpointRequestPayloadShapeValidator = schema.createTsCodecValidator(CheckpointRequestPayload, {
23
+ allowAdditional: true
24
+ });
25
+
26
+ const CheckpointRequestPayloadValidator = {
27
+ validate(params: t.Encoded<typeof CheckpointRequestPayload>) {
28
+ const shapeValidation = CheckpointRequestPayloadShapeValidator.validate(params);
29
+ if (!shapeValidation.valid) {
30
+ return shapeValidation;
31
+ }
32
+
33
+ const decodedParams = CheckpointRequestPayload.decode(params);
34
+ if (!isValidCheckpointRequestId(decodedParams.checkpoint_request_id)) {
35
+ return {
36
+ valid: false as const,
37
+ errors: [`Expected checkpoint_request_id between 1 and ${CHECKPOINT_REQUEST_ID_MAX}`]
38
+ };
39
+ }
40
+
41
+ return {
42
+ valid: true as const
43
+ };
44
+ }
45
+ };
46
+
8
47
  const WriteCheckpointRequest = t.object({
9
48
  client_id: t.string.optional()
10
49
  });
@@ -24,13 +63,13 @@ export const writeCheckpoint = routeDefinition({
24
63
  // Since we don't use LSNs anymore, the only way to get that is to wait.
25
64
  const start = Date.now();
26
65
 
27
- const head = await apiHandler.createReplicationHead(async (head) => head);
66
+ const head = await apiHandler.createReplicationHead(async (head) => ({ response: head, shouldAdvance: true }));
28
67
 
29
68
  const timeout = 50_000;
30
69
 
31
70
  logger.info(`Waiting for LSN checkpoint: ${head}`);
32
71
  while (Date.now() - start < timeout) {
33
- const bucketStorage = await service_context.storageEngine.activeBucketStorage.getActiveStorage();
72
+ const bucketStorage = (await service_context.storageEngine.activeBucketStorage.getActiveSyncConfig())?.storage;
34
73
  const cp = await bucketStorage?.getCheckpoint();
35
74
  if (cp == null) {
36
75
  throw new Error('No sync config available');
@@ -54,13 +93,10 @@ export const writeCheckpoint2 = routeDefinition({
54
93
  handler: async (payload) => {
55
94
  const { token_payload, service_context } = payload.context;
56
95
 
57
- const apiHandler = service_context.routerEngine.getAPI();
58
-
59
96
  const { replicationHead, writeCheckpoint } = await util.createWriteCheckpoint({
60
97
  userId: token_payload!.userIdString,
61
98
  clientId: payload.params.client_id,
62
- api: apiHandler,
63
- storage: service_context.storageEngine.activeBucketStorage
99
+ batcher: service_context.writeCheckpointBatcher
64
100
  });
65
101
 
66
102
  logger.info(
@@ -73,4 +109,39 @@ export const writeCheckpoint2 = routeDefinition({
73
109
  }
74
110
  });
75
111
 
76
- export const CHECKPOINT_ROUTES = [writeCheckpoint, writeCheckpoint2];
112
+ export const checkpointRequest = routeDefinition({
113
+ path: '/sync/checkpoint-request',
114
+ method: router.HTTPMethod.POST,
115
+ authorize: authUser,
116
+ validator: CheckpointRequestPayloadValidator,
117
+ handler: async (request) => {
118
+ const { token_payload, service_context } = request.context;
119
+ const { params } = request;
120
+
121
+ const decodedParams = CheckpointRequestPayload.decode(params);
122
+
123
+ // Storage only applies supplied request ids that advance the stored managed checkpoint.
124
+ // Stale or duplicate ids return the stored checkpoint; storage decides whether
125
+ // the matched checkpoint still needs a source marker.
126
+ const { replicationHead, writeCheckpoint } = await util.createWriteCheckpoint({
127
+ userId: token_payload!.userIdString,
128
+ clientId: decodedParams.client_id,
129
+ batcher: service_context.writeCheckpointBatcher,
130
+ checkpointRequestId: decodedParams.checkpoint_request_id
131
+ });
132
+
133
+ logger.info(
134
+ `Requested checkpoint for ${token_payload!.userIdString}/${decodedParams.client_id}: ${writeCheckpoint} | ${replicationHead}`
135
+ );
136
+
137
+ // Return the checkpoint request id storage is actually at after this request.
138
+ // When an earlier request has already advanced the stored value beyond the
139
+ // supplied checkpoint_request_id, this returns that larger previous value so
140
+ // the client can treat the response as a stale-request acknowledgement.
141
+ return {
142
+ checkpoint_request_id: String(writeCheckpoint)
143
+ };
144
+ }
145
+ });
146
+
147
+ export const CHECKPOINT_ROUTES = [checkpointRequest, writeCheckpoint, writeCheckpoint2];
@@ -71,7 +71,7 @@ export const syncStreamReactive: SocketRouteGenerator = (router) =>
71
71
  storageEngine: { activeBucketStorage }
72
72
  } = service_context;
73
73
 
74
- const bucketStorage = await activeBucketStorage.getActiveStorage();
74
+ const bucketStorage = (await activeBucketStorage.getActiveSyncConfig())?.storage;
75
75
  if (bucketStorage == null) {
76
76
  responder.onError(
77
77
  new errors.ServiceError({
@@ -163,8 +163,9 @@ export const syncStreamReactive: SocketRouteGenerator = (router) =>
163
163
  } catch (ex) {
164
164
  // Convert to our standard form before responding.
165
165
  // This ensures the error can be serialized.
166
+ // However, use the original error for the logs, so that we have the stack trace.
166
167
  const error = new errors.InternalServerError(ex);
167
- logger.error('Sync stream error', error);
168
+ logger.error('Sync stream error', ex);
168
169
  closeReason ??= 'stream error';
169
170
  responder.onError(error);
170
171
  } finally {
@@ -73,7 +73,7 @@ export const deploySyncRules = routeDefinition({
73
73
  const sync_rules = await storageEngine.activeBucketStorage.updateSyncRules(updateSyncRulesFromConfig(syncConfig));
74
74
 
75
75
  return {
76
- slot_name: sync_rules.slot_name
76
+ slot_name: sync_rules.replicationStreamName
77
77
  };
78
78
  }
79
79
  });
@@ -110,8 +110,8 @@ export const currentSyncRules = routeDefinition({
110
110
  storageEngine: { activeBucketStorage }
111
111
  } = service_context;
112
112
 
113
- const sync_rules = await activeBucketStorage.getActiveSyncRulesContent();
114
- if (!sync_rules) {
113
+ const active = await activeBucketStorage.getActiveSyncConfig();
114
+ if (!active) {
115
115
  throw new errors.ServiceError({
116
116
  status: 422,
117
117
  code: ErrorCode.PSYNC_S4104,
@@ -119,15 +119,16 @@ export const currentSyncRules = routeDefinition({
119
119
  });
120
120
  }
121
121
 
122
+ const sync_rules = active.content;
122
123
  const apiHandler = service_context.routerEngine.getAPI();
123
124
  const info = await debugSyncRules(apiHandler, sync_rules.sync_rules_content);
124
- const next = await activeBucketStorage.getNextSyncRulesContent();
125
+ const next = await activeBucketStorage.getDeployingSyncConfig();
125
126
 
126
- const next_info = next ? await debugSyncRules(apiHandler, next.sync_rules_content) : null;
127
+ const next_info = next ? await debugSyncRules(apiHandler, next.content.sync_rules_content) : null;
127
128
 
128
129
  const response = {
129
130
  current: {
130
- slot_name: sync_rules.slot_name,
131
+ slot_name: sync_rules.replicationStreamName,
131
132
  content: sync_rules.sync_rules_content,
132
133
  ...info
133
134
  },
@@ -135,8 +136,8 @@ export const currentSyncRules = routeDefinition({
135
136
  next == null
136
137
  ? null
137
138
  : {
138
- slot_name: next.slot_name,
139
- content: next.sync_rules_content,
139
+ slot_name: next.content.replicationStreamName,
140
+ content: next.content.sync_rules_content,
140
141
  ...next_info
141
142
  }
142
143
  };
@@ -156,9 +157,17 @@ export const reprocessSyncRules = routeDefinition({
156
157
  const {
157
158
  storageEngine: { activeBucketStorage }
158
159
  } = payload.context.service_context;
159
- const apiHandler = payload.context.service_context.routerEngine.getAPI();
160
- const sync_rules = await activeBucketStorage.getActiveSyncRules(apiHandler.getParseSyncRulesOptions());
161
- if (sync_rules == null) {
160
+ const next = await activeBucketStorage.getDeployingSyncConfig();
161
+ if (next != null) {
162
+ throw new errors.ServiceError({
163
+ status: 409,
164
+ code: ErrorCode.PSYNC_S4106,
165
+ description: 'Busy processing sync config - cannot reprocess'
166
+ });
167
+ }
168
+
169
+ const active = await activeBucketStorage.getActiveSyncConfig();
170
+ if (active == null) {
162
171
  throw new errors.ServiceError({
163
172
  status: 422,
164
173
  code: ErrorCode.PSYNC_S4104,
@@ -166,15 +175,18 @@ export const reprocessSyncRules = routeDefinition({
166
175
  });
167
176
  }
168
177
 
178
+ const sync_rules = active.content;
169
179
  const new_rules = await activeBucketStorage.updateSyncRules(
170
- updateSyncRulesFromYaml(sync_rules.syncConfigWithErrors.config.content, {
180
+ updateSyncRulesFromYaml(sync_rules.sync_rules_content, {
171
181
  // This sync config already passed validation. But if the rules are not valid anymore due
172
182
  // to a service change, we do want to report the error here.
173
- validate: true
183
+ validate: true,
184
+ version_label: sync_rules.version_label,
185
+ forceNewReplicationStream: true
174
186
  })
175
187
  );
176
188
  return {
177
- slot_name: new_rules.slot_name
189
+ slot_name: new_rules.replicationStreamName
178
190
  };
179
191
  }
180
192
  });
@@ -62,7 +62,7 @@ export const syncStreamed = routeDefinition({
62
62
  });
63
63
  }
64
64
 
65
- const bucketStorage = await storageEngine.activeBucketStorage.getActiveStorage();
65
+ const bucketStorage = (await storageEngine.activeBucketStorage.getActiveSyncConfig())?.storage;
66
66
 
67
67
  if (bucketStorage == null) {
68
68
  throw new errors.ServiceError({
@@ -40,22 +40,22 @@ async function terminateSyncRules(storageFactory: storage.BucketStorageFactory,
40
40
  const locks: storage.ReplicationLock[] = [];
41
41
  while (Date.now() - start < 120_000) {
42
42
  let retry = false;
43
- const replicatingSyncRules = await storageFactory.getReplicatingSyncRules();
43
+ const replicatingStreams = await storageFactory.getReplicatingReplicationStreams();
44
44
  // Lock all the replicating replication streams
45
- for (const replicatingSyncRule of replicatingSyncRules) {
46
- const lock = await replicatingSyncRule.lock();
45
+ for (const replicatingStream of replicatingStreams) {
46
+ const lock = await replicatingStream.lock();
47
47
  locks.push(lock);
48
48
  }
49
49
 
50
- const stoppedSyncRules = await storageFactory.getStoppedSyncRules();
51
- const combinedSyncRules = [...replicatingSyncRules, ...stoppedSyncRules];
50
+ const stoppedStreams = await storageFactory.getStoppedReplicationStreams();
51
+ const combinedStreams = [...replicatingStreams, ...stoppedStreams];
52
52
  try {
53
53
  // Clean up any module specific configuration for the replication stream
54
- await moduleManager.tearDown({ syncRules: combinedSyncRules });
54
+ await moduleManager.tearDown({ replicationStreams: combinedStreams, syncRules: combinedStreams });
55
55
 
56
56
  // Mark the replication stream as terminated
57
- for (let syncRules of combinedSyncRules) {
58
- const syncRulesStorage = storageFactory.getInstance(syncRules);
57
+ for (let replicationStream of combinedStreams) {
58
+ const syncRulesStorage = storageFactory.getInstance(replicationStream);
59
59
  // The storage will be dropped at the end of the teardown, so we don't need to clear it here
60
60
  await syncRulesStorage.terminate({ clearStorage: false });
61
61
  }