@powersync/service-module-mongodb-storage 0.20.0 → 0.22.0

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 (192) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/storage/MongoBucketStorage.d.ts +36 -3
  3. package/dist/storage/MongoBucketStorage.js +372 -207
  4. package/dist/storage/MongoBucketStorage.js.map +1 -1
  5. package/dist/storage/implementation/MongoBucketBatch.d.ts +17 -5
  6. package/dist/storage/implementation/MongoBucketBatch.js +44 -17
  7. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  8. package/dist/storage/implementation/MongoCompactor.d.ts +19 -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/MongoParameterCompactor.d.ts +83 -10
  12. package/dist/storage/implementation/MongoParameterCompactor.js +309 -96
  13. package/dist/storage/implementation/MongoParameterCompactor.js.map +1 -1
  14. package/dist/storage/implementation/MongoParsedSyncConfigSet.d.ts +9 -1
  15. package/dist/storage/implementation/MongoParsedSyncConfigSet.js +29 -0
  16. package/dist/storage/implementation/MongoParsedSyncConfigSet.js.map +1 -1
  17. package/dist/storage/implementation/MongoPersistedSyncConfigContent.js +4 -2
  18. package/dist/storage/implementation/MongoPersistedSyncConfigContent.js.map +1 -1
  19. package/dist/storage/implementation/MongoStorageProvider.js +7 -3
  20. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  21. package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +27 -11
  22. package/dist/storage/implementation/MongoSyncBucketStorage.js +78 -31
  23. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  24. package/dist/storage/implementation/MongoSyncRulesLock.js +21 -9
  25. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  26. package/dist/storage/implementation/MongoWriteBatch.d.ts +49 -0
  27. package/dist/storage/implementation/MongoWriteBatch.js +149 -0
  28. package/dist/storage/implementation/MongoWriteBatch.js.map +1 -0
  29. package/dist/storage/implementation/MongoWriteCheckpointAPI.d.ts +9 -7
  30. package/dist/storage/implementation/MongoWriteCheckpointAPI.js +9 -30
  31. package/dist/storage/implementation/MongoWriteCheckpointAPI.js.map +1 -1
  32. package/dist/storage/implementation/SyncRuleStateUpdate.d.ts +11 -5
  33. package/dist/storage/implementation/SyncRuleStateUpdate.js +14 -6
  34. package/dist/storage/implementation/SyncRuleStateUpdate.js.map +1 -1
  35. package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.d.ts +22 -2
  36. package/dist/storage/implementation/common/PersistedBatch.d.ts +32 -4
  37. package/dist/storage/implementation/common/PersistedBatch.js +49 -6
  38. package/dist/storage/implementation/common/PersistedBatch.js.map +1 -1
  39. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.d.ts +3 -0
  40. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js +3 -0
  41. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js.map +1 -1
  42. package/dist/storage/implementation/db.d.ts +9 -1
  43. package/dist/storage/implementation/db.js +27 -1
  44. package/dist/storage/implementation/db.js.map +1 -1
  45. package/dist/storage/implementation/models.d.ts +31 -0
  46. package/dist/storage/implementation/models.js.map +1 -1
  47. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +2 -0
  48. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +33 -4
  49. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  50. package/dist/storage/implementation/v1/MongoCompactorV1.d.ts +38 -6
  51. package/dist/storage/implementation/v1/MongoCompactorV1.js +247 -20
  52. package/dist/storage/implementation/v1/MongoCompactorV1.js.map +1 -1
  53. package/dist/storage/implementation/v1/MongoParameterCompactorV1.d.ts +16 -2
  54. package/dist/storage/implementation/v1/MongoParameterCompactorV1.js +20 -9
  55. package/dist/storage/implementation/v1/MongoParameterCompactorV1.js.map +1 -1
  56. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.d.ts +18 -11
  57. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js +65 -16
  58. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js.map +1 -1
  59. package/dist/storage/implementation/v1/PersistedBatchV1.d.ts +7 -5
  60. package/dist/storage/implementation/v1/PersistedBatchV1.js +22 -28
  61. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  62. package/dist/storage/implementation/v1/models.js +1 -0
  63. package/dist/storage/implementation/v1/models.js.map +1 -1
  64. package/dist/storage/implementation/v3/CompactionLease.d.ts +50 -0
  65. package/dist/storage/implementation/v3/CompactionLease.js +131 -0
  66. package/dist/storage/implementation/v3/CompactionLease.js.map +1 -0
  67. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +10 -2
  68. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +100 -26
  69. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  70. package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +82 -25
  71. package/dist/storage/implementation/v3/MongoCompactorV3.js +698 -159
  72. package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
  73. package/dist/storage/implementation/v3/MongoParameterCompactorV3.d.ts +18 -0
  74. package/dist/storage/implementation/v3/MongoParameterCompactorV3.js +23 -0
  75. package/dist/storage/implementation/v3/MongoParameterCompactorV3.js.map +1 -0
  76. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.d.ts +2 -15
  77. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js +60 -92
  78. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js.map +1 -1
  79. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.d.ts +19 -9
  80. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js +91 -31
  81. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js.map +1 -1
  82. package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.d.ts +26 -0
  83. package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js +82 -0
  84. package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js.map +1 -0
  85. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -8
  86. package/dist/storage/implementation/v3/PersistedBatchV3.js +76 -42
  87. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  88. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.d.ts +12 -2
  89. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js +42 -3
  90. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js.map +1 -1
  91. package/dist/storage/implementation/v3/bucket-format.js +2 -0
  92. package/dist/storage/implementation/v3/bucket-format.js.map +1 -1
  93. package/dist/storage/implementation/v3/compact-utils.d.ts +107 -0
  94. package/dist/storage/implementation/v3/compact-utils.js +216 -0
  95. package/dist/storage/implementation/v3/compact-utils.js.map +1 -0
  96. package/dist/storage/implementation/v3/compaction-constants.d.ts +5 -0
  97. package/dist/storage/implementation/v3/compaction-constants.js +6 -0
  98. package/dist/storage/implementation/v3/compaction-constants.js.map +1 -0
  99. package/dist/storage/implementation/v3/models.d.ts +84 -4
  100. package/dist/storage/implementation/v3/models.js.map +1 -1
  101. package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.d.ts +7 -8
  102. package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js +16 -5
  103. package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js.map +1 -1
  104. package/dist/storage/implementation/v3/object-storage/ObjectStorage.d.ts +14 -11
  105. package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.d.ts +6 -8
  106. package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js +17 -11
  107. package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js.map +1 -1
  108. package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.d.ts +38 -0
  109. package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js +164 -0
  110. package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js.map +1 -0
  111. package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.d.ts +37 -12
  112. package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js +197 -25
  113. package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js.map +1 -1
  114. package/dist/storage/implementation/v3/source-table-utils.d.ts +6 -6
  115. package/dist/storage/implementation/v3/source-table-utils.js +30 -37
  116. package/dist/storage/implementation/v3/source-table-utils.js.map +1 -1
  117. package/dist/storage/storage-index.d.ts +2 -1
  118. package/dist/storage/storage-index.js +1 -0
  119. package/dist/storage/storage-index.js.map +1 -1
  120. package/dist/types/types.d.ts +28 -1
  121. package/dist/types/types.js +28 -7
  122. package/dist/types/types.js.map +1 -1
  123. package/dist/utils/test-utils.js +1 -0
  124. package/dist/utils/test-utils.js.map +1 -1
  125. package/dist/utils/util.js +3 -1
  126. package/dist/utils/util.js.map +1 -1
  127. package/package.json +10 -9
  128. package/src/storage/MongoBucketStorage.ts +507 -269
  129. package/src/storage/implementation/MongoBucketBatch.ts +67 -24
  130. package/src/storage/implementation/MongoCompactor.ts +35 -346
  131. package/src/storage/implementation/MongoParameterCompactor.ts +388 -102
  132. package/src/storage/implementation/MongoParsedSyncConfigSet.ts +34 -0
  133. package/src/storage/implementation/MongoPersistedSyncConfigContent.ts +4 -2
  134. package/src/storage/implementation/MongoStorageProvider.ts +15 -3
  135. package/src/storage/implementation/MongoSyncBucketStorage.ts +114 -40
  136. package/src/storage/implementation/MongoSyncRulesLock.ts +22 -9
  137. package/src/storage/implementation/MongoWriteBatch.ts +172 -0
  138. package/src/storage/implementation/MongoWriteCheckpointAPI.ts +16 -46
  139. package/src/storage/implementation/SyncRuleStateUpdate.ts +13 -6
  140. package/src/storage/implementation/common/MongoSyncBucketStorageCheckpoint.ts +24 -2
  141. package/src/storage/implementation/common/PersistedBatch.ts +66 -10
  142. package/src/storage/implementation/common/VersionedPowerSyncMongoBase.ts +4 -0
  143. package/src/storage/implementation/db.ts +35 -2
  144. package/src/storage/implementation/models.ts +34 -0
  145. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +46 -6
  146. package/src/storage/implementation/v1/MongoCompactorV1.ts +327 -40
  147. package/src/storage/implementation/v1/MongoParameterCompactorV1.ts +25 -9
  148. package/src/storage/implementation/v1/MongoSyncBucketStorageV1.ts +87 -27
  149. package/src/storage/implementation/v1/PersistedBatchV1.ts +25 -30
  150. package/src/storage/implementation/v1/models.ts +1 -0
  151. package/src/storage/implementation/v3/CompactionLease.ts +152 -0
  152. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +138 -34
  153. package/src/storage/implementation/v3/MongoCompactorV3.ts +958 -225
  154. package/src/storage/implementation/v3/MongoParameterCompactorV3.ts +34 -0
  155. package/src/storage/implementation/v3/MongoStoppedSyncConfigCleanup.ts +100 -109
  156. package/src/storage/implementation/v3/MongoSyncBucketStorageV3.ts +111 -41
  157. package/src/storage/implementation/v3/MongoWriteCheckpointAPIV3.ts +111 -0
  158. package/src/storage/implementation/v3/PersistedBatchV3.ts +93 -48
  159. package/src/storage/implementation/v3/VersionedPowerSyncMongoV3.ts +55 -4
  160. package/src/storage/implementation/v3/bucket-format.ts +2 -0
  161. package/src/storage/implementation/v3/compact-utils.ts +320 -0
  162. package/src/storage/implementation/v3/compaction-constants.ts +5 -0
  163. package/src/storage/implementation/v3/models.ts +91 -3
  164. package/src/storage/implementation/v3/object-storage/BucketDataObjectStorage.ts +24 -9
  165. package/src/storage/implementation/v3/object-storage/ObjectStorage.ts +20 -5
  166. package/src/storage/implementation/v3/object-storage/ObjectStorageLifecycle.ts +26 -14
  167. package/src/storage/implementation/v3/object-storage/ObjectStorageUsage.ts +229 -0
  168. package/src/storage/implementation/v3/object-storage/S3ObjectStorage.ts +279 -29
  169. package/src/storage/implementation/v3/source-table-utils.ts +39 -41
  170. package/src/storage/storage-index.ts +2 -0
  171. package/src/types/types.ts +42 -7
  172. package/src/utils/test-utils.ts +1 -0
  173. package/src/utils/util.ts +3 -1
  174. package/test/src/__snapshots__/storage.test.ts.snap +25 -0
  175. package/test/src/__snapshots__/storage_sync.test.ts.snap +605 -16
  176. package/test/src/chunk_compaction_config.test.ts +38 -0
  177. package/test/src/cleanup-stopped-sync-configs.test.ts +40 -13
  178. package/test/src/compact-utils.test.ts +226 -0
  179. package/test/src/helpers/MemoryObjectStorage.ts +14 -6
  180. package/test/src/object_storage_usage.test.ts +267 -0
  181. package/test/src/parameter_compacting_v1.test.ts +120 -0
  182. package/test/src/parameter_compacting_v3.test.ts +192 -0
  183. package/test/src/parameter_compaction_fence.test.ts +276 -0
  184. package/test/src/storage.test.ts +273 -22
  185. package/test/src/storage_compacting.test.ts +968 -246
  186. package/test/src/storage_s3_checksums.test.ts +3 -4
  187. package/test/src/storage_s3_compaction_lifecycle.test.ts +138 -12
  188. package/test/src/storage_s3_reading.test.ts +290 -2
  189. package/test/src/storage_s3_writing.test.ts +1 -0
  190. package/test/src/storage_sync.test.ts +336 -41
  191. package/test/src/util.ts +1 -1
  192. package/tsconfig.tsbuildinfo +1 -1
@@ -1,15 +1,11 @@
1
1
  import * as timers from 'node:timers/promises';
2
- import { isMongoServerError, MONGO_OPERATION_TIMEOUT_MS } from '@powersync/lib-service-mongodb';
3
- import { logger as defaultLogger, ReplicationAssertionError, ServiceAssertionError } from '@powersync/lib-services-framework';
4
- import { isPartialChecksum } from '@powersync/service-core';
2
+ import { isMongoServerError } from '@powersync/lib-service-mongodb';
3
+ import { logger as defaultLogger, ReplicationAssertionError } from '@powersync/lib-services-framework';
5
4
  import { isRetryableObjectStorageError } from './v3/object-storage/ObjectStorage.js';
6
5
  const DEFAULT_CLEAR_BATCH_LIMIT = 5000;
7
6
  const DEFAULT_MOVE_BATCH_LIMIT = 2000;
8
7
  const DEFAULT_MOVE_BATCH_QUERY_LIMIT = 10_000;
9
8
  const DEFAULT_MOVE_BATCH_BYTE_LIMIT = 16 * 1024 * 1024;
10
- const DEFAULT_MIN_BUCKET_CHANGES = 10;
11
- const DEFAULT_MIN_CHANGE_RATIO = 0.1;
12
- const DIRTY_BUCKET_SCAN_BATCH_SIZE = 2_000;
13
9
  /** This default is primarily for tests. */
14
10
  const DEFAULT_MEMORY_LIMIT_MB = 64;
15
11
  const COMPACTION_RETRY_LIMIT = 3;
@@ -20,22 +16,31 @@ export class ConcurrentCompactionError extends Error {
20
16
  this.name = 'ConcurrentCompactionError';
21
17
  }
22
18
  }
19
+ /**
20
+ * A worker whose bucket lease has been replaced must stop immediately. Unlike
21
+ * a transactional replacement conflict, retrying it with the same compactor
22
+ * instance would still use the stale lease and could race the new owner.
23
+ */
24
+ export class CompactionLeaseLostError extends ConcurrentCompactionError {
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = 'CompactionLeaseLostError';
28
+ }
29
+ }
23
30
  export class MongoCompactor {
24
31
  storage;
25
32
  db;
26
- bucketStateUpdates = [];
27
33
  idLimitBytes;
28
34
  moveBatchLimit;
29
35
  moveBatchQueryLimit;
30
36
  moveBatchByteLimit;
31
37
  clearBatchLimit;
32
- minBucketChanges;
33
- minChangeRatio;
34
- maxOpId;
35
38
  buckets;
36
39
  deleteCheckpointRequestsBefore;
37
40
  signal;
38
41
  group_id;
42
+ compactChunksOnly;
43
+ compactedBucketCount = 0;
39
44
  logger;
40
45
  constructor(storage, db, options) {
41
46
  this.storage = storage;
@@ -49,32 +54,12 @@ export class MongoCompactor {
49
54
  if (this.clearBatchLimit < 2) {
50
55
  throw new ReplicationAssertionError('clearBatchLimit must be >= 2');
51
56
  }
52
- this.minBucketChanges = options.minBucketChanges ?? DEFAULT_MIN_BUCKET_CHANGES;
53
- this.minChangeRatio = options.minChangeRatio ?? DEFAULT_MIN_CHANGE_RATIO;
54
- this.maxOpId = options.maxOpId ?? 0n;
55
57
  this.buckets = options.compactBuckets;
56
58
  this.deleteCheckpointRequestsBefore = options.deleteCheckpointRequestsBefore;
57
59
  this.signal = options.signal;
60
+ this.compactChunksOnly = options.compactChunksOnly ?? false;
58
61
  this.logger = options.logger ?? defaultLogger;
59
62
  }
60
- /**
61
- * Compact buckets by converting operations into MOVE and/or CLEAR operations.
62
- *
63
- * See /docs/storage/compacting-operations.md for details.
64
- */
65
- async compact() {
66
- await this.deleteOldCheckpointRequests();
67
- if (this.buckets) {
68
- for (const bucket of this.buckets) {
69
- // We can make this more efficient later on by iterating through the buckets in a single query.
70
- // That makes batching more tricky, so we leave for later.
71
- await this.compactSingleBucketRetried(bucket);
72
- }
73
- }
74
- else {
75
- await this.compactDirtyBuckets();
76
- }
77
- }
78
63
  async deleteOldCheckpointRequests() {
79
64
  if (this.deleteCheckpointRequestsBefore == null) {
80
65
  return;
@@ -88,141 +73,16 @@ export class MongoCompactor {
88
73
  checkpoint_requested_at: { $exists: true, $lt: this.deleteCheckpointRequestsBefore },
89
74
  processed_at_lsn: { $ne: null }
90
75
  });
76
+ await this.deleteOldCustomCheckpointRequests();
77
+ }
78
+ async deleteOldCustomCheckpointRequests() {
79
+ if (this.deleteCheckpointRequestsBefore == null) {
80
+ return;
81
+ }
91
82
  await this.db.custom_write_checkpoints.deleteMany({
92
83
  checkpoint_requested_at: { $exists: true, $lt: this.deleteCheckpointRequestsBefore }
93
84
  });
94
85
  }
95
- /**
96
- * Subset of compact, only populating checksums where relevant.
97
- */
98
- async populateChecksums(options) {
99
- let count = 0;
100
- // Paginate through dirty buckets in batches until no more buckets meet the criteria.
101
- while (true) {
102
- this.signal?.throwIfAborted();
103
- const buckets = await this.dirtyBucketBatchForChecksums(options);
104
- if (buckets.length == 0) {
105
- break;
106
- }
107
- this.signal?.throwIfAborted();
108
- const start = Date.now();
109
- // Filter batch by estimated bucket size, to reduce possibility of timeouts.
110
- const checkBuckets = [];
111
- let totalCountEstimate = 0;
112
- for (const bucket of buckets) {
113
- checkBuckets.push(bucket);
114
- totalCountEstimate += bucket.estimatedCount;
115
- if (totalCountEstimate > 50_000) {
116
- break;
117
- }
118
- }
119
- this.logger.info(`Calculating checksums for batch of ${buckets.length} buckets, estimated count of ${totalCountEstimate}`);
120
- await this.updateChecksumsBatch(checkBuckets);
121
- this.logger.info(`Updated checksums for batch of ${checkBuckets.length} buckets in ${Date.now() - start}ms`);
122
- count += checkBuckets.length;
123
- }
124
- return { buckets: count };
125
- }
126
- async *dirtyBucketBatchesForCollection(collection, lastId, maxId, options, getDefinitionId) {
127
- // Paginate through the bucket state collection using cursor-based scanning.
128
- while (true) {
129
- // To avoid timeouts from too many buckets not meeting the minBucketChanges criteria, use an aggregation pipeline
130
- // to scan a fixed batch of buckets at a time, but only return buckets that meet the criteria.
131
- const [result] = await collection
132
- .aggregate([
133
- {
134
- $match: {
135
- _id: { $gt: lastId, $lt: maxId }
136
- }
137
- },
138
- {
139
- $sort: { _id: 1 }
140
- },
141
- {
142
- // Scan a fixed number of docs each query so sparse matches don't block progress.
143
- $limit: DIRTY_BUCKET_SCAN_BATCH_SIZE
144
- },
145
- {
146
- $facet: {
147
- buckets: [
148
- {
149
- $match: {
150
- 'estimate_since_compact.count': { $gte: options.minBucketChanges }
151
- }
152
- },
153
- {
154
- $project: {
155
- _id: 1,
156
- estimate_since_compact: 1,
157
- compacted_state: 1
158
- }
159
- }
160
- ],
161
- // This is used for the next query.
162
- cursor: [{ $sort: { _id: -1 } }, { $limit: 1 }, { $project: { _id: 1 } }]
163
- }
164
- }
165
- ], { maxTimeMS: MONGO_OPERATION_TIMEOUT_MS })
166
- .toArray();
167
- const cursor = result?.cursor?.[0];
168
- if (cursor == null) {
169
- break;
170
- }
171
- lastId = cursor._id;
172
- const mapped = (result?.buckets ?? []).map((bucketState) => {
173
- // The numbers, specifically the bytes, could be a bigint. Convert to Number to allow calculating ratios.
174
- // BigInt precision is not needed here since this is only an estimate.
175
- const updatedCount = bucketState.estimate_since_compact?.count ?? 0;
176
- const totalCount = (bucketState.compacted_state?.count ?? 0) + updatedCount;
177
- const updatedBytes = Number(bucketState.estimate_since_compact?.bytes ?? 0);
178
- const totalBytes = Number(bucketState.compacted_state?.bytes ?? 0) + updatedBytes;
179
- const dirtyChangeNumber = totalCount > 0 ? updatedCount / totalCount : 0;
180
- const dirtyChangeBytes = totalBytes > 0 ? updatedBytes / totalBytes : 0;
181
- return {
182
- bucket: bucketState._id.b,
183
- definitionId: getDefinitionId(bucketState),
184
- estimatedCount: totalCount,
185
- dirtyRatio: Math.max(dirtyChangeNumber, dirtyChangeBytes)
186
- };
187
- });
188
- yield mapped.filter((bucket) => bucket.estimatedCount >= options.minBucketChanges && bucket.dirtyRatio >= options.minChangeRatio);
189
- }
190
- }
191
- async dirtyBucketBatchForChecksumsForCollection(collection, filter, getDefinitionId) {
192
- const dirtyBuckets = await collection
193
- .find(filter, {
194
- projection: {
195
- _id: 1,
196
- estimate_since_compact: 1,
197
- compacted_state: 1
198
- },
199
- sort: {
200
- 'estimate_since_compact.count': -1
201
- },
202
- limit: 200,
203
- maxTimeMS: MONGO_OPERATION_TIMEOUT_MS
204
- })
205
- .toArray();
206
- return dirtyBuckets.map((bucket) => ({
207
- bucket: bucket._id.b,
208
- definitionId: getDefinitionId(bucket),
209
- estimatedCount: Number(bucket.estimate_since_compact.count) + Number(bucket.compacted_state?.count ?? 0)
210
- }));
211
- }
212
- async compactDirtyBuckets() {
213
- for await (const buckets of this.dirtyBucketBatches({
214
- minBucketChanges: this.minBucketChanges,
215
- minChangeRatio: this.minChangeRatio
216
- })) {
217
- this.signal?.throwIfAborted();
218
- if (buckets.length == 0) {
219
- continue;
220
- }
221
- for (const { bucket, definitionId } of buckets) {
222
- await this.compactSingleBucketRetried(bucket, definitionId);
223
- }
224
- }
225
- }
226
86
  /**
227
87
  * Compaction for a single bucket, with retries on failure.
228
88
  *
@@ -231,14 +91,12 @@ export class MongoCompactor {
231
91
  * storage paths are also prepared with lifecycle markers, so a retry can
232
92
  * safely overwrite or eventually clean up uploads from the failed attempt.
233
93
  */
234
- async compactSingleBucketRetried(bucket, definitionId = null) {
94
+ async retryCompaction(bucket, compact) {
235
95
  let retryCount = 0;
236
96
  while (true) {
237
97
  this.signal?.throwIfAborted();
238
- // Do not carry queued bucket state writes from a failed attempt into the rescan.
239
- this.bucketStateUpdates = [];
240
98
  try {
241
- await this.compactSingleBucket(bucket, definitionId);
99
+ await compact();
242
100
  return;
243
101
  }
244
102
  catch (e) {
@@ -260,80 +118,11 @@ export class MongoCompactor {
260
118
  }
261
119
  }
262
120
  }
263
- collectBucketStateUpdates(state, compactedOpId) {
264
- if (state.opCount < 0) {
265
- throw new ServiceAssertionError(`Invalid opCount: ${state.opCount} checksum ${state.checksum} opsSincePut: ${state.opsSincePut} maxOpId: ${this.maxOpId}`);
266
- }
267
- return {
268
- updateOne: {
269
- filter: this.bucketStateFilter(state.bucket, state.definitionId),
270
- update: {
271
- $set: {
272
- compacted_state: {
273
- op_id: compactedOpId,
274
- count: state.opCount,
275
- checksum: BigInt(state.checksum),
276
- bytes: state.opBytes
277
- },
278
- estimate_since_compact: {
279
- // There could have been a whole bunch of new operations added to the bucket while compacting,
280
- // which we don't currently cater for. We could potentially query for that, but that adds overhead.
281
- count: 0,
282
- bytes: 0
283
- }
284
- }
285
- },
286
- // We generally expect this to have been created before.
287
- // We don't create new ones here, to avoid issues with the unique index on bucket_updates.
288
- upsert: false
289
- }
290
- };
291
- }
292
- updateBucketChecksums(state, compactedOpId) {
293
- this.bucketStateUpdates.push(this.collectBucketStateUpdates(state, compactedOpId));
294
- }
295
- async flushBucketStateUpdates() {
296
- if (this.bucketStateUpdates.length > 0) {
297
- this.logger.info(`Updating ${this.bucketStateUpdates.length} bucket states`);
298
- await this.writeBucketStateUpdates();
299
- this.bucketStateUpdates = [];
300
- }
301
- }
302
- async updateChecksumsBatch(buckets) {
303
- const checksums = await this.computeChecksumsForBuckets(buckets);
304
- const definitionIdByBucket = new Map(buckets.map((bucket) => [bucket.bucket, bucket.definitionId]));
305
- for (const bucketChecksum of checksums.values()) {
306
- if (isPartialChecksum(bucketChecksum)) {
307
- // Should never happen since we don't specify `start`.
308
- throw new ServiceAssertionError(`Full checksum expected, got ${JSON.stringify(bucketChecksum)}`);
309
- }
310
- this.bucketStateUpdates.push({
311
- updateOne: {
312
- filter: this.bucketStateFilter(bucketChecksum.bucket, definitionIdByBucket.get(bucketChecksum.bucket) ?? null),
313
- update: {
314
- $set: {
315
- compacted_state: {
316
- op_id: this.maxOpId,
317
- count: bucketChecksum.count,
318
- checksum: BigInt(bucketChecksum.checksum),
319
- bytes: null
320
- },
321
- estimate_since_compact: {
322
- count: 0,
323
- bytes: 0
324
- }
325
- }
326
- },
327
- // We don't create new ones here - it gets tricky to get the last_op right with the unique index on
328
- // bucket_updates.
329
- upsert: false
330
- }
331
- });
332
- }
333
- await this.flushBucketStateUpdates();
334
- }
335
121
  }
336
122
  function compactionRetryReason(error) {
123
+ if (error instanceof CompactionLeaseLostError) {
124
+ return null;
125
+ }
337
126
  if (error instanceof ConcurrentCompactionError) {
338
127
  return 'concurrent compaction';
339
128
  }
@@ -1 +1 @@
1
- {"version":3,"file":"MongoCompactor.js","sourceRoot":"","sources":["../../../src/storage/implementation/MongoCompactor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,sBAAsB,CAAC;AAE/C,OAAO,EAAE,kBAAkB,EAAS,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AACvG,OAAO,EACL,MAAM,IAAI,aAAa,EAEvB,yBAAyB,EACzB,qBAAqB,EACtB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAgB,iBAAiB,EAAyC,MAAM,yBAAyB,CAAC;AAOjH,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAsCrF,MAAM,yBAAyB,GAAG,IAAI,CAAC;AACvC,MAAM,wBAAwB,GAAG,IAAI,CAAC;AACtC,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,6BAA6B,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACvD,MAAM,0BAA0B,GAAG,EAAE,CAAC;AACtC,MAAM,wB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C,KAAK,EAAE,IAAI;6BACZ;4BACD,sBAAsB,EAAE;gCACtB,KAAK,EAAE,CAAC;gCACR,KAAK,EAAE,CAAC;6BACT;yBACF;qBACoD;oBACvD,mGAAmG;oBACnG,kBAAkB;oBAClB,MAAM,EAAE,KAAK;iBACd;aACF,CAAC,CAAC;QACL,CAAC;QAED,MAAM,IAAI,CAAC,uBAAuB,EAAE,CAAC;IACvC,CAAC;CAOF;AAOD,SAAS,qBAAqB,CAAC,KAAc;IAC3C,IAAI,KAAK,YAAY,yBAAyB,EAAE,CAAC;QAC/C,OAAO,uBAAuB,CAAC;IACjC,CAAC;IACD,IAAI,6BAA6B,CAAC,KAAK,CAAC,EAAE,CAAC;QACzC,OAAO,kCAAkC,CAAC;IAC5C,CAAC;IACD,IAAI,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9B,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC"}
1
+ {"version":3,"file":"MongoCompactor.js","sourceRoot":"","sources":["../../../src/storage/implementation/MongoCompactor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,sBAAsB,CAAC;AAE/C,OAAO,EAAE,kBAAkB,EAAS,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,MAAM,IAAI,aAAa,EAAU,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAM/G,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAWrF,MAAM,yBAAyB,GAAG,IAAI,CAAC;AACvC,MAAM,wBAAwB,GAAG,IAAI,CAAC;AACtC,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAC9C,MAAM,6BAA6B,GAAG,EAAE,GAAG,I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AM,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAC/F,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAOD,SAAS,qBAAqB,CAAC,KAAc;IAC3C,IAAI,KAAK,YAAY,wBAAwB,EAAE,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,KAAK,YAAY,yBAAyB,EAAE,CAAC;QAC/C,OAAO,uBAAuB,CAAC;IACjC,CAAC;IACD,IAAI,6BAA6B,CAAC,KAAK,CAAC,EAAE,CAAC;QACzC,OAAO,kCAAkC,CAAC;IAC5C,CAAC;IACD,IAAI,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9B,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC"}
@@ -1,23 +1,96 @@
1
1
  import { mongo } from '@powersync/lib-service-mongodb';
2
- import { CompactOptions, InternalOpId } from '@powersync/service-core';
2
+ import { Logger } from '@powersync/lib-services-framework';
3
+ import { bson, CompactOptions, InternalOpId } from '@powersync/service-core';
3
4
  import type { VersionedPowerSyncMongo } from './db.js';
5
+ type ParameterCompactionReadDocument = {
6
+ _id: InternalOpId;
7
+ key: mongo.Document;
8
+ lookup: bson.Binary;
9
+ bucket_parameters?: unknown[] | null;
10
+ };
11
+ export type ParameterCompactionResult = {
12
+ collections: number;
13
+ scannedEntries: number;
14
+ deletedEntries: number;
15
+ };
4
16
  /**
5
17
  * Compacts parameter lookup data (the bucket_parameters collection).
6
18
  *
7
- * This scans through the entire collection to find data to compact.
19
+ * Both storage versions persist a per-stream compaction cursor, so a run only scans entries in the
20
+ * un-compacted operation-id range. V1 scans its shared collection using only the `_id` index, so it
21
+ * additionally filters by stream in code.
22
+ *
23
+ * The cursor is a single value covering every collection of the stream, so it can only be advanced
24
+ * to a boundary that all collections have passed. To keep it moving during a long pass, collections
25
+ * are processed in lock-step rather than one after another - see {@link compactCollections}.
8
26
  *
9
27
  * For background, see the `/docs/storage/parameter-lookups.md` file.
10
28
  */
11
- export declare class MongoParameterCompactor {
29
+ export declare abstract class MongoParameterCompactor {
30
+ #private;
12
31
  protected readonly db: VersionedPowerSyncMongo;
13
- protected readonly group_id: number;
32
+ protected readonly replicationStreamId: number;
14
33
  protected readonly checkpoint: InternalOpId;
15
34
  protected readonly options: CompactOptions;
16
- protected readonly getCollectionsCb?: (() => Promise<mongo.Collection<mongo.Document>[]>) | undefined;
17
- constructor(db: VersionedPowerSyncMongo, group_id: number, checkpoint: InternalOpId, options: CompactOptions, getCollectionsCb?: (() => Promise<mongo.Collection<mongo.Document>[]>) | undefined);
35
+ protected readonly parameterCompactionBatchSize: number;
36
+ protected readonly parameterCompactionPersistIntervalMs: number;
37
+ protected readonly logger: Logger;
38
+ protected readonly signal?: AbortSignal;
39
+ constructor(db: VersionedPowerSyncMongo, replicationStreamId: number, checkpoint: InternalOpId, options: CompactOptions, parameterCompactionBatchSize?: number, parameterCompactionPersistIntervalMs?: number);
18
40
  compact(): Promise<void>;
19
- protected getCollections(): Promise<mongo.Collection<mongo.Document>[]>;
20
- protected collectionFilter(): mongo.Document;
21
- protected deleteFilter(doc: mongo.Document): mongo.Document;
22
- protected compactCollection(collection: mongo.Collection<mongo.Document>): Promise<void>;
41
+ /**
42
+ * The exclusive operation-id boundary through which this stream's parameter indexes have all
43
+ * been compacted.
44
+ */
45
+ protected readCompactedBefore(): Promise<InternalOpId>;
46
+ protected persistCompactedBefore(compactedBefore: InternalOpId): Promise<void>;
47
+ /**
48
+ * Commits the checkpoint-change invalidation fence before the first delete of this pass.
49
+ *
50
+ * Checkpoint change detection finds changed lookups by querying parameter entries in
51
+ * (lastCheckpoint, nextCheckpoint]. Compaction physically removes entries in that range, so a
52
+ * checkpoint that can no longer see the full history must instead invalidate all parameter
53
+ * buckets. The fence records the boundary below which that history may be missing.
54
+ *
55
+ * The fence must be committed before the first delete: MongoDB snapshot ordering then
56
+ * guarantees that a checkpoint snapshot which observes a deletion also observes the fence.
57
+ *
58
+ * This deliberately isn't the same value as the compaction cursor. If the pass fails halfway,
59
+ * the fence only causes conservative invalidation, while an advanced cursor would skip
60
+ * deletion work that never completed.
61
+ */
62
+ private ensureInvalidationFence;
63
+ protected abstract getCollections(): Promise<mongo.Collection<mongo.Document>[]>;
64
+ protected abstract shouldCompactDocument(doc: ParameterCompactionReadDocument): boolean;
65
+ /** Deletes history preceding a batch for several identities sharing a lookup. */
66
+ protected abstract leadingHistoryDeleteFilter(lookup: bson.Binary, keys: mongo.Document[], before: InternalOpId): mongo.Document;
67
+ /**
68
+ * Processes every collection of the stream, in lock-step: each turn takes one batch from the
69
+ * collection that has processed the least so far.
70
+ *
71
+ * The persisted cursor is the minimum position over all collections, which is exactly the
72
+ * boundary that all of them have passed, so it can be advanced periodically during the pass.
73
+ * Always picking the collection that is furthest behind also keeps each of them within one batch
74
+ * of that boundary, bounding the work an interrupted pass has to repeat.
75
+ *
76
+ * V1 storage always has a single collection; V3 has a collection per defined index. So in V1 the
77
+ * ame process collapses to compacting the single collection in order, while V3 can alternate between
78
+ * collections.
79
+ */
80
+ private compactCollections;
81
+ /**
82
+ * The boundary that every scope has processed past, capped at the target checkpoint, and the
83
+ * scope sitting on it.
84
+ *
85
+ * The frontier is the furthest the cursor may be advanced. The scope is the one that has
86
+ * processed the least, or null once all of them have reached the target checkpoint.
87
+ */
88
+ private frontier;
89
+ /**
90
+ * Reads and processes one batch from the scope, and advances its position past that batch.
91
+ */
92
+ private compactBatch;
93
+ /** Deletes documents by `_id`, chunked to bound the command size. Returns the number deleted. */
94
+ private deleteByIds;
23
95
  }
96
+ export {};