@powersync/service-core 0.0.0-dev-20250122110924 → 0.0.0-dev-20250227082606

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 (193) hide show
  1. package/CHANGELOG.md +84 -9
  2. package/dist/api/RouteAPI.d.ts +9 -1
  3. package/dist/api/diagnostics.js +107 -169
  4. package/dist/api/diagnostics.js.map +1 -1
  5. package/dist/auth/CachedKeyCollector.js +26 -25
  6. package/dist/auth/CachedKeyCollector.js.map +1 -1
  7. package/dist/auth/CompoundKeyCollector.js +1 -0
  8. package/dist/auth/CompoundKeyCollector.js.map +1 -1
  9. package/dist/auth/KeySpec.js +3 -0
  10. package/dist/auth/KeySpec.js.map +1 -1
  11. package/dist/auth/KeyStore.js +4 -0
  12. package/dist/auth/KeyStore.js.map +1 -1
  13. package/dist/auth/LeakyBucket.js +5 -0
  14. package/dist/auth/LeakyBucket.js.map +1 -1
  15. package/dist/auth/RemoteJWKSCollector.js +4 -1
  16. package/dist/auth/RemoteJWKSCollector.js.map +1 -1
  17. package/dist/auth/StaticKeyCollector.js +1 -0
  18. package/dist/auth/StaticKeyCollector.js.map +1 -1
  19. package/dist/auth/StaticSupabaseKeyCollector.js +1 -0
  20. package/dist/auth/StaticSupabaseKeyCollector.js.map +1 -1
  21. package/dist/entry/commands/compact-action.js +10 -73
  22. package/dist/entry/commands/compact-action.js.map +1 -1
  23. package/dist/metrics/Metrics.js +35 -1
  24. package/dist/metrics/Metrics.js.map +1 -1
  25. package/dist/modules/AbstractModule.d.ts +1 -1
  26. package/dist/modules/AbstractModule.js +2 -0
  27. package/dist/modules/AbstractModule.js.map +1 -1
  28. package/dist/modules/ModuleManager.js +1 -3
  29. package/dist/modules/ModuleManager.js.map +1 -1
  30. package/dist/replication/AbstractReplicationJob.js +4 -2
  31. package/dist/replication/AbstractReplicationJob.js.map +1 -1
  32. package/dist/replication/AbstractReplicator.js +26 -88
  33. package/dist/replication/AbstractReplicator.js.map +1 -1
  34. package/dist/replication/ReplicationEngine.js +1 -3
  35. package/dist/replication/ReplicationEngine.js.map +1 -1
  36. package/dist/replication/ReplicationModule.js +3 -0
  37. package/dist/replication/ReplicationModule.js.map +1 -1
  38. package/dist/routes/RouterEngine.js +8 -0
  39. package/dist/routes/RouterEngine.js.map +1 -1
  40. package/dist/routes/configure-fastify.d.ts +3 -3
  41. package/dist/routes/endpoints/admin.d.ts +6 -6
  42. package/dist/routes/endpoints/admin.js +4 -1
  43. package/dist/routes/endpoints/admin.js.map +1 -1
  44. package/dist/routes/endpoints/checkpointing.js +17 -86
  45. package/dist/routes/endpoints/checkpointing.js.map +1 -1
  46. package/dist/routes/endpoints/socket-route.js +7 -6
  47. package/dist/routes/endpoints/socket-route.js.map +1 -1
  48. package/dist/routes/endpoints/sync-rules.js +7 -2
  49. package/dist/routes/endpoints/sync-rules.js.map +1 -1
  50. package/dist/routes/endpoints/sync-stream.js +7 -6
  51. package/dist/routes/endpoints/sync-stream.js.map +1 -1
  52. package/dist/runner/teardown.js +5 -67
  53. package/dist/runner/teardown.js.map +1 -1
  54. package/dist/storage/BucketStorage.d.ts +8 -414
  55. package/dist/storage/BucketStorage.js +9 -7
  56. package/dist/storage/BucketStorage.js.map +1 -1
  57. package/dist/storage/BucketStorageBatch.d.ts +130 -0
  58. package/dist/storage/BucketStorageBatch.js +10 -0
  59. package/dist/storage/BucketStorageBatch.js.map +1 -0
  60. package/dist/storage/BucketStorageFactory.d.ts +145 -0
  61. package/dist/storage/BucketStorageFactory.js +2 -0
  62. package/dist/storage/BucketStorageFactory.js.map +1 -0
  63. package/dist/storage/ChecksumCache.js +12 -7
  64. package/dist/storage/ChecksumCache.js.map +1 -1
  65. package/dist/storage/PersistedSyncRulesContent.d.ts +20 -0
  66. package/dist/storage/PersistedSyncRulesContent.js +2 -0
  67. package/dist/storage/PersistedSyncRulesContent.js.map +1 -0
  68. package/dist/storage/ReplicationEventPayload.d.ts +1 -1
  69. package/dist/storage/ReplicationLock.d.ts +4 -0
  70. package/dist/storage/ReplicationLock.js +2 -0
  71. package/dist/storage/ReplicationLock.js.map +1 -0
  72. package/dist/storage/SourceEntity.d.ts +6 -2
  73. package/dist/storage/SourceTable.d.ts +2 -2
  74. package/dist/storage/SourceTable.js +32 -25
  75. package/dist/storage/SourceTable.js.map +1 -1
  76. package/dist/storage/StorageEngine.d.ts +4 -4
  77. package/dist/storage/StorageEngine.js +6 -5
  78. package/dist/storage/StorageEngine.js.map +1 -1
  79. package/dist/storage/StorageProvider.d.ts +4 -1
  80. package/dist/storage/SyncRulesBucketStorage.d.ts +207 -0
  81. package/dist/storage/SyncRulesBucketStorage.js +7 -0
  82. package/dist/storage/SyncRulesBucketStorage.js.map +1 -0
  83. package/dist/storage/bson.d.ts +19 -6
  84. package/dist/storage/bson.js +18 -2
  85. package/dist/storage/bson.js.map +1 -1
  86. package/dist/storage/storage-index.d.ts +5 -0
  87. package/dist/storage/storage-index.js +5 -0
  88. package/dist/storage/storage-index.js.map +1 -1
  89. package/dist/sync/BroadcastIterable.js +4 -3
  90. package/dist/sync/BroadcastIterable.js.map +1 -1
  91. package/dist/sync/BucketChecksumState.d.ts +95 -0
  92. package/dist/sync/BucketChecksumState.js +321 -0
  93. package/dist/sync/BucketChecksumState.js.map +1 -0
  94. package/dist/sync/LastValueSink.js +2 -0
  95. package/dist/sync/LastValueSink.js.map +1 -1
  96. package/dist/sync/RequestTracker.js +2 -4
  97. package/dist/sync/RequestTracker.js.map +1 -1
  98. package/dist/sync/SyncContext.d.ts +17 -0
  99. package/dist/sync/SyncContext.js +23 -0
  100. package/dist/sync/SyncContext.js.map +1 -0
  101. package/dist/sync/merge.js +4 -0
  102. package/dist/sync/merge.js.map +1 -1
  103. package/dist/sync/sync-index.d.ts +2 -0
  104. package/dist/sync/sync-index.js +2 -0
  105. package/dist/sync/sync-index.js.map +1 -1
  106. package/dist/sync/sync.d.ts +10 -4
  107. package/dist/sync/sync.js +143 -149
  108. package/dist/sync/sync.js.map +1 -1
  109. package/dist/sync/util.d.ts +9 -0
  110. package/dist/sync/util.js +46 -2
  111. package/dist/sync/util.js.map +1 -1
  112. package/dist/system/ServiceContext.d.ts +3 -0
  113. package/dist/system/ServiceContext.js +10 -0
  114. package/dist/system/ServiceContext.js.map +1 -1
  115. package/dist/util/Mutex.js +5 -0
  116. package/dist/util/Mutex.js.map +1 -1
  117. package/dist/util/checkpointing.d.ts +13 -0
  118. package/dist/util/checkpointing.js +29 -0
  119. package/dist/util/checkpointing.js.map +1 -0
  120. package/dist/util/config/compound-config-collector.js +16 -2
  121. package/dist/util/config/compound-config-collector.js.map +1 -1
  122. package/dist/util/config/defaults.d.ts +5 -0
  123. package/dist/util/config/defaults.js +6 -0
  124. package/dist/util/config/defaults.js.map +1 -0
  125. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +1 -0
  126. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -1
  127. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +1 -0
  128. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -1
  129. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.js +1 -0
  130. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.js.map +1 -1
  131. package/dist/util/config/sync-rules/sync-rules-provider.d.ts +2 -0
  132. package/dist/util/config/sync-rules/sync-rules-provider.js +4 -0
  133. package/dist/util/config/sync-rules/sync-rules-provider.js.map +1 -1
  134. package/dist/util/config/types.d.ts +8 -2
  135. package/dist/util/config/types.js.map +1 -1
  136. package/dist/util/memory-tracking.js +1 -1
  137. package/dist/util/memory-tracking.js.map +1 -1
  138. package/dist/util/protocol-types.d.ts +13 -4
  139. package/dist/util/util-index.d.ts +1 -0
  140. package/dist/util/util-index.js +1 -0
  141. package/dist/util/util-index.js.map +1 -1
  142. package/dist/util/utils.d.ts +0 -1
  143. package/dist/util/utils.js +0 -9
  144. package/dist/util/utils.js.map +1 -1
  145. package/package.json +6 -6
  146. package/src/api/RouteAPI.ts +11 -1
  147. package/src/api/diagnostics.ts +1 -1
  148. package/src/entry/commands/compact-action.ts +2 -3
  149. package/src/modules/AbstractModule.ts +1 -1
  150. package/src/replication/AbstractReplicator.ts +16 -15
  151. package/src/routes/RouterEngine.ts +1 -0
  152. package/src/routes/endpoints/admin.ts +4 -1
  153. package/src/routes/endpoints/checkpointing.ts +11 -22
  154. package/src/routes/endpoints/socket-route.ts +9 -6
  155. package/src/routes/endpoints/sync-rules.ts +7 -2
  156. package/src/routes/endpoints/sync-stream.ts +10 -6
  157. package/src/runner/teardown.ts +1 -1
  158. package/src/storage/BucketStorage.ts +8 -515
  159. package/src/storage/BucketStorageBatch.ts +158 -0
  160. package/src/storage/BucketStorageFactory.ts +166 -0
  161. package/src/storage/ChecksumCache.ts +1 -0
  162. package/src/storage/PersistedSyncRulesContent.ts +26 -0
  163. package/src/storage/ReplicationEventPayload.ts +1 -1
  164. package/src/storage/ReplicationLock.ts +5 -0
  165. package/src/storage/SourceEntity.ts +6 -2
  166. package/src/storage/SourceTable.ts +1 -1
  167. package/src/storage/StorageEngine.ts +4 -4
  168. package/src/storage/StorageProvider.ts +4 -1
  169. package/src/storage/SyncRulesBucketStorage.ts +265 -0
  170. package/src/storage/bson.ts +31 -11
  171. package/src/storage/storage-index.ts +5 -0
  172. package/src/sync/BucketChecksumState.ts +418 -0
  173. package/src/sync/SyncContext.ts +36 -0
  174. package/src/sync/sync-index.ts +2 -0
  175. package/src/sync/sync.ts +199 -177
  176. package/src/sync/util.ts +54 -0
  177. package/src/system/ServiceContext.ts +9 -0
  178. package/src/util/checkpointing.ts +41 -0
  179. package/src/util/config/compound-config-collector.ts +26 -2
  180. package/src/util/config/defaults.ts +5 -0
  181. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +1 -0
  182. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +1 -0
  183. package/src/util/config/sync-rules/impl/inline-sync-rules-collector.ts +1 -0
  184. package/src/util/config/sync-rules/sync-rules-provider.ts +6 -0
  185. package/src/util/config/types.ts +9 -2
  186. package/src/util/memory-tracking.ts +2 -2
  187. package/src/util/protocol-types.ts +16 -4
  188. package/src/util/util-index.ts +1 -0
  189. package/src/util/utils.ts +0 -10
  190. package/test/src/auth.test.ts +5 -5
  191. package/test/src/sync/BucketChecksumState.test.ts +580 -0
  192. package/test/src/sync/util.test.ts +34 -0
  193. package/tsconfig.tsbuildinfo +1 -1
@@ -1,33 +1,4 @@
1
- import {
2
- AsyncDisposableObserverClient,
3
- DisposableListener,
4
- DisposableObserverClient
5
- } from '@powersync/lib-services-framework';
6
- import {
7
- EvaluatedParameters,
8
- EvaluatedRow,
9
- SqlSyncRules,
10
- SqliteJsonRow,
11
- SqliteJsonValue,
12
- SqliteRow,
13
- ToastableSqliteRow
14
- } from '@powersync/service-sync-rules';
15
- import { BSON } from 'bson';
16
- import * as util from '../util/util-index.js';
17
- import { ReplicationEventPayload } from './ReplicationEventPayload.js';
18
- import { SourceEntityDescriptor } from './SourceEntity.js';
19
- import { SourceTable } from './SourceTable.js';
20
- import { BatchedCustomWriteCheckpointOptions } from './storage-index.js';
21
- import { SyncStorageWriteCheckpointAPI } from './WriteCheckpointAPI.js';
22
-
23
- /**
24
- * Replica id uniquely identifying a row on the source database.
25
- *
26
- * Can be any value serializable to BSON.
27
- *
28
- * If the value is an entire document, the data serialized to a v5 UUID may be a good choice here.
29
- */
30
- export type ReplicaId = BSON.UUID | BSON.Document | any;
1
+ import { ToastableSqliteRow } from '@powersync/service-sync-rules';
31
2
 
32
3
  export enum SyncRuleState {
33
4
  /**
@@ -41,7 +12,7 @@ export enum SyncRuleState {
41
12
  /**
42
13
  * Sync rule processing is done, and can be used for sync.
43
14
  *
44
- * Only one set of sync rules should be in ACTIVE state.
15
+ * Only one set of sync rules should be in ACTIVE or ERRORED state.
45
16
  */
46
17
  ACTIVE = 'ACTIVE',
47
18
  /**
@@ -53,446 +24,21 @@ export enum SyncRuleState {
53
24
  * After sync rules have been stopped, the data needs to be
54
25
  * deleted. Once deleted, the state is TERMINATED.
55
26
  */
56
- TERMINATED = 'TERMINATED'
57
- }
58
- export interface BucketStorageFactoryListener extends DisposableListener {
59
- syncStorageCreated: (storage: SyncRulesBucketStorage) => void;
60
- replicationEvent: (event: ReplicationEventPayload) => void;
61
- }
62
-
63
- export interface BucketStorageFactory extends AsyncDisposableObserverClient<BucketStorageFactoryListener> {
64
- /**
65
- * Update sync rules from configuration, if changed.
66
- */
67
- configureSyncRules(
68
- sync_rules: string,
69
- options?: { lock?: boolean }
70
- ): Promise<{ updated: boolean; persisted_sync_rules?: PersistedSyncRulesContent; lock?: ReplicationLock }>;
71
-
72
- /**
73
- * Get a storage instance to query sync data for specific sync rules.
74
- */
75
- getInstance(options: PersistedSyncRulesContent): SyncRulesBucketStorage;
27
+ TERMINATED = 'TERMINATED',
76
28
 
77
29
  /**
78
- * Deploy new sync rules.
79
- */
80
- updateSyncRules(options: UpdateSyncRulesOptions): Promise<PersistedSyncRulesContent>;
81
-
82
- /**
83
- * Indicate that a slot was removed, and we should re-sync by creating
84
- * a new sync rules instance.
85
- *
86
- * This is roughly the same as deploying a new version of the current sync
87
- * rules, but also accounts for cases where the current sync rules are not
88
- * the latest ones.
89
- *
90
- * Replication should be restarted after this.
30
+ * Sync rules has run into a permanent replication error. It
31
+ * is still the "active" sync rules for syncing to users,
32
+ * but should not replicate anymore.
91
33
  *
92
- * @param slot_name The removed slot
93
- */
94
- slotRemoved(slot_name: string): Promise<void>;
95
-
96
- /**
97
- * Get the sync rules used for querying.
98
- */
99
- getActiveSyncRules(options: ParseSyncRulesOptions): Promise<PersistedSyncRules | null>;
100
-
101
- /**
102
- * Get the sync rules used for querying.
103
- */
104
- getActiveSyncRulesContent(): Promise<PersistedSyncRulesContent | null>;
105
-
106
- /**
107
- * Get the sync rules that will be active next once done with initial replicatino.
108
- */
109
- getNextSyncRules(options: ParseSyncRulesOptions): Promise<PersistedSyncRules | null>;
110
-
111
- /**
112
- * Get the sync rules that will be active next once done with initial replicatino.
113
- */
114
- getNextSyncRulesContent(): Promise<PersistedSyncRulesContent | null>;
115
-
116
- /**
117
- * Get all sync rules currently replicating. Typically this is the "active" and "next" sync rules.
118
- */
119
- getReplicatingSyncRules(): Promise<PersistedSyncRulesContent[]>;
120
-
121
- /**
122
- * Get all sync rules stopped but not terminated yet.
123
- */
124
- getStoppedSyncRules(): Promise<PersistedSyncRulesContent[]>;
125
-
126
- /**
127
- * Same as:
128
- * getInstance(await getActiveSyncRules()).getCheckpoint().
129
- */
130
- getActiveCheckpoint(): Promise<ActiveCheckpoint>;
131
-
132
- /**
133
- * Yields the latest user write checkpoint whenever the sync checkpoint updates.
134
- */
135
- watchWriteCheckpoint(user_id: string, signal: AbortSignal): AsyncIterable<WriteCheckpoint>;
136
-
137
- /**
138
- * Get storage size of active sync rules.
139
- */
140
- getStorageMetrics(): Promise<StorageMetrics>;
141
-
142
- /**
143
- * Get the unique identifier for this instance of Powersync
34
+ * It will transition to STOP when a new sync rules is activated.
144
35
  */
145
- getPowerSyncInstanceId(): Promise<string>;
146
- }
147
-
148
- export interface ReplicationCheckpoint {
149
- readonly checkpoint: util.OpId;
150
- readonly lsn: string | null;
151
- }
152
-
153
- export interface ActiveCheckpoint extends ReplicationCheckpoint {
154
- hasSyncRules(): boolean;
155
-
156
- getBucketStorage(): Promise<SyncRulesBucketStorage | null>;
157
- }
158
-
159
- export interface WriteCheckpoint {
160
- base: ActiveCheckpoint;
161
- writeCheckpoint: bigint | null;
162
- }
163
-
164
- export interface StorageMetrics {
165
- /**
166
- * Size of operations (bucket_data)
167
- */
168
- operations_size_bytes: number;
169
-
170
- /**
171
- * Size of parameter storage.
172
- *
173
- * Replication storage -> raw data as received from Postgres.
174
- */
175
- parameters_size_bytes: number;
176
-
177
- /**
178
- * Size of current_data.
179
- */
180
- replication_size_bytes: number;
181
- }
182
-
183
- export interface ParseSyncRulesOptions {
184
- defaultSchema: string;
185
- }
186
-
187
- export interface PersistedSyncRulesContent {
188
- readonly id: number;
189
- readonly sync_rules_content: string;
190
- readonly slot_name: string;
191
-
192
- readonly last_fatal_error?: string | null;
193
- readonly last_keepalive_ts?: Date | null;
194
- readonly last_checkpoint_ts?: Date | null;
195
-
196
- parsed(options: ParseSyncRulesOptions): PersistedSyncRules;
197
-
198
- lock(): Promise<ReplicationLock>;
199
- }
200
-
201
- export interface ReplicationLock {
202
- sync_rules_id: number;
203
-
204
- release(): Promise<void>;
205
- }
206
-
207
- export interface PersistedSyncRules {
208
- readonly id: number;
209
- readonly sync_rules: SqlSyncRules;
210
- readonly slot_name: string;
211
- }
212
-
213
- export interface UpdateSyncRulesOptions {
214
- content: string;
215
- lock?: boolean;
216
- }
217
-
218
- export interface SyncRulesBucketStorageOptions {
219
- sync_rules: SqlSyncRules;
220
- group_id: number;
36
+ ERRORED = 'ERRORED'
221
37
  }
222
38
 
223
39
  export const DEFAULT_DOCUMENT_BATCH_LIMIT = 1000;
224
40
  export const DEFAULT_DOCUMENT_CHUNK_LIMIT_BYTES = 1 * 1024 * 1024;
225
41
 
226
- export interface BucketDataBatchOptions {
227
- /** Limit number of documents returned. Defaults to 1000. */
228
- limit?: number;
229
-
230
- /**
231
- * Limit size of chunks returned. Defaults to 1MB.
232
- *
233
- * This is a lower bound, not an upper bound. As soon as the chunk size goes over this limit,
234
- * it is returned.
235
- *
236
- * Note that an individual data row can be close to 16MB in size, so this does not help in
237
- * extreme cases.
238
- */
239
- chunkLimitBytes?: number;
240
- }
241
-
242
- export interface StartBatchOptions extends ParseSyncRulesOptions {
243
- zeroLSN: string;
244
- /**
245
- * Whether or not to store a copy of the current data.
246
- *
247
- * This is needed if we need to apply partial updates, for example
248
- * when we get TOAST values from Postgres.
249
- *
250
- * This is not needed when we get the full document from the source
251
- * database, for example from MongoDB.
252
- */
253
- storeCurrentData: boolean;
254
-
255
- /**
256
- * Set to true for initial replication.
257
- *
258
- * This will avoid creating new operations for rows previously replicated.
259
- */
260
- skipExistingRows?: boolean;
261
- }
262
-
263
- export interface SyncRulesBucketStorageListener extends DisposableListener {
264
- batchStarted: (batch: BucketStorageBatch) => void;
265
- }
266
-
267
- export interface SyncRulesBucketStorage
268
- extends DisposableObserverClient<SyncRulesBucketStorageListener>,
269
- SyncStorageWriteCheckpointAPI {
270
- readonly group_id: number;
271
- readonly slot_name: string;
272
-
273
- readonly factory: BucketStorageFactory;
274
-
275
- resolveTable(options: ResolveTableOptions): Promise<ResolveTableResult>;
276
-
277
- startBatch(
278
- options: StartBatchOptions,
279
- callback: (batch: BucketStorageBatch) => Promise<void>
280
- ): Promise<FlushedResult | null>;
281
-
282
- getCheckpoint(): Promise<ReplicationCheckpoint>;
283
-
284
- getParsedSyncRules(options: ParseSyncRulesOptions): SqlSyncRules;
285
-
286
- getParameterSets(checkpoint: util.OpId, lookups: SqliteJsonValue[][]): Promise<SqliteJsonRow[]>;
287
-
288
- /**
289
- * Get a "batch" of data for a checkpoint.
290
- *
291
- * The results will be split into separate SyncBucketData chunks to:
292
- * 1. Separate buckets.
293
- * 2. Limit the size of each individual chunk according to options.batchSizeLimitBytes.
294
- *
295
- * @param checkpoint the checkpoint
296
- * @param dataBuckets current bucket states
297
- * @param options batch size options
298
- */
299
- getBucketDataBatch(
300
- checkpoint: util.OpId,
301
- dataBuckets: Map<string, string>,
302
- options?: BucketDataBatchOptions
303
- ): AsyncIterable<SyncBucketDataBatch>;
304
-
305
- /**
306
- * Compute checksums for a given list of buckets.
307
- *
308
- * Returns zero checksums for any buckets not found.
309
- */
310
- getChecksums(checkpoint: util.OpId, buckets: string[]): Promise<util.ChecksumMap>;
311
-
312
- /**
313
- * Terminate the sync rules.
314
- *
315
- * This clears the storage, and sets state to TERMINATED.
316
- *
317
- * Must only be called on stopped sync rules.
318
- */
319
- terminate(options?: TerminateOptions): Promise<void>;
320
-
321
- getStatus(): Promise<SyncRuleStatus>;
322
-
323
- /**
324
- * Clear the storage, without changing state.
325
- */
326
- clear(): Promise<void>;
327
-
328
- autoActivate(): Promise<void>;
329
-
330
- /**
331
- * Record a replication error.
332
- *
333
- * This could be a recoverable error (e.g. temporary network failure),
334
- * or a permanent error (e.g. missing toast data).
335
- *
336
- * Errors are cleared on commit.
337
- */
338
- reportError(e: any): Promise<void>;
339
-
340
- compact(options?: CompactOptions): Promise<void>;
341
- }
342
-
343
- export interface SyncRuleStatus {
344
- checkpoint_lsn: string | null;
345
- active: boolean;
346
- snapshot_done: boolean;
347
- }
348
- export interface ResolveTableOptions {
349
- group_id: number;
350
- connection_id: number;
351
- connection_tag: string;
352
- entity_descriptor: SourceEntityDescriptor;
353
-
354
- sync_rules: SqlSyncRules;
355
- }
356
-
357
- export interface ResolveTableResult {
358
- table: SourceTable;
359
- dropTables: SourceTable[];
360
- }
361
-
362
- export interface FlushedResult {
363
- flushed_op: string;
364
- }
365
-
366
- export interface BucketBatchStorageListener extends DisposableListener {
367
- replicationEvent: (payload: ReplicationEventPayload) => void;
368
- }
369
-
370
- export interface BucketStorageBatch extends DisposableObserverClient<BucketBatchStorageListener> {
371
- /**
372
- * Save an op, and potentially flush.
373
- *
374
- * This can be an insert, update or delete op.
375
- */
376
- save(record: SaveOptions): Promise<FlushedResult | null>;
377
-
378
- /**
379
- * Replicate a truncate op - deletes all data in the specified tables.
380
- */
381
- truncate(sourceTables: SourceTable[]): Promise<FlushedResult | null>;
382
-
383
- /**
384
- * Drop one or more tables.
385
- *
386
- * This is the same as truncate, but additionally removes the SourceTable record.
387
- */
388
- drop(sourceTables: SourceTable[]): Promise<FlushedResult | null>;
389
-
390
- /**
391
- * Explicitly flush all pending changes in the batch.
392
- *
393
- * This does not create a new checkpoint until `commit()` is called. This means it's
394
- * safe to flush multiple times in the middle of a large transaction.
395
- *
396
- * @returns null if there are no changes to flush.
397
- */
398
- flush(): Promise<FlushedResult | null>;
399
-
400
- /**
401
- * Flush and commit any saved ops. This creates a new checkpoint.
402
- *
403
- * Only call this after a transaction.
404
- */
405
- commit(lsn: string): Promise<boolean>;
406
-
407
- /**
408
- * Advance the checkpoint LSN position, without any associated op.
409
- *
410
- * This must only be called when not inside a transaction.
411
- *
412
- * @returns true if the checkpoint was advanced, false if this was a no-op
413
- */
414
- keepalive(lsn: string): Promise<boolean>;
415
-
416
- /**
417
- * Get the last checkpoint LSN, from either commit or keepalive.
418
- */
419
- lastCheckpointLsn: string | null;
420
-
421
- markSnapshotDone(tables: SourceTable[], no_checkpoint_before_lsn: string): Promise<SourceTable[]>;
422
-
423
- /**
424
- * Queues the creation of a custom Write Checkpoint. This will be persisted after operations are flushed.
425
- */
426
- addCustomWriteCheckpoint(checkpoint: BatchedCustomWriteCheckpointOptions): void;
427
- }
428
-
429
- export interface SaveParameterData {
430
- sourceTable: SourceTable;
431
- /** UUID */
432
- sourceKey: string;
433
- evaluated: EvaluatedParameters[];
434
- }
435
-
436
- export interface SaveBucketData {
437
- sourceTable: SourceTable;
438
- /** UUID */
439
- sourceKey: string;
440
-
441
- evaluated: EvaluatedRow[];
442
- }
443
-
444
- export type SaveOp = 'insert' | 'update' | 'delete';
445
-
446
- export type SaveOptions = SaveInsert | SaveUpdate | SaveDelete;
447
-
448
- export enum SaveOperationTag {
449
- INSERT = 'insert',
450
- UPDATE = 'update',
451
- DELETE = 'delete'
452
- }
453
-
454
- export interface SaveInsert {
455
- tag: SaveOperationTag.INSERT;
456
- sourceTable: SourceTable;
457
- before?: undefined;
458
- beforeReplicaId?: undefined;
459
- after: SqliteRow;
460
- afterReplicaId: ReplicaId;
461
- }
462
-
463
- export interface SaveUpdate {
464
- tag: SaveOperationTag.UPDATE;
465
- sourceTable: SourceTable;
466
-
467
- /**
468
- * This is only present when the id has changed, and will only contain replica identity columns.
469
- */
470
- before?: SqliteRow;
471
- beforeReplicaId?: ReplicaId;
472
-
473
- /**
474
- * A null value means null column.
475
- *
476
- * An undefined value means it's a TOAST value - must be copied from another record.
477
- */
478
- after: ToastableSqliteRow;
479
- afterReplicaId: ReplicaId;
480
- }
481
-
482
- export interface SaveDelete {
483
- tag: SaveOperationTag.DELETE;
484
- sourceTable: SourceTable;
485
- before?: SqliteRow;
486
- beforeReplicaId: ReplicaId;
487
- after?: undefined;
488
- afterReplicaId?: undefined;
489
- }
490
-
491
- export interface SyncBucketDataBatch {
492
- batch: util.SyncBucketData;
493
- targetOp: bigint | null;
494
- }
495
-
496
42
  export function mergeToast(record: ToastableSqliteRow, persisted: ToastableSqliteRow): ToastableSqliteRow {
497
43
  const newRecord: ToastableSqliteRow = {};
498
44
  for (let key in record) {
@@ -504,56 +50,3 @@ export function mergeToast(record: ToastableSqliteRow, persisted: ToastableSqlit
504
50
  }
505
51
  return newRecord;
506
52
  }
507
-
508
- export interface CompactOptions {
509
- /**
510
- * Heap memory limit for the compact process.
511
- *
512
- * Add around 64MB to this to determine the "--max-old-space-size" argument.
513
- * Add another 80MB to get RSS usage / memory limits.
514
- */
515
- memoryLimitMB?: number;
516
-
517
- /**
518
- * If specified, ignore any operations newer than this when compacting.
519
- *
520
- * This is primarily for tests, where we want to test compacting at a specific
521
- * point.
522
- *
523
- * This can also be used to create a "safe buffer" of recent operations that should
524
- * not be compacted, to avoid invalidating checkpoints in use.
525
- */
526
- maxOpId?: bigint;
527
-
528
- /**
529
- * If specified, compact only the specific buckets.
530
- *
531
- * If not specified, compacts all buckets.
532
- *
533
- * These can be individual bucket names, or bucket definition names.
534
- */
535
- compactBuckets?: string[];
536
- }
537
-
538
- export interface TerminateOptions {
539
- /**
540
- * If true, also clear the storage before terminating.
541
- */
542
- clearStorage: boolean;
543
- }
544
-
545
- /**
546
- * Helper for tests.
547
- * This is not in the `service-core-tests` package in order for storage modules
548
- * to provide relevant factories without requiring `service-core-tests` as a direct dependency.
549
- */
550
- export interface TestStorageOptions {
551
- /**
552
- * By default, collections are only cleared/
553
- * Setting this to true will drop the collections completely.
554
- */
555
- dropAll?: boolean;
556
-
557
- doNotClear?: boolean;
558
- }
559
- export type TestStorageFactory = (options?: TestStorageOptions) => Promise<BucketStorageFactory>;
@@ -0,0 +1,158 @@
1
+ import { ObserverClient } from '@powersync/lib-services-framework';
2
+ import { EvaluatedParameters, EvaluatedRow, SqliteRow, ToastableSqliteRow } from '@powersync/service-sync-rules';
3
+ import { BSON } from 'bson';
4
+ import { ReplicationEventPayload } from './ReplicationEventPayload.js';
5
+ import { SourceTable } from './SourceTable.js';
6
+ import { BatchedCustomWriteCheckpointOptions } from './storage-index.js';
7
+
8
+ export const DEFAULT_BUCKET_BATCH_COMMIT_OPTIONS: ResolvedBucketBatchCommitOptions = {
9
+ createEmptyCheckpoints: true
10
+ };
11
+
12
+ export interface BucketStorageBatch extends ObserverClient<BucketBatchStorageListener>, AsyncDisposable {
13
+ /**
14
+ * Save an op, and potentially flush.
15
+ *
16
+ * This can be an insert, update or delete op.
17
+ */
18
+ save(record: SaveOptions): Promise<FlushedResult | null>;
19
+
20
+ /**
21
+ * Replicate a truncate op - deletes all data in the specified tables.
22
+ */
23
+ truncate(sourceTables: SourceTable[]): Promise<FlushedResult | null>;
24
+
25
+ /**
26
+ * Drop one or more tables.
27
+ *
28
+ * This is the same as truncate, but additionally removes the SourceTable record.
29
+ */
30
+ drop(sourceTables: SourceTable[]): Promise<FlushedResult | null>;
31
+
32
+ /**
33
+ * Explicitly flush all pending changes in the batch.
34
+ *
35
+ * This does not create a new checkpoint until `commit()` is called. This means it's
36
+ * safe to flush multiple times in the middle of a large transaction.
37
+ *
38
+ * @returns null if there are no changes to flush.
39
+ */
40
+ flush(): Promise<FlushedResult | null>;
41
+
42
+ /**
43
+ * Flush and commit any saved ops. This creates a new checkpoint by default.
44
+ *
45
+ * Only call this after a transaction.
46
+ */
47
+ commit(lsn: string, options?: BucketBatchCommitOptions): Promise<boolean>;
48
+
49
+ /**
50
+ * Advance the checkpoint LSN position, without any associated op.
51
+ *
52
+ * This must only be called when not inside a transaction.
53
+ *
54
+ * @returns true if the checkpoint was advanced, false if this was a no-op
55
+ */
56
+ keepalive(lsn: string): Promise<boolean>;
57
+
58
+ /**
59
+ * Get the last checkpoint LSN, from either commit or keepalive.
60
+ */
61
+ lastCheckpointLsn: string | null;
62
+
63
+ markSnapshotDone(tables: SourceTable[], no_checkpoint_before_lsn: string): Promise<SourceTable[]>;
64
+
65
+ /**
66
+ * Queues the creation of a custom Write Checkpoint. This will be persisted after operations are flushed.
67
+ */
68
+ addCustomWriteCheckpoint(checkpoint: BatchedCustomWriteCheckpointOptions): void;
69
+ }
70
+
71
+ /**
72
+ * Replica id uniquely identifying a row on the source database.
73
+ *
74
+ * Can be any value serializable to BSON.
75
+ *
76
+ * If the value is an entire document, the data serialized to a v5 UUID may be a good choice here.
77
+ */
78
+ export type ReplicaId = BSON.UUID | BSON.Document | any;
79
+
80
+ export interface SaveParameterData {
81
+ sourceTable: SourceTable;
82
+ /** UUID */
83
+ sourceKey: string;
84
+ evaluated: EvaluatedParameters[];
85
+ }
86
+
87
+ export interface SaveBucketData {
88
+ sourceTable: SourceTable;
89
+ /** UUID */
90
+ sourceKey: string;
91
+
92
+ evaluated: EvaluatedRow[];
93
+ }
94
+
95
+ export type SaveOp = 'insert' | 'update' | 'delete';
96
+
97
+ export type SaveOptions = SaveInsert | SaveUpdate | SaveDelete;
98
+
99
+ export enum SaveOperationTag {
100
+ INSERT = 'insert',
101
+ UPDATE = 'update',
102
+ DELETE = 'delete'
103
+ }
104
+
105
+ export interface SaveInsert {
106
+ tag: SaveOperationTag.INSERT;
107
+ sourceTable: SourceTable;
108
+ before?: undefined;
109
+ beforeReplicaId?: undefined;
110
+ after: SqliteRow;
111
+ afterReplicaId: ReplicaId;
112
+ }
113
+
114
+ export interface SaveUpdate {
115
+ tag: SaveOperationTag.UPDATE;
116
+ sourceTable: SourceTable;
117
+
118
+ /**
119
+ * This is only present when the id has changed, and will only contain replica identity columns.
120
+ */
121
+ before?: SqliteRow;
122
+ beforeReplicaId?: ReplicaId;
123
+
124
+ /**
125
+ * A null value means null column.
126
+ *
127
+ * An undefined value means it's a TOAST value - must be copied from another record.
128
+ */
129
+ after: ToastableSqliteRow;
130
+ afterReplicaId: ReplicaId;
131
+ }
132
+
133
+ export interface SaveDelete {
134
+ tag: SaveOperationTag.DELETE;
135
+ sourceTable: SourceTable;
136
+ before?: SqliteRow;
137
+ beforeReplicaId: ReplicaId;
138
+ after?: undefined;
139
+ afterReplicaId?: undefined;
140
+ }
141
+
142
+ export interface BucketBatchStorageListener {
143
+ replicationEvent: (payload: ReplicationEventPayload) => void;
144
+ }
145
+
146
+ export interface FlushedResult {
147
+ flushed_op: string;
148
+ }
149
+
150
+ export interface BucketBatchCommitOptions {
151
+ /**
152
+ * Creates a new checkpoint even if there were no persisted operations.
153
+ * Defaults to true.
154
+ */
155
+ createEmptyCheckpoints?: boolean;
156
+ }
157
+
158
+ export type ResolvedBucketBatchCommitOptions = Required<BucketBatchCommitOptions>;