@powersync/service-module-mongodb-storage 0.24.2 → 0.26.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 (105) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/migrations/db/migrations/1684951997326-init.js +3 -29
  3. package/dist/migrations/db/migrations/1684951997326-init.js.map +1 -1
  4. package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js +3 -24
  5. package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js.map +1 -1
  6. package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js +3 -24
  7. package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js.map +1 -1
  8. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.d.ts +3 -0
  9. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js +21 -0
  10. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js.map +1 -0
  11. package/dist/storage/MongoBucketStorage.d.ts +9 -0
  12. package/dist/storage/MongoBucketStorage.js +60 -30
  13. package/dist/storage/MongoBucketStorage.js.map +1 -1
  14. package/dist/storage/implementation/MongoBucketBatch.d.ts +21 -16
  15. package/dist/storage/implementation/MongoBucketBatch.js +22 -125
  16. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  17. package/dist/storage/implementation/MongoStorageProvider.js +1 -0
  18. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  19. package/dist/storage/implementation/MongoSyncBucketStorage.js +12 -5
  20. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  21. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +9 -2
  22. package/dist/storage/implementation/MongoSyncRulesLock.js +12 -3
  23. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  24. package/dist/storage/implementation/OperationBatch.d.ts +10 -3
  25. package/dist/storage/implementation/OperationBatch.js +22 -13
  26. package/dist/storage/implementation/OperationBatch.js.map +1 -1
  27. package/dist/storage/implementation/ReplicationBatchLimits.d.ts +24 -0
  28. package/dist/storage/implementation/ReplicationBatchLimits.js +25 -0
  29. package/dist/storage/implementation/ReplicationBatchLimits.js.map +1 -0
  30. package/dist/storage/implementation/common/BatchOperationBuffer.d.ts +17 -1
  31. package/dist/storage/implementation/common/BatchOperationBuffer.js +22 -24
  32. package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
  33. package/dist/storage/implementation/common/PersistedBatch.d.ts +2 -0
  34. package/dist/storage/implementation/common/PreparedPublication.d.ts +13 -9
  35. package/dist/storage/implementation/db.d.ts +2 -0
  36. package/dist/storage/implementation/db.js +14 -0
  37. package/dist/storage/implementation/db.js.map +1 -1
  38. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +18 -1
  39. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +99 -14
  40. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  41. package/dist/storage/implementation/v1/PersistedBatchV1.js +1 -1
  42. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  43. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js +3 -1
  44. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js.map +1 -1
  45. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +39 -3
  46. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +356 -90
  47. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  48. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -5
  49. package/dist/storage/implementation/v3/PersistedBatchV3.js +26 -13
  50. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  51. package/dist/storage/implementation/v3/ReplicationPipelineV3.d.ts +84 -0
  52. package/dist/storage/implementation/v3/ReplicationPipelineV3.js +187 -0
  53. package/dist/storage/implementation/v3/ReplicationPipelineV3.js.map +1 -0
  54. package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +4 -4
  55. package/dist/storage/implementation/v3/SourceRecordStoreV3.js +4 -4
  56. package/dist/storage/implementation/v3/chunking.js +7 -3
  57. package/dist/storage/implementation/v3/chunking.js.map +1 -1
  58. package/dist/types/types.d.ts +5 -0
  59. package/dist/types/types.js +4 -0
  60. package/dist/types/types.js.map +1 -1
  61. package/dist/utils/collection-sizes.d.ts +9 -0
  62. package/dist/utils/collection-sizes.js +95 -0
  63. package/dist/utils/collection-sizes.js.map +1 -0
  64. package/dist/utils/test-utils.js +1 -4
  65. package/dist/utils/test-utils.js.map +1 -1
  66. package/package.json +7 -7
  67. package/src/migrations/db/migrations/1684951997326-init.ts +3 -36
  68. package/src/migrations/db/migrations/1741697235857-bucket-state-index.ts +3 -31
  69. package/src/migrations/db/migrations/1760433882550-bucket-state-index2.ts +3 -31
  70. package/src/migrations/db/migrations/1794268800000-v1-storage-collections.ts +22 -0
  71. package/src/storage/MongoBucketStorage.ts +80 -31
  72. package/src/storage/implementation/MongoBucketBatch.ts +47 -137
  73. package/src/storage/implementation/MongoStorageProvider.ts +1 -0
  74. package/src/storage/implementation/MongoSyncBucketStorage.ts +13 -5
  75. package/src/storage/implementation/MongoSyncRulesLock.ts +13 -3
  76. package/src/storage/implementation/OperationBatch.ts +23 -15
  77. package/src/storage/implementation/ReplicationBatchLimits.ts +45 -0
  78. package/src/storage/implementation/common/BatchOperationBuffer.ts +21 -26
  79. package/src/storage/implementation/common/PersistedBatch.ts +2 -0
  80. package/src/storage/implementation/common/PreparedPublication.ts +13 -9
  81. package/src/storage/implementation/db.ts +15 -0
  82. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
  83. package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
  84. package/src/storage/implementation/v1/VersionedPowerSyncMongoV1.ts +3 -1
  85. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +433 -101
  86. package/src/storage/implementation/v3/PersistedBatchV3.ts +26 -13
  87. package/src/storage/implementation/v3/ReplicationPipelineV3.ts +220 -0
  88. package/src/storage/implementation/v3/SourceRecordStoreV3.ts +4 -4
  89. package/src/storage/implementation/v3/chunking.ts +8 -3
  90. package/src/types/types.ts +7 -0
  91. package/src/utils/collection-sizes.ts +114 -0
  92. package/src/utils/test-utils.ts +1 -5
  93. package/test/src/concurrent_writers.test.ts +9 -15
  94. package/test/src/operation_batch.test.ts +207 -0
  95. package/test/src/prepared_publication.test.ts +187 -6
  96. package/test/src/replication_batch_config.test.ts +117 -0
  97. package/test/src/replication_pipeline.test.ts +738 -0
  98. package/test/src/replication_pipeline_benchmark.test.ts +133 -0
  99. package/test/src/replication_preparation.test.ts +4 -2
  100. package/test/src/replication_uploads.test.ts +28 -3
  101. package/test/src/storage.test.ts +24 -5
  102. package/test/src/storage_compacting.test.ts +16 -0
  103. package/test/src/storage_metrics.test.ts +88 -0
  104. package/test/src/v1_collections.test.ts +233 -0
  105. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,133 @@
1
+ import { mongoTestStorageFactoryGenerator } from '@module/utils/test-utils.js';
2
+ import { storage, updateSyncRulesFromYaml } from '@powersync/service-core';
3
+ import { getTestStorage, test_utils } from '@powersync/service-core-tests';
4
+ import { writeFile } from 'node:fs/promises';
5
+ import { setTimeout } from 'node:timers/promises';
6
+ import { expect, test, vi } from 'vitest';
7
+ import { DEFAULT_REPLICATION_BATCH_LIMITS } from '../../src/storage/implementation/ReplicationBatchLimits.js';
8
+ import { PersistedBatchV3 } from '../../src/storage/implementation/v3/PersistedBatchV3.js';
9
+ import { SourceRecordStoreV3 } from '../../src/storage/implementation/v3/SourceRecordStoreV3.js';
10
+ import { env } from './env.js';
11
+ import { MemoryObjectStorage } from './helpers/MemoryObjectStorage.js';
12
+ import { PublicationCommandMonitor } from './helpers/PublicationCommandMonitor.js';
13
+
14
+ /**
15
+ * Opt-in scheduling experiment with real MongoDB and injected I/O latency.
16
+ * Run with POWERSYNC_PIPELINE_BENCHMARK=1 and --silent=false through the MongoDB test wrapper.
17
+ * Set POWERSYNC_PIPELINE_BENCHMARK_OUTPUT to also save the JSON report.
18
+ * Serial mode drains at every input boundary; both modes keep production batch
19
+ * targets and identical offloaded payloads and command instrumentation. Timing ends at durable commit.
20
+ * This isolates overlap, rather than predicting production throughput or RSS.
21
+ */
22
+ test.skipIf(!process.env.POWERSYNC_PIPELINE_BENCHMARK)(
23
+ 'measures serial versus pipelined v4 publication',
24
+ async () => {
25
+ const batchRows = DEFAULT_REPLICATION_BATCH_LIMITS.maxInputBatchCount;
26
+ const totalRows = 10 * batchRows;
27
+ const readDelayMs = 10;
28
+ const publicationDelayMs = 20;
29
+ const uploadDelayMs = 10;
30
+ const results: unknown[] = [];
31
+ for (const serial of [true, false]) {
32
+ const objects = new MemoryObjectStorage();
33
+ const gen = mongoTestStorageFactoryGenerator({
34
+ url: env.MONGO_TEST_URL,
35
+ isCI: env.CI,
36
+ monitorCommands: true,
37
+ objectStorage: objects,
38
+ inlineThresholdBytes: 0
39
+ });
40
+ await using factory = await gen.factory();
41
+ const stream = await factory.updateSyncRules(
42
+ updateSyncRulesFromYaml(
43
+ `
44
+ config:
45
+ edition: 3
46
+ streams:
47
+ items:
48
+ query: SELECT * FROM items
49
+ `,
50
+ { storageVersion: 4 }
51
+ )
52
+ );
53
+ const buckets = await getTestStorage(factory, stream);
54
+ await using writer = await buckets.createWriter(test_utils.BATCH_OPTIONS);
55
+ const table = await test_utils.resolveTestTable(writer, 'items', ['id'], gen, 1);
56
+ await writer.markAllSnapshotDone('1/1');
57
+ await writer.save({
58
+ sourceTable: table,
59
+ tag: storage.SaveOperationTag.INSERT,
60
+ after: { id: 'warmup', description: 'warmup' },
61
+ afterReplicaId: 'warmup'
62
+ });
63
+ await writer.commit('1/1');
64
+ const load = SourceRecordStoreV3.prototype.loadDocuments;
65
+ using _read = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments').mockImplementation(async function (
66
+ this: SourceRecordStoreV3,
67
+ ...args
68
+ ) {
69
+ await setTimeout(readDelayMs);
70
+ return load.apply(this, args);
71
+ });
72
+ const publish = PersistedBatchV3.prototype.publish;
73
+ using _publish = vi.spyOn(PersistedBatchV3.prototype, 'publish').mockImplementation(async function (
74
+ this: PersistedBatchV3,
75
+ ...args
76
+ ) {
77
+ await setTimeout(publicationDelayMs);
78
+ return publish.apply(this, args);
79
+ });
80
+ const put = objects.put.bind(objects);
81
+ let uploadCount = 0;
82
+ using _upload = vi.spyOn(objects, 'put').mockImplementation(async (...args) => {
83
+ uploadCount++;
84
+ await setTimeout(uploadDelayMs);
85
+ return put(...args);
86
+ });
87
+ using monitor = new PublicationCommandMonitor(factory.db.client);
88
+ const peak = process.memoryUsage();
89
+ const startedAt = performance.now();
90
+ const description = 'x'.repeat(128);
91
+ for (let i = 0; i < totalRows; i++) {
92
+ await writer.save({
93
+ sourceTable: table,
94
+ tag: storage.SaveOperationTag.INSERT,
95
+ after: { id: String(i), description },
96
+ afterReplicaId: String(i)
97
+ });
98
+ if ((i + 1) % batchRows === 0) {
99
+ if (serial) {
100
+ await writer.flush();
101
+ }
102
+ const memory = process.memoryUsage();
103
+ for (const key of ['rss', 'heapUsed', 'external', 'arrayBuffers'] as const) {
104
+ peak[key] = Math.max(peak[key], memory[key]);
105
+ }
106
+ }
107
+ }
108
+ await writer.commit('1/2');
109
+ const elapsedMs = performance.now() - startedAt;
110
+ const summary = monitor.summary();
111
+ expect((await buckets.getCheckpoint()).lsn).toBe('1/2');
112
+ results.push({
113
+ serial,
114
+ totalRows,
115
+ batchRows,
116
+ readDelayMs,
117
+ publicationDelayMs,
118
+ uploadDelayMs,
119
+ uploadCount,
120
+ elapsedMs,
121
+ rowsPerSecond: (totalRows * 1000) / elapsedMs,
122
+ sampledProcessMemoryPeak: peak,
123
+ ...summary
124
+ });
125
+ }
126
+ const report = { benchmark: 'v4-publication-pipeline', node: process.version, results };
127
+ console.info(JSON.stringify(report));
128
+ if (process.env.POWERSYNC_PIPELINE_BENCHMARK_OUTPUT) {
129
+ await writeFile(process.env.POWERSYNC_PIPELINE_BENCHMARK_OUTPUT, JSON.stringify(report, null, 2));
130
+ }
131
+ },
132
+ 120_000
133
+ );
@@ -157,6 +157,9 @@ describe.each([3, 4])('eager replication preparation v%s', (version) => {
157
157
  after: { id: 'A', description: '"'.repeat(8 * 1024 * 1024), retained: 'old' },
158
158
  afterReplicaId: test_utils.rid('A')
159
159
  });
160
+ // Automatic save admission is speculative; the explicit barrier waits for
161
+ // the immutable publication and its transaction retry.
162
+ await writer.flush();
160
163
  expect(attempts).toBe(2);
161
164
  expect(logged).toHaveBeenCalledTimes(1);
162
165
  expect(logged).toHaveBeenCalledWith(expect.stringMatching(/^Row .* too large: .* bytes\. Removing\.$/));
@@ -532,8 +535,7 @@ describe.each([3, 4])('eager replication preparation v%s', (version) => {
532
535
  try {
533
536
  await entered.promise;
534
537
  using read = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments');
535
- await save(writer, context.table, 'after cleanup');
536
- pending.push(writer.flush());
538
+ pending.push(save(writer, context.table, 'after cleanup').then(() => writer.flush()));
537
539
  expect(read).not.toHaveBeenCalled();
538
540
  release.resolve();
539
541
  await Promise.all(pending);
@@ -58,7 +58,20 @@ async function open(version: number, options: Partial<storage.CreateWriterOption
58
58
  after: { id: 'A', description: 'offloaded' },
59
59
  afterReplicaId: test_utils.rid('A')
60
60
  });
61
- return { factory, stream, bucketStorage, writer, table, db, objectStorage, markers, lifecycle, data, records };
61
+ return {
62
+ factory,
63
+ factoryGen,
64
+ stream,
65
+ bucketStorage,
66
+ writer,
67
+ table,
68
+ db,
69
+ objectStorage,
70
+ markers,
71
+ lifecycle,
72
+ data,
73
+ records
74
+ };
62
75
  }
63
76
 
64
77
  describe.each([3, 4])('replication uploads v%s', (version) => {
@@ -133,8 +146,20 @@ describe.each([3, 4])('replication uploads v%s', (version) => {
133
146
  expect(await context.markers.countDocuments()).toBe(1);
134
147
  expect(await context.records.countDocuments()).toBe(0);
135
148
  expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(0n);
136
- // A later explicit retry reevaluates the retained input using a fresh path.
137
- await writer.commit('1/2');
149
+ // Ambiguous upload-marker registration invalidates the lease attempt. Replay
150
+ // under a fresh lease uses a new path and leaves the abandoned marker protected.
151
+ await expect(writer.commit('1/2')).rejects.toThrow('restart');
152
+ await test_utils.releaseTestStorageLease(context.factory, context.stream.replicationStreamId);
153
+ const restarted = await getTestStorage(context.factory, context.stream);
154
+ await using replay = await restarted.createWriter(test_utils.BATCH_OPTIONS);
155
+ const replayTable = await test_utils.resolveTestTable(replay, 'items', ['id'], context.factoryGen, 1);
156
+ await replay.save({
157
+ sourceTable: replayTable,
158
+ tag: storage.SaveOperationTag.INSERT,
159
+ after: { id: 'A', description: 'offloaded' },
160
+ afterReplicaId: test_utils.rid('A')
161
+ });
162
+ await replay.commit('1/2');
138
163
  expect(put).toHaveBeenCalledTimes(1);
139
164
  expect(await context.markers.countDocuments()).toBe(1);
140
165
  expect(await context.records.countDocuments()).toBe(1);
@@ -152,6 +152,30 @@ bucket_definitions:
152
152
  }
153
153
  });
154
154
 
155
+ test.runIf(storageVersion >= 3)('rejects custom checkpoints without an event definition id', async () => {
156
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
157
+ const syncRules = await factory.updateSyncRules(
158
+ updateSyncRulesFromYaml(
159
+ `
160
+ config:
161
+ edition: 3
162
+
163
+ streams:
164
+ global:
165
+ query: SELECT * FROM checkpoints
166
+ `,
167
+ { storageVersion }
168
+ )
169
+ );
170
+ const bucketStorage = await getTestStorage(factory, syncRules);
171
+ const db = bucketStorage.db as VersionedPowerSyncMongoV3;
172
+ // Keep rejected input in its own test: disposal invalidates the shared lease.
173
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
174
+ writer.addCustomWriteCheckpoint({ user_id: 'invalid', checkpoint: 1n });
175
+ await expect(writer.flush()).rejects.toThrow('require an event definition id');
176
+ await expect(db.listCustomCheckpointRequestCollections(syncRules.replicationStreamId)).resolves.toEqual([]);
177
+ });
178
+
155
179
  test.runIf(storageVersion >= 3)(
156
180
  'stores and streams checkpoints from different event definitions independently',
157
181
  async (context) => {
@@ -211,11 +235,6 @@ event_definitions:
211
235
  // they must not require the lazily-created collection to exist.
212
236
  await expect(bucketStorage.lastWriteCheckpoint({ user_id: 'user1' })).resolves.toBeNull();
213
237
 
214
- await using invalidWriter = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
215
- invalidWriter.addCustomWriteCheckpoint({ user_id: 'invalid', checkpoint: 1n });
216
- await expect(invalidWriter.flush()).rejects.toThrow('require an event definition id');
217
- await expect(db.listCustomCheckpointRequestCollections(syncRules.replicationStreamId)).resolves.toEqual([]);
218
-
219
238
  await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
220
239
  await writer.markAllSnapshotDone('1/1');
221
240
  const abortController = new AbortController();
@@ -861,6 +861,22 @@ bucket_definitions:
861
861
  expect(chunks[0]).toHaveLength(1);
862
862
  });
863
863
 
864
+ test('chunk targets count UTF-8 payload bytes rather than string length', () => {
865
+ const data = '界'.repeat(200_000);
866
+ const ops = [makeBucketDataDoc({ o: 1n, data }), makeBucketDataDoc({ o: 2n, data })];
867
+ expect(chunkBucketData(ops)).toEqual([[ops[0]], [ops[1]]]);
868
+ for (const chunk of chunkBucketData(ops)) {
869
+ const document = serializeBucketData('test[]', chunk);
870
+ expect(document.size).toBe(bson.calculateObjectSize(document.ops!));
871
+ }
872
+ });
873
+
874
+ test('chunk targets also account for large row identities', () => {
875
+ const row_id = 'x'.repeat(600_000);
876
+ const ops = [makeBucketDataDoc({ o: 1n, row_id }), makeBucketDataDoc({ o: 2n, row_id })];
877
+ expect(chunkBucketData(ops)).toEqual([[ops[0]], [ops[1]]]);
878
+ });
879
+
864
880
  test('9. serialization fidelity - null data preserved', () => {
865
881
  const ops = [makeBucketDataDoc({ o: 1n, data: null })];
866
882
  const doc = serializeBucketData('test[]', ops);
@@ -0,0 +1,88 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { describe, expect, test, vi } from 'vitest';
3
+ import { INITIALIZED_MONGO_STORAGE_FACTORY } from './util.js';
4
+
5
+ describe('storage metrics collection sizes', () => {
6
+ test('uses sequential estimated dataSize commands for logical sizes', async () => {
7
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
8
+ const before = await factory.getStorageMetrics();
9
+ const document = { _id: new mongo.ObjectId(), value: 'payload' };
10
+ const names = ['bucket_data_999_metrics', 'parameter_index_999_metrics', 'source_records_999_metrics'];
11
+ for (const name of names) {
12
+ await factory.db.db.collection(name).insertOne(document);
13
+ }
14
+ const expectedSize = mongo.BSON.calculateObjectSize(document);
15
+ const command = factory.db.db.command.bind(factory.db.db);
16
+ let inFlight = 0;
17
+ let maxInFlight = 0;
18
+ using commands = vi.spyOn(factory.db.db, 'command').mockImplementation(async (...args) => {
19
+ inFlight++;
20
+ maxInFlight = Math.max(maxInFlight, inFlight);
21
+ try {
22
+ return await command(...args);
23
+ } finally {
24
+ inFlight--;
25
+ }
26
+ });
27
+
28
+ const after = await factory.getStorageMetrics();
29
+
30
+ expect(after.operations_size_bytes - before.operations_size_bytes).toBe(expectedSize);
31
+ expect(after.parameters_size_bytes - before.parameters_size_bytes).toBe(expectedSize);
32
+ expect(after.replication_size_bytes - before.replication_size_bytes).toBe(expectedSize);
33
+ expect(maxInFlight).toBe(1);
34
+ for (const name of names) {
35
+ expect(commands).toHaveBeenCalledWith(
36
+ { dataSize: `${factory.db.db.databaseName}.${name}`, estimate: true },
37
+ { readPreference: undefined }
38
+ );
39
+ }
40
+ });
41
+
42
+ test.each([
43
+ { code: 59, errmsg: 'no such command: dataSize' },
44
+ { code: 115, errmsg: 'Command dataSize is not supported' },
45
+ { code: 8000, errmsg: 'dataSize is not allowed in this atlas tier' }
46
+ ])('caches unsupported dataSize errors ($code) and falls back across union batches', async (response) => {
47
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
48
+ const before = await factory.getStorageMetrics();
49
+ const document = { _id: new mongo.ObjectId(), value: 'payload' };
50
+ for (let index = 0; index < 101; index++) {
51
+ await factory.db.db.collection(`bucket_data_999_metrics_${index}`).insertOne(document);
52
+ }
53
+ const expectedSize = 101 * mongo.BSON.calculateObjectSize(document);
54
+ const command = factory.db.db.command.bind(factory.db.db);
55
+ // Fail after a successful size query to check that fallback doesn't double-count partial results.
56
+ using commands = vi
57
+ .spyOn(factory.db.db, 'command')
58
+ .mockImplementationOnce((...args) => command(...args))
59
+ .mockRejectedValueOnce(new mongo.MongoServerError(response));
60
+
61
+ const first = await factory.getStorageMetrics();
62
+ expect(first.operations_size_bytes - before.operations_size_bytes).toBe(expectedSize);
63
+ expect(commands).toHaveBeenCalledTimes(2);
64
+
65
+ const additionalDocument = { _id: new mongo.ObjectId() };
66
+ await factory.db.db.collection('bucket_data_999_metrics_0').insertOne(additionalDocument);
67
+ const second = await factory.getStorageMetrics();
68
+ expect(second.operations_size_bytes - first.operations_size_bytes).toBe(
69
+ mongo.BSON.calculateObjectSize(additionalDocument)
70
+ );
71
+ expect(commands).toHaveBeenCalledTimes(2);
72
+ });
73
+
74
+ test.each([
75
+ { code: 13, errmsg: 'not authorized to execute dataSize' },
76
+ { code: 8000, errmsg: 'unrelated Atlas error' },
77
+ { code: 11600, errmsg: 'interrupted at shutdown' }
78
+ ])('propagates other errors ($code) and retries dataSize on the next refresh', async (response) => {
79
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
80
+ await factory.db.db.collection('bucket_data_999_metrics').insertOne({ _id: new mongo.ObjectId() });
81
+ const error = new mongo.MongoServerError(response);
82
+ using commands = vi.spyOn(factory.db.db, 'command').mockRejectedValueOnce(error);
83
+
84
+ await expect(factory.getStorageMetrics()).rejects.toBe(error);
85
+ await expect(factory.getStorageMetrics()).resolves.toHaveProperty('operations_size_bytes');
86
+ expect(commands.mock.calls.length).toBeGreaterThan(1);
87
+ });
88
+ });
@@ -0,0 +1,233 @@
1
+ import { MongoBucketStorage } from '@module/storage/MongoBucketStorage.js';
2
+ import { mongoTestStorageFactoryGenerator } from '@module/utils/test-utils.js';
3
+ import { storage, updateSyncRulesFromYaml } from '@powersync/service-core';
4
+ import { getTestStorage, releaseTestStorageLease, test_utils } from '@powersync/service-core-tests';
5
+ import { describe, expect, test, vi } from 'vitest';
6
+ import { up as parameterIndexes } from '../../src/migrations/db/migrations/1684951997326-init.js';
7
+ import { up as bucketIndexes } from '../../src/migrations/db/migrations/1741697235857-bucket-state-index.js';
8
+ import { up as dirtyBucketIndexes } from '../../src/migrations/db/migrations/1760433882550-bucket-state-index2.js';
9
+ import {
10
+ up as removeUnusedV1Collections,
11
+ down as restoreV1Collections
12
+ } from '../../src/migrations/db/migrations/1794268800000-v1-storage-collections.js';
13
+ import { env } from './env.js';
14
+
15
+ const collectionNames = ['current_data', 'bucket_data', 'bucket_parameters', 'bucket_state', 'source_tables'];
16
+ const migrationContext = {
17
+ service_context: {
18
+ configuration: { storage: { type: 'mongodb', uri: env.MONGO_TEST_URL }, slot_name_prefix: 'test_' }
19
+ }
20
+ } as unknown as Parameters<typeof parameterIndexes>[0];
21
+ const testStorage = mongoTestStorageFactoryGenerator({
22
+ url: env.MONGO_TEST_URL,
23
+ isCI: env.CI,
24
+ monitorCommands: true,
25
+ supportsMultipleSyncConfigs: true
26
+ });
27
+ const yaml = /* yaml */ `
28
+ # sync config fixture.
29
+ config:
30
+ edition: 3
31
+ streams:
32
+ global:
33
+ query: SELECT id FROM test
34
+ `;
35
+
36
+ async function activate(factory: MongoBucketStorage, version: number, lsn: string) {
37
+ const stream = await factory.updateSyncRules(updateSyncRulesFromYaml(yaml, { storageVersion: version }));
38
+ const bucketStorage = await getTestStorage(factory, stream);
39
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
40
+ const sourceTable = await test_utils.resolveTestTable(
41
+ writer,
42
+ 'test',
43
+ ['id'],
44
+ testStorage,
45
+ stream.replicationStreamId
46
+ );
47
+ await writer.save({
48
+ sourceTable,
49
+ tag: storage.SaveOperationTag.INSERT,
50
+ after: { id: 'item-1' },
51
+ afterReplicaId: test_utils.rid('item-1')
52
+ });
53
+ await writer.markAllSnapshotDone(lsn);
54
+ await writer.commit(lsn);
55
+ return stream;
56
+ }
57
+
58
+ async function names(factory: MongoBucketStorage) {
59
+ return (await factory.db.db.listCollections({}, { nameOnly: true }).toArray()).map((c) => c.name);
60
+ }
61
+
62
+ async function terminateStopped(factory: MongoBucketStorage) {
63
+ for (const stream of await factory.getStoppedReplicationStreams()) {
64
+ const lock = await stream.lock();
65
+ try {
66
+ await factory.getInstance(stream, { skipLifecycleHooks: true }).terminate({ clearStorage: true });
67
+ } finally {
68
+ await lock.release();
69
+ }
70
+ }
71
+ }
72
+
73
+ describe('v1/v2 collection lifecycle', () => {
74
+ test('migrations and v4 initialization do not create v1/v2 collections', async () => {
75
+ await using factory = await testStorage.factory();
76
+ await factory.db.drop();
77
+ await factory.db.createCheckpointEventsCollection();
78
+ for (const migration of [parameterIndexes, bucketIndexes, dirtyBucketIndexes, removeUnusedV1Collections]) {
79
+ await migration(migrationContext);
80
+ }
81
+ for (const name of collectionNames) expect(await names(factory)).not.toContain(name);
82
+ await activate(factory, storage.STORAGE_VERSION_4, '1/1');
83
+ for (const name of collectionNames) expect(await names(factory)).not.toContain(name);
84
+ });
85
+
86
+ test.each([1, 2])('drops unused v%i collections instead of deleting individual records', async (version) => {
87
+ await using factory = await testStorage.factory();
88
+ const previous = await activate(factory, version, '1/1');
89
+ await releaseTestStorageLease(factory, previous.replicationStreamId);
90
+ expect(await names(factory)).toEqual(expect.arrayContaining(collectionNames));
91
+ const current = await activate(factory, storage.STORAGE_VERSION_4, '2/1');
92
+ const dropped: string[] = [];
93
+ const deleted: string[] = [];
94
+ factory.db.client.on('commandStarted', (event) => {
95
+ if (event.commandName === 'drop') dropped.push(event.command.drop);
96
+ if (event.commandName === 'delete') deleted.push(event.command.delete);
97
+ });
98
+ await terminateStopped(factory);
99
+ expect(dropped).toEqual(expect.arrayContaining(collectionNames));
100
+ expect(deleted.filter((name) => collectionNames.includes(name))).toEqual([]);
101
+ for (const name of collectionNames) expect(await names(factory)).not.toContain(name);
102
+ expect((await factory.db.sync_rules.findOne({ _id: previous.replicationStreamId }))?.state).toBe(
103
+ storage.SyncRuleState.TERMINATED
104
+ );
105
+ expect((await factory.getActiveSyncConfig())?.replicationStream.replicationStreamId).toBe(
106
+ current.replicationStreamId
107
+ );
108
+
109
+ const returning = await activate(factory, version, '3/1');
110
+ await releaseTestStorageLease(factory, current.replicationStreamId);
111
+ await terminateStopped(factory);
112
+ expect(await names(factory)).toEqual(expect.arrayContaining(collectionNames));
113
+ expect((await factory.db.bucket_parameters.listIndexes().toArray()).map((index) => index.name)).toContain(
114
+ 'lookup1'
115
+ );
116
+ expect((await factory.db.bucket_state.listIndexes().toArray()).map((index) => index.name)).toEqual(
117
+ expect.arrayContaining(['bucket_updates', 'dirty_count'])
118
+ );
119
+ expect(await factory.db.current_data.countDocuments({ '_id.g': returning.replicationStreamId })).toBe(1);
120
+ });
121
+
122
+ test.each([storage.SyncRuleState.PROCESSING, storage.SyncRuleState.ACTIVE, storage.SyncRuleState.ERRORED])(
123
+ 'retains shared collections for a stream in state %s and deletes only stopped stream records',
124
+ async (state) => {
125
+ await using factory = await testStorage.factory();
126
+ const previous = await activate(factory, storage.STORAGE_VERSION_1, '1/1');
127
+ await releaseTestStorageLease(factory, previous.replicationStreamId);
128
+ const current = await activate(factory, storage.STORAGE_VERSION_2, '2/1');
129
+ await factory.db.sync_rules.updateOne({ _id: current.replicationStreamId }, { $set: { state } });
130
+ await terminateStopped(factory);
131
+ expect(await names(factory)).toEqual(expect.arrayContaining(collectionNames));
132
+ expect(await factory.db.current_data.countDocuments({ '_id.g': previous.replicationStreamId })).toBe(0);
133
+ expect(await factory.db.current_data.countDocuments({ '_id.g': current.replicationStreamId })).toBe(1);
134
+ // A missing storage_version also identifies a v1 stream.
135
+ await factory.db.sync_rules.updateOne({ _id: current.replicationStreamId }, { $unset: { storage_version: 1 } });
136
+ expect(await factory.dropUnusedV1StorageCollections()).toBe(false);
137
+ await removeUnusedV1Collections(migrationContext);
138
+ expect(await names(factory)).toEqual(expect.arrayContaining(collectionNames));
139
+ expect(await factory.db.current_data.countDocuments({ '_id.g': current.replicationStreamId })).toBe(1);
140
+ }
141
+ );
142
+
143
+ test('restarting and clearing an active v4 stream do not drop v1 collections', async () => {
144
+ await using factory = await testStorage.factory();
145
+ const previous = await activate(factory, storage.STORAGE_VERSION_2, '1/1');
146
+ await releaseTestStorageLease(factory, previous.replicationStreamId);
147
+ const current = await activate(factory, storage.STORAGE_VERSION_4, '2/1');
148
+ await factory.db.sync_rules.updateOne(
149
+ { _id: previous.replicationStreamId },
150
+ { $set: { state: storage.SyncRuleState.TERMINATED } }
151
+ );
152
+ await using restarted = await testStorage.factory({ doNotClear: true });
153
+ const drop = vi.spyOn(restarted, 'dropUnusedV1StorageCollections');
154
+ expect(await restarted.getStoppedReplicationStreams()).toEqual([]);
155
+ expect(drop).not.toHaveBeenCalled();
156
+ expect(await names(restarted)).toEqual(expect.arrayContaining(collectionNames));
157
+ await factory.getInstance(current).clear();
158
+ expect(await names(factory)).toEqual(expect.arrayContaining(collectionNames));
159
+ });
160
+
161
+ test('migration removes unused v1 collections and rollback recreates collections and indexes', async () => {
162
+ await using factory = await testStorage.factory();
163
+ const previous = await activate(factory, storage.STORAGE_VERSION_2, '1/1');
164
+ await releaseTestStorageLease(factory, previous.replicationStreamId);
165
+ const current = await activate(factory, storage.STORAGE_VERSION_4, '2/1');
166
+ await factory.db.sync_rules.updateOne(
167
+ { _id: previous.replicationStreamId },
168
+ { $set: { state: storage.SyncRuleState.TERMINATED } }
169
+ );
170
+ await removeUnusedV1Collections(migrationContext);
171
+ for (const name of collectionNames) expect(await names(factory)).not.toContain(name);
172
+ // Both directions are idempotent, and rollback must retain any existing data.
173
+ await removeUnusedV1Collections(migrationContext);
174
+ await restoreV1Collections(migrationContext);
175
+ await factory.db.current_data.insertOne({ _id: { g: 99, t: 'test', k: 'item' } } as any);
176
+ await restoreV1Collections(migrationContext);
177
+ expect(await names(factory)).toEqual(expect.arrayContaining(collectionNames));
178
+ expect(await factory.db.current_data.countDocuments({ '_id.g': 99 })).toBe(1);
179
+ expect((await factory.db.bucket_parameters.listIndexes().toArray()).map((index) => index.name)).toEqual(
180
+ expect.arrayContaining(['_id_', 'lookup1'])
181
+ );
182
+ expect((await factory.db.bucket_state.listIndexes().toArray()).map((index) => index.name)).toEqual(
183
+ expect.arrayContaining(['_id_', 'bucket_updates', 'dirty_count'])
184
+ );
185
+ expect((await factory.getActiveSyncConfig())?.replicationStream.replicationStreamId).toBe(
186
+ current.replicationStreamId
187
+ );
188
+ });
189
+
190
+ test('retries a partially completed collection drop', async () => {
191
+ await using factory = await testStorage.factory();
192
+ const previous = await activate(factory, storage.STORAGE_VERSION_2, '1/1');
193
+ await releaseTestStorageLease(factory, previous.replicationStreamId);
194
+ await activate(factory, storage.STORAGE_VERSION_4, '2/1');
195
+ const drop = vi.spyOn(factory.db.bucket_parameters, 'drop').mockRejectedValueOnce(new Error('drop interrupted'));
196
+ await expect(terminateStopped(factory)).rejects.toThrow('drop interrupted');
197
+ expect((await factory.db.sync_rules.findOne({ _id: previous.replicationStreamId }))?.state).toBe(
198
+ storage.SyncRuleState.STOP
199
+ );
200
+ await terminateStopped(factory);
201
+ for (const name of collectionNames) expect(await names(factory)).not.toContain(name);
202
+ drop.mockRestore();
203
+ });
204
+
205
+ test('serializes collection drops with deployment by another worker', async () => {
206
+ await using factory = await testStorage.factory();
207
+ await using other = await testStorage.factory({ doNotClear: true });
208
+ const entered = Promise.withResolvers<void>();
209
+ const resume = Promise.withResolvers<void>();
210
+ const originalDrop = factory.db.current_data.drop.bind(factory.db.current_data);
211
+ const drop = vi.spyOn(factory.db.current_data, 'drop').mockImplementation(async (options) => {
212
+ entered.resolve();
213
+ await resume.promise;
214
+ return originalDrop(options);
215
+ });
216
+ const cleanup = factory.dropUnusedV1StorageCollections();
217
+ await entered.promise;
218
+ let deployed = false;
219
+ const deployment = other.updateSyncRules(updateSyncRulesFromYaml(yaml, { storageVersion: 2 })).then(() => {
220
+ deployed = true;
221
+ });
222
+ try {
223
+ await new Promise((resolve) => setTimeout(resolve, 100));
224
+ expect(deployed).toBe(false);
225
+ } finally {
226
+ resume.resolve();
227
+ await cleanup;
228
+ drop.mockRestore();
229
+ }
230
+ await deployment;
231
+ expect(deployed).toBe(true);
232
+ }, 15_000);
233
+ });