@powersync/service-module-mongodb-storage 0.0.0-dev-20260803144812 → 0.0.0-dev-20260929095716

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/CHANGELOG.md +129 -7
  2. package/dist/storage/MongoBucketStorage.d.ts +42 -5
  3. package/dist/storage/MongoBucketStorage.js +404 -215
  4. package/dist/storage/MongoBucketStorage.js.map +1 -1
  5. package/dist/storage/implementation/MongoBucketBatch.d.ts +39 -14
  6. package/dist/storage/implementation/MongoBucketBatch.js +169 -98
  7. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  8. package/dist/storage/implementation/MongoCompactor.d.ts +21 -79
  9. package/dist/storage/implementation/MongoCompactor.js +27 -238
  10. package/dist/storage/implementation/MongoCompactor.js.map +1 -1
  11. package/dist/storage/implementation/MongoIdSequence.d.ts +10 -1
  12. package/dist/storage/implementation/MongoIdSequence.js +14 -1
  13. package/dist/storage/implementation/MongoIdSequence.js.map +1 -1
  14. package/dist/storage/implementation/MongoOpIdAllocator.d.ts +27 -0
  15. package/dist/storage/implementation/MongoOpIdAllocator.js +97 -0
  16. package/dist/storage/implementation/MongoOpIdAllocator.js.map +1 -0
  17. package/dist/storage/implementation/MongoParameterCompactor.d.ts +83 -10
  18. package/dist/storage/implementation/MongoParameterCompactor.js +309 -96
  19. package/dist/storage/implementation/MongoParameterCompactor.js.map +1 -1
  20. package/dist/storage/implementation/MongoParsedSyncConfigSet.d.ts +9 -1
  21. package/dist/storage/implementation/MongoParsedSyncConfigSet.js +35 -2
  22. package/dist/storage/implementation/MongoParsedSyncConfigSet.js.map +1 -1
  23. package/dist/storage/implementation/MongoPersistedReplicationStream.d.ts +2 -1
  24. package/dist/storage/implementation/MongoPersistedReplicationStream.js +7 -4
  25. package/dist/storage/implementation/MongoPersistedReplicationStream.js.map +1 -1
  26. package/dist/storage/implementation/MongoPersistedSyncConfigContent.d.ts +3 -3
  27. package/dist/storage/implementation/MongoPersistedSyncConfigContent.js +10 -8
  28. package/dist/storage/implementation/MongoPersistedSyncConfigContent.js.map +1 -1
  29. package/dist/storage/implementation/MongoStorageProvider.js +8 -4
  30. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  31. package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +32 -11
  32. package/dist/storage/implementation/MongoSyncBucketStorage.js +95 -31
  33. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  34. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +26 -2
  35. package/dist/storage/implementation/MongoSyncRulesLock.js +59 -10
  36. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  37. package/dist/storage/implementation/MongoWriteBatch.d.ts +49 -0
  38. package/dist/storage/implementation/MongoWriteBatch.js +149 -0
  39. package/dist/storage/implementation/MongoWriteBatch.js.map +1 -0
  40. package/dist/storage/implementation/MongoWriteCheckpointAPI.d.ts +9 -7
  41. package/dist/storage/implementation/MongoWriteCheckpointAPI.js +9 -30
  42. package/dist/storage/implementation/MongoWriteCheckpointAPI.js.map +1 -1
  43. package/dist/storage/implementation/SyncRuleStateUpdate.d.ts +11 -5
  44. package/dist/storage/implementation/SyncRuleStateUpdate.js +14 -6
  45. package/dist/storage/implementation/SyncRuleStateUpdate.js.map +1 -1
  46. package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.d.ts +22 -2
  47. package/dist/storage/implementation/common/PersistedBatch.d.ts +32 -4
  48. package/dist/storage/implementation/common/PersistedBatch.js +57 -14
  49. package/dist/storage/implementation/common/PersistedBatch.js.map +1 -1
  50. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.d.ts +3 -0
  51. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js +3 -0
  52. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js.map +1 -1
  53. package/dist/storage/implementation/db.d.ts +9 -1
  54. package/dist/storage/implementation/db.js +28 -1
  55. package/dist/storage/implementation/db.js.map +1 -1
  56. package/dist/storage/implementation/models.d.ts +35 -0
  57. package/dist/storage/implementation/models.js.map +1 -1
  58. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +11 -0
  59. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +227 -221
  60. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  61. package/dist/storage/implementation/v1/MongoCompactorV1.d.ts +38 -6
  62. package/dist/storage/implementation/v1/MongoCompactorV1.js +247 -20
  63. package/dist/storage/implementation/v1/MongoCompactorV1.js.map +1 -1
  64. package/dist/storage/implementation/v1/MongoParameterCompactorV1.d.ts +16 -2
  65. package/dist/storage/implementation/v1/MongoParameterCompactorV1.js +20 -9
  66. package/dist/storage/implementation/v1/MongoParameterCompactorV1.js.map +1 -1
  67. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.d.ts +18 -11
  68. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js +66 -17
  69. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js.map +1 -1
  70. package/dist/storage/implementation/v1/PersistedBatchV1.d.ts +7 -5
  71. package/dist/storage/implementation/v1/PersistedBatchV1.js +22 -28
  72. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  73. package/dist/storage/implementation/v1/models.js +1 -0
  74. package/dist/storage/implementation/v1/models.js.map +1 -1
  75. package/dist/storage/implementation/v3/CompactionLease.d.ts +50 -0
  76. package/dist/storage/implementation/v3/CompactionLease.js +131 -0
  77. package/dist/storage/implementation/v3/CompactionLease.js.map +1 -0
  78. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +14 -2
  79. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +261 -194
  80. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  81. package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +83 -25
  82. package/dist/storage/implementation/v3/MongoCompactorV3.js +702 -159
  83. package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
  84. package/dist/storage/implementation/v3/MongoParameterCompactorV3.d.ts +18 -0
  85. package/dist/storage/implementation/v3/MongoParameterCompactorV3.js +23 -0
  86. package/dist/storage/implementation/v3/MongoParameterCompactorV3.js.map +1 -0
  87. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.d.ts +2 -15
  88. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js +60 -92
  89. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js.map +1 -1
  90. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.d.ts +19 -9
  91. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js +92 -32
  92. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js.map +1 -1
  93. package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.d.ts +26 -0
  94. package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js +82 -0
  95. package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js.map +1 -0
  96. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -8
  97. package/dist/storage/implementation/v3/PersistedBatchV3.js +77 -45
  98. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  99. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.d.ts +12 -2
  100. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js +42 -3
  101. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js.map +1 -1
  102. package/dist/storage/implementation/v3/bucket-format.js +2 -0
  103. package/dist/storage/implementation/v3/bucket-format.js.map +1 -1
  104. package/dist/storage/implementation/v3/compact-utils.d.ts +108 -0
  105. package/dist/storage/implementation/v3/compact-utils.js +223 -0
  106. package/dist/storage/implementation/v3/compact-utils.js.map +1 -0
  107. package/dist/storage/implementation/v3/compaction-constants.d.ts +5 -0
  108. package/dist/storage/implementation/v3/compaction-constants.js +6 -0
  109. package/dist/storage/implementation/v3/compaction-constants.js.map +1 -0
  110. package/dist/storage/implementation/v3/models.d.ts +90 -6
  111. package/dist/storage/implementation/v3/models.js.map +1 -1
  112. package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.d.ts +7 -8
  113. package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js +16 -5
  114. package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js.map +1 -1
  115. package/dist/storage/implementation/v3/object-storage/ObjectStorage.d.ts +14 -11
  116. package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.d.ts +6 -8
  117. package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js +17 -11
  118. package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js.map +1 -1
  119. package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.d.ts +38 -0
  120. package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js +164 -0
  121. package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js.map +1 -0
  122. package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.d.ts +37 -12
  123. package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js +197 -25
  124. package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js.map +1 -1
  125. package/dist/storage/implementation/v3/source-table-utils.d.ts +15 -7
  126. package/dist/storage/implementation/v3/source-table-utils.js +49 -57
  127. package/dist/storage/implementation/v3/source-table-utils.js.map +1 -1
  128. package/dist/storage/storage-index.d.ts +2 -1
  129. package/dist/storage/storage-index.js +1 -0
  130. package/dist/storage/storage-index.js.map +1 -1
  131. package/dist/types/types.d.ts +28 -1
  132. package/dist/types/types.js +28 -7
  133. package/dist/types/types.js.map +1 -1
  134. package/dist/utils/test-utils.d.ts +4 -2
  135. package/dist/utils/test-utils.js +7 -4
  136. package/dist/utils/test-utils.js.map +1 -1
  137. package/dist/utils/util.js +3 -1
  138. package/dist/utils/util.js.map +1 -1
  139. package/package.json +10 -9
  140. package/src/storage/MongoBucketStorage.ts +545 -277
  141. package/src/storage/implementation/MongoBucketBatch.ts +258 -124
  142. package/src/storage/implementation/MongoCompactor.ts +37 -346
  143. package/src/storage/implementation/MongoIdSequence.ts +21 -1
  144. package/src/storage/implementation/MongoOpIdAllocator.ts +105 -0
  145. package/src/storage/implementation/MongoParameterCompactor.ts +388 -102
  146. package/src/storage/implementation/MongoParsedSyncConfigSet.ts +46 -1
  147. package/src/storage/implementation/MongoPersistedReplicationStream.ts +12 -4
  148. package/src/storage/implementation/MongoPersistedSyncConfigContent.ts +48 -29
  149. package/src/storage/implementation/MongoStorageProvider.ts +16 -4
  150. package/src/storage/implementation/MongoSyncBucketStorage.ts +133 -40
  151. package/src/storage/implementation/MongoSyncRulesLock.ts +78 -12
  152. package/src/storage/implementation/MongoWriteBatch.ts +172 -0
  153. package/src/storage/implementation/MongoWriteCheckpointAPI.ts +16 -46
  154. package/src/storage/implementation/SyncRuleStateUpdate.ts +13 -6
  155. package/src/storage/implementation/common/MongoSyncBucketStorageCheckpoint.ts +24 -2
  156. package/src/storage/implementation/common/PersistedBatch.ts +76 -20
  157. package/src/storage/implementation/common/VersionedPowerSyncMongoBase.ts +4 -0
  158. package/src/storage/implementation/db.ts +36 -2
  159. package/src/storage/implementation/models.ts +39 -0
  160. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +272 -254
  161. package/src/storage/implementation/v1/MongoCompactorV1.ts +327 -40
  162. package/src/storage/implementation/v1/MongoParameterCompactorV1.ts +25 -9
  163. package/src/storage/implementation/v1/MongoSyncBucketStorageV1.ts +88 -28
  164. package/src/storage/implementation/v1/PersistedBatchV1.ts +25 -30
  165. package/src/storage/implementation/v1/models.ts +1 -0
  166. package/src/storage/implementation/v3/CompactionLease.ts +152 -0
  167. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +339 -247
  168. package/src/storage/implementation/v3/MongoCompactorV3.ts +955 -225
  169. package/src/storage/implementation/v3/MongoParameterCompactorV3.ts +34 -0
  170. package/src/storage/implementation/v3/MongoStoppedSyncConfigCleanup.ts +100 -109
  171. package/src/storage/implementation/v3/MongoSyncBucketStorageV3.ts +112 -42
  172. package/src/storage/implementation/v3/MongoWriteCheckpointAPIV3.ts +111 -0
  173. package/src/storage/implementation/v3/PersistedBatchV3.ts +94 -51
  174. package/src/storage/implementation/v3/VersionedPowerSyncMongoV3.ts +55 -4
  175. package/src/storage/implementation/v3/bucket-format.ts +2 -0
  176. package/src/storage/implementation/v3/compact-utils.ts +329 -0
  177. package/src/storage/implementation/v3/compaction-constants.ts +5 -0
  178. package/src/storage/implementation/v3/models.ts +97 -4
  179. package/src/storage/implementation/v3/object-storage/BucketDataObjectStorage.ts +24 -9
  180. package/src/storage/implementation/v3/object-storage/ObjectStorage.ts +20 -5
  181. package/src/storage/implementation/v3/object-storage/ObjectStorageLifecycle.ts +26 -14
  182. package/src/storage/implementation/v3/object-storage/ObjectStorageUsage.ts +229 -0
  183. package/src/storage/implementation/v3/object-storage/S3ObjectStorage.ts +279 -29
  184. package/src/storage/implementation/v3/source-table-utils.ts +82 -76
  185. package/src/storage/storage-index.ts +2 -0
  186. package/src/types/types.ts +42 -7
  187. package/src/utils/test-utils.ts +9 -5
  188. package/src/utils/util.ts +3 -1
  189. package/test/src/__snapshots__/storage.test.ts.snap +25 -0
  190. package/test/src/__snapshots__/storage_sync.test.ts.snap +794 -205
  191. package/test/src/chunk_compaction_config.test.ts +38 -0
  192. package/test/src/cleanup-stopped-sync-configs.test.ts +59 -26
  193. package/test/src/compact-utils.test.ts +251 -0
  194. package/test/src/concurrent_writers.test.ts +599 -0
  195. package/test/src/connection_config.test.ts +159 -0
  196. package/test/src/helpers/MemoryObjectStorage.ts +14 -6
  197. package/test/src/helpers/concurrentWriter.mjs +29 -0
  198. package/test/src/helpers/s3TestFactory.ts +12 -12
  199. package/test/src/object_storage_usage.test.ts +268 -0
  200. package/test/src/parameter_compacting_v1.test.ts +120 -0
  201. package/test/src/parameter_compacting_v3.test.ts +192 -0
  202. package/test/src/parameter_compaction_fence.test.ts +276 -0
  203. package/test/src/storage.test.ts +280 -24
  204. package/test/src/storage_compacting.test.ts +1097 -253
  205. package/test/src/storage_object_storage_inline_threshold.test.ts +3 -3
  206. package/test/src/storage_s3_checksums.test.ts +6 -7
  207. package/test/src/storage_s3_compaction_lifecycle.test.ts +143 -17
  208. package/test/src/storage_s3_reading.test.ts +294 -6
  209. package/test/src/storage_s3_writing.test.ts +4 -3
  210. package/test/src/storage_sync.test.ts +412 -80
  211. package/test/src/storeCurrentData.test.ts +5 -5
  212. package/test/src/util.ts +1 -1
  213. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,329 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
3
+ import { addChecksums, InternalOpId } from '@powersync/service-core';
4
+ import { BucketDataDoc } from '../common/BucketDataDoc.js';
5
+ import { AVAILABLE_LEASE_EXPR, CompactionLease } from './CompactionLease.js';
6
+ import { BucketDataDocumentV3, BucketStateDocumentV3 } from './models.js';
7
+
8
+ /**
9
+ * Perform chunk compaction if at least this many chunks have been added since
10
+ * the latest compaction.
11
+ *
12
+ * A lower value increases compaction frequency and can increase chunk rewrites
13
+ * and object-storage operations. A higher value leaves more small chunks for
14
+ * longer, which can hurt sync performance.
15
+ */
16
+ const MERGE_CHUNKS_THRESHOLD = 8;
17
+
18
+ export const FULL_COMPACT_RESCHEDULE_MARGIN_MS = 60 * 1000;
19
+
20
+ export interface PendingCompactionGroup {
21
+ /**
22
+ * Input documents are ordered from oldest to newest, matching `ops`.
23
+ * Keeping the inputs intact lets unchanged singletons retain their object.
24
+ */
25
+ inputs: BucketDataDocumentV3[];
26
+ ops: BucketDataDoc[];
27
+ changed: boolean;
28
+ targetOp: InternalOpId | null;
29
+ }
30
+
31
+ export interface CompactIntervalConfig {
32
+ readonly minCompactChunkIntervalMs: number;
33
+ readonly minCompactFullIntervalMs: number;
34
+ readonly maxCompactFullIntervalMs: number;
35
+ }
36
+ export interface CompactTargetConfig {
37
+ readonly maxOpIdCap: InternalOpId | undefined;
38
+ readonly forceChunkCompaction?: boolean;
39
+ }
40
+
41
+ export enum CompactionKind {
42
+ Full = 'full',
43
+ Chunks = 'chunks'
44
+ }
45
+
46
+ export interface CompactionDecision {
47
+ kind: CompactionKind | null;
48
+ nextCompactCheck: mongo.Document;
49
+ }
50
+
51
+ export interface ScheduledCompactionOptions {
52
+ /** Process checks scheduled this far after the captured job start. */
53
+ dueAheadMs?: number;
54
+ /** Used by initial replication, which must not run a full compact. */
55
+ requestedKind?: CompactionKind;
56
+ }
57
+
58
+ export class CompactionContext {
59
+ constructor(
60
+ readonly lease: CompactionLease,
61
+ readonly kind: CompactionKind,
62
+ readonly decision: CompactionDecision,
63
+ readonly rescheduleNotBefore: Date | undefined,
64
+ readonly targetOp: InternalOpId
65
+ ) {}
66
+
67
+ get state() {
68
+ return this.lease.state;
69
+ }
70
+
71
+ get startedAt() {
72
+ return this.lease.startedAt;
73
+ }
74
+
75
+ get lastOp() {
76
+ return this.lease.lastOp;
77
+ }
78
+ }
79
+
80
+ export interface BucketStats {
81
+ count: number;
82
+ bytes: bigint;
83
+ chunks: number;
84
+ }
85
+
86
+ /** Bucket stats read from bucket-data documents, including their checksum. */
87
+ export interface BucketStatsWithChecksum extends BucketStats {
88
+ checksum: number;
89
+ }
90
+
91
+ export interface CompactionResult {
92
+ /** Metadata cached at compacted_state.op_id. */
93
+ compactedState: BucketStatsWithChecksum;
94
+ /** Complete bucket metadata through the op head captured at claim time. */
95
+ bucketStats: BucketStats;
96
+ }
97
+
98
+ export function bucketStats(state: BucketStateDocumentV3): BucketStats {
99
+ return {
100
+ count: state.bucket_stats.count,
101
+ bytes: state.bucket_stats.bytes,
102
+ chunks: state.bucket_stats.chunks
103
+ };
104
+ }
105
+
106
+ export function emptyBucketStats(): BucketStatsWithChecksum {
107
+ return { count: 0, bytes: 0n, chunks: 0, checksum: 0 };
108
+ }
109
+
110
+ export function statsForDocument(
111
+ document: Pick<BucketDataDocumentV3, 'count' | 'size' | 'checksum'>
112
+ ): BucketStatsWithChecksum {
113
+ return {
114
+ count: document.count,
115
+ bytes: BigInt(document.size),
116
+ chunks: 1,
117
+ checksum: addChecksums(0, Number(document.checksum))
118
+ };
119
+ }
120
+
121
+ export function statsForDocuments(
122
+ documents: Iterable<Pick<BucketDataDocumentV3, 'count' | 'size' | 'checksum'>>
123
+ ): BucketStatsWithChecksum {
124
+ let result = emptyBucketStats();
125
+ for (const document of documents) {
126
+ result = combineAdjacentStats(result, statsForDocument(document));
127
+ }
128
+ return result;
129
+ }
130
+
131
+ /** A scheduled bucket always has writes awaiting a full compact. */
132
+ export function firstUncompactedWrite(state: BucketStateDocumentV3): Date {
133
+ if (state.first_uncompacted_write == null) {
134
+ throw new ReplicationAssertionError(`Scheduled V3 bucket ${state._id.b} has no first uncompacted write`);
135
+ }
136
+ return state.first_uncompacted_write;
137
+ }
138
+
139
+ export function combineChunkStats(
140
+ previous: NonNullable<BucketStateDocumentV3['compacted_state']>,
141
+ compactedTail: BucketStatsWithChecksum,
142
+ overlappingCompactedChunk: BucketStatsWithChecksum
143
+ ): BucketStatsWithChecksum {
144
+ return {
145
+ count: previous.count - overlappingCompactedChunk.count + compactedTail.count,
146
+ bytes: previous.bytes - overlappingCompactedChunk.bytes + compactedTail.bytes,
147
+ chunks: previous.chunks - 1 + compactedTail.chunks,
148
+ checksum: addChecksums(
149
+ addChecksums(Number(previous.checksum), -overlappingCompactedChunk.checksum),
150
+ compactedTail.checksum
151
+ )
152
+ };
153
+ }
154
+
155
+ export function combineAdjacentStats(
156
+ first: BucketStatsWithChecksum,
157
+ second: BucketStatsWithChecksum
158
+ ): BucketStatsWithChecksum {
159
+ return {
160
+ count: first.count + second.count,
161
+ bytes: first.bytes + second.bytes,
162
+ chunks: first.chunks + second.chunks,
163
+ checksum: addChecksums(first.checksum, second.checksum)
164
+ };
165
+ }
166
+
167
+ export function applyCompactionDelta(
168
+ total: BucketStats,
169
+ before: BucketStatsWithChecksum,
170
+ after: BucketStatsWithChecksum
171
+ ): BucketStats {
172
+ return {
173
+ count: total.count - before.count + after.count,
174
+ bytes: total.bytes - before.bytes + after.bytes,
175
+ chunks: total.chunks - before.chunks + after.chunks
176
+ };
177
+ }
178
+
179
+ /** Replace one stored range in an accumulated statistics snapshot. */
180
+ export function applyStatsReplacement(
181
+ total: BucketStatsWithChecksum,
182
+ before: BucketStatsWithChecksum,
183
+ after: BucketStatsWithChecksum
184
+ ): BucketStatsWithChecksum {
185
+ return {
186
+ ...applyCompactionDelta(total, before, after),
187
+ checksum: addChecksums(addChecksums(total.checksum, -before.checksum), after.checksum)
188
+ };
189
+ }
190
+
191
+ /**
192
+ * This checks that the bucket state hasn't changed by a concurrent write since we checked.
193
+ *
194
+ * If it has changed, we'll re-check in the next batch.
195
+ */
196
+ export function unclaimedSnapshotFilter(state: BucketStateDocumentV3): mongo.Filter<BucketStateDocumentV3> {
197
+ return {
198
+ _id: state._id,
199
+ last_op: state.last_op,
200
+ next_compact_check: state.next_compact_check,
201
+ first_uncompacted_write: state.first_uncompacted_write ?? { $exists: false },
202
+ bucket_stats: state.bucket_stats,
203
+ compacted_state: state.compacted_state ?? { $exists: false },
204
+ last_full_compact: state.last_full_compact ?? { $exists: false },
205
+ ...AVAILABLE_LEASE_EXPR
206
+ };
207
+ }
208
+
209
+ /**
210
+ * Calculate the earliest full compaction time from the first uncompacted
211
+ * write, bounded by the maximum retention interval.
212
+ */
213
+ export function fullCompactionCheckAt(state: BucketStateDocumentV3, config: CompactIntervalConfig): Date {
214
+ const firstWrite = firstUncompactedWrite(state);
215
+ const stats = bucketStats(state);
216
+ const lastFull = state.last_full_compact;
217
+
218
+ // The number of operations since the last full compact.
219
+ // We may make this more specific in the future, to track new updates and deletes only, ignoring
220
+ // full new inserts, but that requires more granular tracking when replicating.
221
+ const uncompactedCount = lastFull == null ? stats.count : Math.max(0, stats.count - lastFull.count);
222
+ const compactedRows = lastFull?.puts ?? 0;
223
+
224
+ // If no full compact has ever been performed: ratio = 1, compact after minCompactFullIntervalMs.
225
+ // If every row has been updated or deleted exactly once since the last full compact: ratio = 0.5, compact after minCompactFullIntervalMs * 2.
226
+ // If 10% of rows has been updated since the last full compact, compact after minCompactFullIntervalMs * 11.
227
+ // If every row has been updated multiple times, the ratio tends closer to 1 again.
228
+ const ratio = uncompactedCount == 0 ? 0 : uncompactedCount / (compactedRows + uncompactedCount);
229
+ const fullIntervalMs = ratio == 0 ? config.maxCompactFullIntervalMs : config.minCompactFullIntervalMs / ratio;
230
+ return new Date(firstWrite.getTime() + Math.min(fullIntervalMs, config.maxCompactFullIntervalMs));
231
+ }
232
+
233
+ export function chooseCompactionKind(
234
+ state: BucketStateDocumentV3,
235
+ now: Date,
236
+ config: CompactIntervalConfig
237
+ ): CompactionDecision {
238
+ // For chunk compaction, we consider the number of chunks added.
239
+ // Right now, we trigger a compact if the interval has passed and at least a threshold of chunks were added.
240
+ // A future policy could also use bytes per chunk or records per chunk to
241
+ // decide when to compact.
242
+ const fullCheckAt = fullCompactionCheckAt(state, config);
243
+ // Schedule a little late so a worker using a slightly earlier clock does
244
+ // not wake before the exact full-compaction condition is true.
245
+ const fullCheckWithMargin = new Date(fullCheckAt.getTime() + FULL_COMPACT_RESCHEDULE_MARGIN_MS);
246
+ const compacted = state.compacted_state;
247
+ const shouldCompactChunks = hasEnoughChunksToMerge(state);
248
+ const canCheckChunks =
249
+ compacted == null || now.getTime() - compacted.at.getTime() >= config.minCompactChunkIntervalMs;
250
+ // Too few new chunks cannot make chunk compaction eligible. Do not poll this
251
+ // bucket at the chunk-compaction interval; only wake it for its full-compact check.
252
+ const nextCompactCheck: mongo.Document = !shouldCompactChunks
253
+ ? fullCheckWithMargin
254
+ : {
255
+ $min: [
256
+ fullCheckWithMargin,
257
+ { $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: config.minCompactChunkIntervalMs } }
258
+ ]
259
+ };
260
+ let kind: CompactionKind | null = null;
261
+ if (now >= fullCheckAt) {
262
+ kind = CompactionKind.Full;
263
+ } else if (canCheckChunks && shouldCompactChunks) {
264
+ kind = CompactionKind.Chunks;
265
+ }
266
+ return {
267
+ kind,
268
+ nextCompactCheck
269
+ };
270
+ }
271
+
272
+ export function chooseRequestedCompactionKind(
273
+ state: BucketStateDocumentV3,
274
+ requestedKind: CompactionKind | undefined,
275
+ config: CompactTargetConfig
276
+ ): CompactionKind | null {
277
+ if (requestedKind == null) {
278
+ return null;
279
+ }
280
+ // Initial replication bypasses the interval and never runs full compaction,
281
+ // but small buckets should still use the normal bulk-rescheduling path.
282
+ if (requestedKind == CompactionKind.Chunks && !config.forceChunkCompaction && !hasEnoughChunksToMerge(state)) {
283
+ return null;
284
+ }
285
+ const maxOpId = config.maxOpIdCap == null || state.last_op < config.maxOpIdCap ? state.last_op : config.maxOpIdCap;
286
+ return state.compacted_state == null || state.compacted_state.op_id < maxOpId ? requestedKind : null;
287
+ }
288
+
289
+ function hasEnoughChunksToMerge(state: BucketStateDocumentV3): boolean {
290
+ return state.bucket_stats.chunks - (state.compacted_state?.chunks ?? 0) >= MERGE_CHUNKS_THRESHOLD;
291
+ }
292
+
293
+ /**
294
+ * Read one bounded prefix from a compaction cursor.
295
+ *
296
+ * The document that would cross the byte limit is deliberately not returned:
297
+ * pagination resumes past the last returned `_id`, so that document remains
298
+ * eligible for the next query. The first document is always accepted to
299
+ * ensure progress when a single document exceeds the configured byte limit.
300
+ *
301
+ * `hasMore` is conservative when the document limit is reached. An extra empty
302
+ * query is preferable to exhausting the cursor just to determine whether the
303
+ * limited MongoDB query contained another document.
304
+ */
305
+ export async function readCompactionBatch(
306
+ cursor: mongo.AggregationCursor<BucketDataDocumentV3>,
307
+ options: { byteLimit: number; documentLimit: number }
308
+ ): Promise<{ documents: BucketDataDocumentV3[]; hasMore: boolean }> {
309
+ const documents: BucketDataDocumentV3[] = [];
310
+ let cumulativeBytes = 0;
311
+
312
+ try {
313
+ for await (const document of cursor) {
314
+ if (documents.length > 0 && cumulativeBytes + document.size > options.byteLimit) {
315
+ return { documents, hasMore: true };
316
+ }
317
+
318
+ documents.push(document);
319
+ cumulativeBytes += document.size;
320
+
321
+ if (documents.length >= options.documentLimit) {
322
+ return { documents, hasMore: true };
323
+ }
324
+ }
325
+ return { documents, hasMore: false };
326
+ } finally {
327
+ await cursor.close();
328
+ }
329
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Writers use this delay before scheduling their first chunk compaction.
3
+ * Initial replication includes the same delay when it picks up that work.
4
+ */
5
+ export const DEFAULT_MIN_COMPACT_CHUNK_INTERVAL_MS = 5 * 60 * 1000;
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  InternalOpId,
3
+ JsonValue,
3
4
  PersistedDefinitionMapping,
4
5
  SerializedSyncPlan,
5
6
  SyncRuleState,
@@ -7,6 +8,7 @@ import {
7
8
  } from '@powersync/service-core';
8
9
  import {
9
10
  BucketDefinitionId,
11
+ EventDefinitionId,
10
12
  ParameterIndexId,
11
13
  ScopedParameterLookup,
12
14
  SqliteJsonValue
@@ -15,7 +17,6 @@ import * as bson from 'bson';
15
17
  import {
16
18
  BucketDataKey,
17
19
  BucketParameterDocumentBase,
18
- BucketStateDocumentBase,
19
20
  CurrentBucket,
20
21
  OpType,
21
22
  ReplicaId,
@@ -94,7 +95,7 @@ export interface SyncConfigDefinition {
94
95
  created_at: Date;
95
96
  storage_version: number;
96
97
  /**
97
- * The related SyncRuleDocumentV3.
98
+ * The related ReplicationStreamDocumentV3.
98
99
  *
99
100
  * Note that a specific sync config definition never moves between replication streams. Instead, we can create a new copy for the new replication stream.
100
101
  *
@@ -103,6 +104,8 @@ export interface SyncConfigDefinition {
103
104
  replication_stream_id: number;
104
105
 
105
106
  content: string;
107
+ /** Optional operator-supplied label identifying this sync config version. */
108
+ version_label?: string;
106
109
  serialized_plan?: SerializedSyncPlan | null;
107
110
 
108
111
  rule_mapping: PersistedDefinitionMapping;
@@ -156,13 +159,68 @@ export interface SourceTableDocumentV3 {
156
159
  snapshot_status: SourceTableDocumentSnapshotStatus | undefined;
157
160
  bucket_data_source_ids: BucketDefinitionId[];
158
161
  parameter_lookup_source_ids: ParameterIndexId[];
162
+ /**
163
+ * Stream-local ids of the compiled event definitions evaluated by this source table.
164
+ */
165
+ event_definition_ids: EventDefinitionId[];
159
166
  latest_pending_delete?: InternalOpId | undefined;
167
+ /**
168
+ * Source-specific metadata. Absent for legacy records.
169
+ */
170
+ source_metadata?: JsonValue;
160
171
  }
161
172
 
162
- export interface BucketStateDocumentV3 extends BucketStateDocumentBase {
163
- _id: BucketStateDocumentBase['_id'] & {
173
+ export interface BucketStateDocumentV3 {
174
+ _id: {
175
+ b: string;
164
176
  d: BucketDefinitionId;
165
177
  };
178
+
179
+ /** Must always identify an actual operation in this logical stream. */
180
+ last_op: bigint;
181
+
182
+ /** The next time a compact worker should inspect this bucket. */
183
+ next_compact_check: Date | undefined;
184
+ /**
185
+ * Scheduling epoch for work not covered by a full compact. Writers set the
186
+ * first actual write time; a partial full compact advances it to completion.
187
+ */
188
+ first_uncompacted_write: Date | undefined;
189
+
190
+ /**
191
+ * A checksum cache and the statistics captured by the latest compact (full
192
+ * or chunk). Keeping these separate from bucket_stats lets writers only
193
+ * update one set of counters.
194
+ */
195
+ compacted_state?: {
196
+ op_id: InternalOpId;
197
+ checksum: bigint;
198
+ count: number;
199
+ bytes: bigint;
200
+ at: Date;
201
+ chunks: number;
202
+ };
203
+
204
+ /** Statistics for the prefix covered by the most recent full compact. */
205
+ last_full_compact?: {
206
+ op_id: InternalOpId;
207
+ count: number;
208
+ at: Date;
209
+ puts: number;
210
+ };
211
+
212
+ /** Current aggregate bucket statistics, maintained by writers and compactors. */
213
+ bucket_stats: {
214
+ count: number;
215
+ bytes: bigint;
216
+ chunks: number;
217
+ };
218
+
219
+ /** A short-lived ownership marker used to distribute bucket compaction. */
220
+ compact_lease?: {
221
+ expires_at: Date;
222
+ id: unknown;
223
+ };
166
224
  }
167
225
 
168
226
  export interface BucketOperation {
@@ -170,6 +228,7 @@ export interface BucketOperation {
170
228
  op: OpType;
171
229
  source_table?: bson.ObjectId;
172
230
  source_key?: ReplicaId;
231
+ subkey?: string;
173
232
  table?: string;
174
233
  row_id?: string;
175
234
  checksum: bigint;
@@ -181,6 +240,15 @@ export interface StorageRef {
181
240
  file_size: number;
182
241
  }
183
242
 
243
+ export interface ObjectStorageUsageDocument {
244
+ _id: {
245
+ g: number;
246
+ w: string;
247
+ };
248
+ updated_at: Date;
249
+ definitions: Record<BucketDefinitionId, bigint>;
250
+ }
251
+
184
252
  /** An S3 object that may be deleted once its grace period has elapsed. */
185
253
  export interface ObjectStorageDeletionMarker {
186
254
  _id: bson.ObjectId;
@@ -225,6 +293,31 @@ export interface BucketDataDocumentV3 {
225
293
  has_clear_op?: true;
226
294
  }
227
295
 
296
+ /**
297
+ * v3 Custom checkpoints (new name for legacy write checkpoints) are related to
298
+ * a replication stream and a specific event (in a sync config) which created them.
299
+ * Unchanged events, between sync configs, can share the documents.
300
+ * For v3, we store each replication stream's custom checkpoint requests in their own collection:
301
+ * `custom_checkpoint_requests_${replicationStreamId}_${eventId}`
302
+ */
303
+ export interface CustomCheckpointRequestDocumentV3 {
304
+ _id: bson.ObjectId;
305
+ user_id: string;
306
+ checkpoint: bigint;
307
+ /**
308
+ * Unlike managed write checkpoints, custom write checkpoints are flushed together with
309
+ * normal ops. This means we can assign an op_id for ordering / correlating with read checkpoints.
310
+ *
311
+ * This is not unique - multiple write checkpoints can have the same op_id.
312
+ */
313
+ op_id?: InternalOpId;
314
+ /**
315
+ * Set when this checkpoint was created from a client-supplied checkpoint
316
+ * request rather than a persistent custom write checkpoint.
317
+ */
318
+ checkpoint_requested_at?: Date | null;
319
+ }
320
+
228
321
  export function serializeParameterLookup(lookup: ScopedParameterLookup): bson.Binary {
229
322
  return new bson.Binary(bson.serialize({ l: lookup.values.slice(2) }));
230
323
  }
@@ -1,18 +1,22 @@
1
- import { storage } from '@powersync/service-core';
1
+ import { PerformanceTracer, storage } from '@powersync/service-core';
2
2
  import * as bson from 'bson';
3
3
  import { BucketDataDocumentV3, BucketOperation } from '../models.js';
4
- import { ObjectStorage } from './ObjectStorage.js';
4
+ import { ObjectStorage, ObjectStorageOperationOptions } from './ObjectStorage.js';
5
5
 
6
6
  export class BucketDataObjectStorage {
7
7
  constructor(private readonly storage: ObjectStorage) {}
8
8
 
9
- async store(path: string, ops: BucketOperation[]): Promise<{ fileSize: number }> {
9
+ async store(
10
+ path: string,
11
+ ops: BucketOperation[],
12
+ options?: ObjectStorageOperationOptions
13
+ ): Promise<{ fileSize: number }> {
10
14
  const bsonBuffer = bson.serialize({ ops });
11
- await this.storage.put(path, bsonBuffer, { contentType: 'application/bson', contentEncoding: null });
15
+ await this.storage.put(path, bsonBuffer, { contentType: 'application/bson', contentEncoding: null }, options);
12
16
  return { fileSize: bsonBuffer.byteLength };
13
17
  }
14
18
 
15
- async retrieve(path: string, options: { signal?: AbortSignal }): Promise<BucketOperation[]> {
19
+ async retrieve(path: string, options: ObjectStorageOperationOptions): Promise<BucketOperation[]> {
16
20
  const { data, metadata } = await this.storage.get(path, { signal: options.signal });
17
21
  if (metadata.contentEncoding != null) {
18
22
  throw new Error(`Unexpected content encoding: ${metadata.contentEncoding}`);
@@ -24,8 +28,8 @@ export class BucketDataObjectStorage {
24
28
  return wrapper.ops;
25
29
  }
26
30
 
27
- async delete(paths: string[]): Promise<void> {
28
- return this.storage.delete(paths);
31
+ async delete(paths: string[], options?: ObjectStorageOperationOptions): Promise<void> {
32
+ return this.storage.delete(paths, options);
29
33
  }
30
34
  }
31
35
 
@@ -37,7 +41,7 @@ export class BucketDataObjectStorage {
37
41
  export async function hydrateBucketDataDocuments(
38
42
  documents: BucketDataDocumentV3[],
39
43
  objectStorage: ObjectStorage | undefined,
40
- options: { signal?: AbortSignal }
44
+ options: ObjectStorageOperationOptions & { tracer?: PerformanceTracer<string> }
41
45
  ): Promise<void> {
42
46
  if (!objectStorage) {
43
47
  return;
@@ -46,9 +50,20 @@ export async function hydrateBucketDataDocuments(
46
50
  options.signal?.throwIfAborted();
47
51
  const store = new BucketDataObjectStorage(objectStorage);
48
52
  const storedDocuments = documents.filter((document) => document.storage_ref);
49
- await Promise.all(
53
+ if (storedDocuments.length == 0) {
54
+ return;
55
+ }
56
+ using _ = options?.tracer?.span('s3', 'read');
57
+ const results = await Promise.allSettled(
50
58
  storedDocuments.map(async (document) => {
51
59
  document.ops = await store.retrieve(document.storage_ref!.path, { signal: options.signal });
52
60
  })
53
61
  );
62
+ // Drain every download before propagating failure so callers can release their
63
+ // worker slot and payloads without a sibling download hydrating a document later.
64
+ for (const result of results) {
65
+ if (result.status === 'rejected') {
66
+ throw result.reason;
67
+ }
68
+ }
54
69
  }
@@ -17,13 +17,28 @@ export function isRetryableObjectStorageError(error: unknown): error is ObjectSt
17
17
  return error instanceof ObjectStorageError && error.retryable;
18
18
  }
19
19
 
20
+ export interface ObjectStorageOperationOptions {
21
+ /**
22
+ * Cancels the operation, including while it waits for a concurrency slot.
23
+ *
24
+ * Operations are bounded by their own timeouts regardless, but a signal releases the slot as
25
+ * soon as the caller no longer needs the result.
26
+ */
27
+ signal?: AbortSignal;
28
+ }
29
+
20
30
  export interface ObjectStorage {
21
- put(path: string, data: Uint8Array, metadata: ObjectStoragePutMetadata): Promise<void>;
31
+ put(
32
+ path: string,
33
+ data: Uint8Array,
34
+ metadata: ObjectStoragePutMetadata,
35
+ options?: ObjectStorageOperationOptions
36
+ ): Promise<void>;
22
37
  get(
23
38
  path: string,
24
- options?: { signal?: AbortSignal }
39
+ options?: ObjectStorageOperationOptions
25
40
  ): Promise<{ data: Uint8Array; metadata: ObjectStoragePutMetadata }>;
26
- list(prefix: string, options?: { signal?: AbortSignal }): AsyncIterable<string>;
27
- delete(paths: string[]): Promise<void>;
28
- deletePrefix(prefix: string, options?: { signal?: AbortSignal }): Promise<{ objectCount: number }>;
41
+ list(prefix: string, options?: ObjectStorageOperationOptions): AsyncIterable<string>;
42
+ delete(paths: string[], options?: ObjectStorageOperationOptions): Promise<void>;
43
+ deletePrefix(prefix: string, options?: ObjectStorageOperationOptions): Promise<{ objectCount: number }>;
29
44
  }