@powersync/service-module-mongodb-storage 0.0.0-dev-20250108073049

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 (123) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +67 -0
  3. package/README.md +3 -0
  4. package/dist/index.d.ts +5 -0
  5. package/dist/index.js +6 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/migrations/MongoMigrationAgent.d.ts +12 -0
  8. package/dist/migrations/MongoMigrationAgent.js +25 -0
  9. package/dist/migrations/MongoMigrationAgent.js.map +1 -0
  10. package/dist/migrations/db/migrations/1684951997326-init.d.ts +3 -0
  11. package/dist/migrations/db/migrations/1684951997326-init.js +30 -0
  12. package/dist/migrations/db/migrations/1684951997326-init.js.map +1 -0
  13. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.d.ts +2 -0
  14. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.js +5 -0
  15. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.js.map +1 -0
  16. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.d.ts +3 -0
  17. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js +54 -0
  18. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js.map +1 -0
  19. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.d.ts +3 -0
  20. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js +26 -0
  21. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js.map +1 -0
  22. package/dist/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.d.ts +3 -0
  23. package/dist/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.js +28 -0
  24. package/dist/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.js.map +1 -0
  25. package/dist/migrations/mongo-migration-store.d.ts +7 -0
  26. package/dist/migrations/mongo-migration-store.js +49 -0
  27. package/dist/migrations/mongo-migration-store.js.map +1 -0
  28. package/dist/module/MongoStorageModule.d.ts +10 -0
  29. package/dist/module/MongoStorageModule.js +31 -0
  30. package/dist/module/MongoStorageModule.js.map +1 -0
  31. package/dist/storage/MongoBucketStorage.d.ts +48 -0
  32. package/dist/storage/MongoBucketStorage.js +426 -0
  33. package/dist/storage/MongoBucketStorage.js.map +1 -0
  34. package/dist/storage/implementation/MongoBucketBatch.d.ts +72 -0
  35. package/dist/storage/implementation/MongoBucketBatch.js +681 -0
  36. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -0
  37. package/dist/storage/implementation/MongoCompactor.d.ts +40 -0
  38. package/dist/storage/implementation/MongoCompactor.js +300 -0
  39. package/dist/storage/implementation/MongoCompactor.js.map +1 -0
  40. package/dist/storage/implementation/MongoIdSequence.d.ts +12 -0
  41. package/dist/storage/implementation/MongoIdSequence.js +21 -0
  42. package/dist/storage/implementation/MongoIdSequence.js.map +1 -0
  43. package/dist/storage/implementation/MongoPersistedSyncRules.d.ts +9 -0
  44. package/dist/storage/implementation/MongoPersistedSyncRules.js +9 -0
  45. package/dist/storage/implementation/MongoPersistedSyncRules.js.map +1 -0
  46. package/dist/storage/implementation/MongoPersistedSyncRulesContent.d.ts +20 -0
  47. package/dist/storage/implementation/MongoPersistedSyncRulesContent.js +26 -0
  48. package/dist/storage/implementation/MongoPersistedSyncRulesContent.js.map +1 -0
  49. package/dist/storage/implementation/MongoStorageProvider.d.ts +5 -0
  50. package/dist/storage/implementation/MongoStorageProvider.js +33 -0
  51. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -0
  52. package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +36 -0
  53. package/dist/storage/implementation/MongoSyncBucketStorage.js +529 -0
  54. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -0
  55. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +16 -0
  56. package/dist/storage/implementation/MongoSyncRulesLock.js +65 -0
  57. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -0
  58. package/dist/storage/implementation/MongoTestStorageFactoryGenerator.d.ts +7 -0
  59. package/dist/storage/implementation/MongoTestStorageFactoryGenerator.js +16 -0
  60. package/dist/storage/implementation/MongoTestStorageFactoryGenerator.js.map +1 -0
  61. package/dist/storage/implementation/MongoWriteCheckpointAPI.d.ts +20 -0
  62. package/dist/storage/implementation/MongoWriteCheckpointAPI.js +104 -0
  63. package/dist/storage/implementation/MongoWriteCheckpointAPI.js.map +1 -0
  64. package/dist/storage/implementation/OperationBatch.d.ts +34 -0
  65. package/dist/storage/implementation/OperationBatch.js +119 -0
  66. package/dist/storage/implementation/OperationBatch.js.map +1 -0
  67. package/dist/storage/implementation/PersistedBatch.d.ts +46 -0
  68. package/dist/storage/implementation/PersistedBatch.js +223 -0
  69. package/dist/storage/implementation/PersistedBatch.js.map +1 -0
  70. package/dist/storage/implementation/db.d.ts +36 -0
  71. package/dist/storage/implementation/db.js +47 -0
  72. package/dist/storage/implementation/db.js.map +1 -0
  73. package/dist/storage/implementation/models.d.ts +139 -0
  74. package/dist/storage/implementation/models.js +2 -0
  75. package/dist/storage/implementation/models.js.map +1 -0
  76. package/dist/storage/implementation/util.d.ts +46 -0
  77. package/dist/storage/implementation/util.js +155 -0
  78. package/dist/storage/implementation/util.js.map +1 -0
  79. package/dist/storage/storage-index.d.ts +14 -0
  80. package/dist/storage/storage-index.js +15 -0
  81. package/dist/storage/storage-index.js.map +1 -0
  82. package/dist/types/types.d.ts +18 -0
  83. package/dist/types/types.js +9 -0
  84. package/dist/types/types.js.map +1 -0
  85. package/package.json +48 -0
  86. package/src/index.ts +7 -0
  87. package/src/migrations/MongoMigrationAgent.ts +39 -0
  88. package/src/migrations/db/migrations/1684951997326-init.ts +39 -0
  89. package/src/migrations/db/migrations/1688556755264-initial-sync-rules.ts +5 -0
  90. package/src/migrations/db/migrations/1702295701188-sync-rule-state.ts +105 -0
  91. package/src/migrations/db/migrations/1711543888062-write-checkpoint-index.ts +38 -0
  92. package/src/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.ts +40 -0
  93. package/src/migrations/mongo-migration-store.ts +62 -0
  94. package/src/module/MongoStorageModule.ts +37 -0
  95. package/src/storage/MongoBucketStorage.ts +531 -0
  96. package/src/storage/implementation/MongoBucketBatch.ts +896 -0
  97. package/src/storage/implementation/MongoCompactor.ts +381 -0
  98. package/src/storage/implementation/MongoIdSequence.ts +24 -0
  99. package/src/storage/implementation/MongoPersistedSyncRules.ts +16 -0
  100. package/src/storage/implementation/MongoPersistedSyncRulesContent.ts +49 -0
  101. package/src/storage/implementation/MongoStorageProvider.ts +39 -0
  102. package/src/storage/implementation/MongoSyncBucketStorage.ts +612 -0
  103. package/src/storage/implementation/MongoSyncRulesLock.ts +88 -0
  104. package/src/storage/implementation/MongoTestStorageFactoryGenerator.ts +25 -0
  105. package/src/storage/implementation/MongoWriteCheckpointAPI.ts +146 -0
  106. package/src/storage/implementation/OperationBatch.ts +129 -0
  107. package/src/storage/implementation/PersistedBatch.ts +283 -0
  108. package/src/storage/implementation/db.ts +87 -0
  109. package/src/storage/implementation/models.ts +161 -0
  110. package/src/storage/implementation/util.ts +169 -0
  111. package/src/storage/storage-index.ts +14 -0
  112. package/src/types/types.ts +18 -0
  113. package/test/src/__snapshots__/storage_sync.test.ts.snap +332 -0
  114. package/test/src/env.ts +6 -0
  115. package/test/src/setup.ts +9 -0
  116. package/test/src/storage.test.ts +7 -0
  117. package/test/src/storage_compacting.test.ts +6 -0
  118. package/test/src/storage_sync.test.ts +113 -0
  119. package/test/src/util.ts +8 -0
  120. package/test/tsconfig.json +31 -0
  121. package/tsconfig.json +31 -0
  122. package/tsconfig.tsbuildinfo +1 -0
  123. package/vitest.config.ts +15 -0
@@ -0,0 +1,531 @@
1
+ import { SqlSyncRules } from '@powersync/service-sync-rules';
2
+ import { wrapWithAbort } from 'ix/asynciterable/operators/withabort.js';
3
+ import { LRUCache } from 'lru-cache/min';
4
+ import * as mongo from 'mongodb';
5
+ import * as timers from 'timers/promises';
6
+
7
+ import { storage, sync, utils } from '@powersync/service-core';
8
+
9
+ import { DisposableObserver, logger } from '@powersync/lib-services-framework';
10
+ import { v4 as uuid } from 'uuid';
11
+
12
+ import * as lib_mongo from '@powersync/lib-service-mongodb';
13
+ import { PowerSyncMongo } from './implementation/db.js';
14
+ import { SyncRuleDocument } from './implementation/models.js';
15
+ import { MongoPersistedSyncRulesContent } from './implementation/MongoPersistedSyncRulesContent.js';
16
+ import { MongoSyncBucketStorage } from './implementation/MongoSyncBucketStorage.js';
17
+ import { generateSlotName } from './implementation/util.js';
18
+
19
+ export class MongoBucketStorage
20
+ extends DisposableObserver<storage.BucketStorageFactoryListener>
21
+ implements storage.BucketStorageFactory
22
+ {
23
+ private readonly client: mongo.MongoClient;
24
+ private readonly session: mongo.ClientSession;
25
+ // TODO: This is still Postgres specific and needs to be reworked
26
+ public readonly slot_name_prefix: string;
27
+
28
+ private readonly storageCache = new LRUCache<number, MongoSyncBucketStorage>({
29
+ max: 3,
30
+ fetchMethod: async (id) => {
31
+ const doc2 = await this.db.sync_rules.findOne(
32
+ {
33
+ _id: id
34
+ },
35
+ { limit: 1 }
36
+ );
37
+ if (doc2 == null) {
38
+ // Deleted in the meantime?
39
+ return undefined;
40
+ }
41
+ const rules = new MongoPersistedSyncRulesContent(this.db, doc2);
42
+ return this.getInstance(rules);
43
+ },
44
+ dispose: (storage) => {
45
+ storage[Symbol.dispose]();
46
+ }
47
+ });
48
+
49
+ public readonly db: PowerSyncMongo;
50
+
51
+ constructor(
52
+ db: PowerSyncMongo,
53
+ options: {
54
+ slot_name_prefix: string;
55
+ }
56
+ ) {
57
+ super();
58
+ this.client = db.client;
59
+ this.db = db;
60
+ this.session = this.client.startSession();
61
+ this.slot_name_prefix = options.slot_name_prefix;
62
+ }
63
+
64
+ getInstance(options: storage.PersistedSyncRulesContent): MongoSyncBucketStorage {
65
+ let { id, slot_name } = options;
66
+ if ((typeof id as any) == 'bigint') {
67
+ id = Number(id);
68
+ }
69
+ const storage = new MongoSyncBucketStorage(this, id, options, slot_name);
70
+ this.iterateListeners((cb) => cb.syncStorageCreated?.(storage));
71
+ storage.registerListener({
72
+ batchStarted: (batch) => {
73
+ // This nested listener will be automatically disposed when the storage is disposed
74
+ batch.registerManagedListener(storage, {
75
+ replicationEvent: (payload) => this.iterateListeners((cb) => cb.replicationEvent?.(payload))
76
+ });
77
+ }
78
+ });
79
+ return storage;
80
+ }
81
+
82
+ async configureSyncRules(sync_rules: string, options?: { lock?: boolean }) {
83
+ const next = await this.getNextSyncRulesContent();
84
+ const active = await this.getActiveSyncRulesContent();
85
+
86
+ if (next?.sync_rules_content == sync_rules) {
87
+ logger.info('Sync rules from configuration unchanged');
88
+ return { updated: false };
89
+ } else if (next == null && active?.sync_rules_content == sync_rules) {
90
+ logger.info('Sync rules from configuration unchanged');
91
+ return { updated: false };
92
+ } else {
93
+ logger.info('Sync rules updated from configuration');
94
+ const persisted_sync_rules = await this.updateSyncRules({
95
+ content: sync_rules,
96
+ lock: options?.lock
97
+ });
98
+ return { updated: true, persisted_sync_rules, lock: persisted_sync_rules.current_lock ?? undefined };
99
+ }
100
+ }
101
+
102
+ async slotRemoved(slot_name: string) {
103
+ const next = await this.getNextSyncRulesContent();
104
+ const active = await this.getActiveSyncRulesContent();
105
+
106
+ // In both the below cases, we create a new sync rules instance.
107
+ // The current one will continue erroring until the next one has finished processing.
108
+ // TODO: Update
109
+ if (next != null && next.slot_name == slot_name) {
110
+ // We need to redo the "next" sync rules
111
+ await this.updateSyncRules({
112
+ content: next.sync_rules_content
113
+ });
114
+ // Pro-actively stop replicating
115
+ await this.db.sync_rules.updateOne(
116
+ {
117
+ _id: next.id,
118
+ state: storage.SyncRuleState.PROCESSING
119
+ },
120
+ {
121
+ $set: {
122
+ state: storage.SyncRuleState.STOP
123
+ }
124
+ }
125
+ );
126
+ } else if (next == null && active?.slot_name == slot_name) {
127
+ // Slot removed for "active" sync rules, while there is no "next" one.
128
+ await this.updateSyncRules({
129
+ content: active.sync_rules_content
130
+ });
131
+
132
+ // Pro-actively stop replicating
133
+ await this.db.sync_rules.updateOne(
134
+ {
135
+ _id: active.id,
136
+ state: storage.SyncRuleState.ACTIVE
137
+ },
138
+ {
139
+ $set: {
140
+ state: storage.SyncRuleState.STOP
141
+ }
142
+ }
143
+ );
144
+ }
145
+ }
146
+
147
+ async updateSyncRules(options: storage.UpdateSyncRulesOptions): Promise<MongoPersistedSyncRulesContent> {
148
+ // Parse and validate before applying any changes
149
+ const parsed = SqlSyncRules.fromYaml(options.content, {
150
+ // No schema-based validation at this point
151
+ schema: undefined,
152
+ defaultSchema: 'not_applicable', // Not needed for validation
153
+ throwOnError: true
154
+ });
155
+
156
+ let rules: MongoPersistedSyncRulesContent | undefined = undefined;
157
+
158
+ await this.session.withTransaction(async () => {
159
+ // Only have a single set of sync rules with PROCESSING.
160
+ await this.db.sync_rules.updateMany(
161
+ {
162
+ state: storage.SyncRuleState.PROCESSING
163
+ },
164
+ { $set: { state: storage.SyncRuleState.STOP } }
165
+ );
166
+
167
+ const id_doc = await this.db.op_id_sequence.findOneAndUpdate(
168
+ {
169
+ _id: 'sync_rules'
170
+ },
171
+ {
172
+ $inc: {
173
+ op_id: 1n
174
+ }
175
+ },
176
+ {
177
+ upsert: true,
178
+ returnDocument: 'after'
179
+ }
180
+ );
181
+
182
+ const id = Number(id_doc!.op_id);
183
+ const slot_name = generateSlotName(this.slot_name_prefix, id);
184
+
185
+ const doc: SyncRuleDocument = {
186
+ _id: id,
187
+ content: options.content,
188
+ last_checkpoint: null,
189
+ last_checkpoint_lsn: null,
190
+ no_checkpoint_before: null,
191
+ keepalive_op: null,
192
+ snapshot_done: false,
193
+ state: storage.SyncRuleState.PROCESSING,
194
+ slot_name: slot_name,
195
+ last_checkpoint_ts: null,
196
+ last_fatal_error: null,
197
+ last_keepalive_ts: null
198
+ };
199
+ await this.db.sync_rules.insertOne(doc);
200
+ rules = new MongoPersistedSyncRulesContent(this.db, doc);
201
+ if (options.lock) {
202
+ const lock = await rules.lock();
203
+ }
204
+ });
205
+
206
+ return rules!;
207
+ }
208
+
209
+ async getActiveSyncRulesContent(): Promise<MongoPersistedSyncRulesContent | null> {
210
+ const doc = await this.db.sync_rules.findOne(
211
+ {
212
+ state: storage.SyncRuleState.ACTIVE
213
+ },
214
+ { sort: { _id: -1 }, limit: 1 }
215
+ );
216
+ if (doc == null) {
217
+ return null;
218
+ }
219
+
220
+ return new MongoPersistedSyncRulesContent(this.db, doc);
221
+ }
222
+
223
+ async getActiveSyncRules(options: storage.ParseSyncRulesOptions): Promise<storage.PersistedSyncRules | null> {
224
+ const content = await this.getActiveSyncRulesContent();
225
+ return content?.parsed(options) ?? null;
226
+ }
227
+
228
+ async getNextSyncRulesContent(): Promise<MongoPersistedSyncRulesContent | null> {
229
+ const doc = await this.db.sync_rules.findOne(
230
+ {
231
+ state: storage.SyncRuleState.PROCESSING
232
+ },
233
+ { sort: { _id: -1 }, limit: 1 }
234
+ );
235
+ if (doc == null) {
236
+ return null;
237
+ }
238
+
239
+ return new MongoPersistedSyncRulesContent(this.db, doc);
240
+ }
241
+
242
+ async getNextSyncRules(options: storage.ParseSyncRulesOptions): Promise<storage.PersistedSyncRules | null> {
243
+ const content = await this.getNextSyncRulesContent();
244
+ return content?.parsed(options) ?? null;
245
+ }
246
+
247
+ async getReplicatingSyncRules(): Promise<storage.PersistedSyncRulesContent[]> {
248
+ const docs = await this.db.sync_rules
249
+ .find({
250
+ $or: [{ state: storage.SyncRuleState.ACTIVE }, { state: storage.SyncRuleState.PROCESSING }]
251
+ })
252
+ .toArray();
253
+
254
+ return docs.map((doc) => {
255
+ return new MongoPersistedSyncRulesContent(this.db, doc);
256
+ });
257
+ }
258
+
259
+ async getStoppedSyncRules(): Promise<storage.PersistedSyncRulesContent[]> {
260
+ const docs = await this.db.sync_rules
261
+ .find({
262
+ state: storage.SyncRuleState.STOP
263
+ })
264
+ .toArray();
265
+
266
+ return docs.map((doc) => {
267
+ return new MongoPersistedSyncRulesContent(this.db, doc);
268
+ });
269
+ }
270
+
271
+ async getActiveCheckpoint(): Promise<storage.ActiveCheckpoint> {
272
+ const doc = await this.db.sync_rules.findOne(
273
+ {
274
+ state: storage.SyncRuleState.ACTIVE
275
+ },
276
+ {
277
+ sort: { _id: -1 },
278
+ limit: 1,
279
+ projection: { _id: 1, last_checkpoint: 1, last_checkpoint_lsn: 1 }
280
+ }
281
+ );
282
+
283
+ return this.makeActiveCheckpoint(doc);
284
+ }
285
+
286
+ async getStorageMetrics(): Promise<storage.StorageMetrics> {
287
+ const ignoreNotExiting = (e: unknown) => {
288
+ if (e instanceof mongo.MongoServerError && e.codeName == 'NamespaceNotFound') {
289
+ // Collection doesn't exist - return 0
290
+ return [{ storageStats: { size: 0 } }];
291
+ } else {
292
+ return Promise.reject(e);
293
+ }
294
+ };
295
+
296
+ const active_sync_rules = await this.getActiveSyncRules({ defaultSchema: 'public' });
297
+ if (active_sync_rules == null) {
298
+ return {
299
+ operations_size_bytes: 0,
300
+ parameters_size_bytes: 0,
301
+ replication_size_bytes: 0
302
+ };
303
+ }
304
+ const operations_aggregate = await this.db.bucket_data
305
+
306
+ .aggregate([
307
+ {
308
+ $collStats: {
309
+ storageStats: {}
310
+ }
311
+ }
312
+ ])
313
+ .toArray()
314
+ .catch(ignoreNotExiting);
315
+
316
+ const parameters_aggregate = await this.db.bucket_parameters
317
+ .aggregate([
318
+ {
319
+ $collStats: {
320
+ storageStats: {}
321
+ }
322
+ }
323
+ ])
324
+ .toArray()
325
+ .catch(ignoreNotExiting);
326
+
327
+ const replication_aggregate = await this.db.current_data
328
+ .aggregate([
329
+ {
330
+ $collStats: {
331
+ storageStats: {}
332
+ }
333
+ }
334
+ ])
335
+ .toArray()
336
+ .catch(ignoreNotExiting);
337
+
338
+ return {
339
+ operations_size_bytes: Number(operations_aggregate[0].storageStats.size),
340
+ parameters_size_bytes: Number(parameters_aggregate[0].storageStats.size),
341
+ replication_size_bytes: Number(replication_aggregate[0].storageStats.size)
342
+ };
343
+ }
344
+
345
+ async getPowerSyncInstanceId(): Promise<string> {
346
+ let instance = await this.db.instance.findOne({
347
+ _id: { $exists: true }
348
+ });
349
+
350
+ if (!instance) {
351
+ const manager = new lib_mongo.locks.MongoLockManager({
352
+ collection: this.db.locks,
353
+ name: `instance-id-insertion-lock`
354
+ });
355
+
356
+ await manager.lock(async () => {
357
+ await this.db.instance.insertOne({
358
+ _id: uuid()
359
+ });
360
+ });
361
+
362
+ instance = await this.db.instance.findOne({
363
+ _id: { $exists: true }
364
+ });
365
+ }
366
+
367
+ return instance!._id;
368
+ }
369
+
370
+ private makeActiveCheckpoint(doc: SyncRuleDocument | null) {
371
+ return {
372
+ checkpoint: utils.timestampToOpId(doc?.last_checkpoint ?? 0n),
373
+ lsn: doc?.last_checkpoint_lsn ?? null,
374
+ hasSyncRules() {
375
+ return doc != null;
376
+ },
377
+ getBucketStorage: async () => {
378
+ if (doc == null) {
379
+ return null;
380
+ }
381
+ return (await this.storageCache.fetch(doc._id)) ?? null;
382
+ }
383
+ } satisfies storage.ActiveCheckpoint;
384
+ }
385
+
386
+ /**
387
+ * Instance-wide watch on the latest available checkpoint (op_id + lsn).
388
+ */
389
+ private async *watchActiveCheckpoint(signal: AbortSignal): AsyncIterable<storage.ActiveCheckpoint> {
390
+ const pipeline: mongo.Document[] = [
391
+ {
392
+ $match: {
393
+ 'fullDocument.state': 'ACTIVE',
394
+ operationType: { $in: ['insert', 'update'] }
395
+ }
396
+ },
397
+ {
398
+ $project: {
399
+ operationType: 1,
400
+ 'fullDocument._id': 1,
401
+ 'fullDocument.last_checkpoint': 1,
402
+ 'fullDocument.last_checkpoint_lsn': 1
403
+ }
404
+ }
405
+ ];
406
+
407
+ // Use this form instead of (doc: SyncRuleDocument | null = null),
408
+ // otherwise we get weird "doc: never" issues.
409
+ let doc = null as SyncRuleDocument | null;
410
+ let clusterTime = null as mongo.Timestamp | null;
411
+
412
+ await this.client.withSession(async (session) => {
413
+ doc = await this.db.sync_rules.findOne(
414
+ {
415
+ state: storage.SyncRuleState.ACTIVE
416
+ },
417
+ {
418
+ session,
419
+ sort: { _id: -1 },
420
+ limit: 1,
421
+ projection: {
422
+ _id: 1,
423
+ last_checkpoint: 1,
424
+ last_checkpoint_lsn: 1
425
+ }
426
+ }
427
+ );
428
+ const time = session.clusterTime?.clusterTime ?? null;
429
+ clusterTime = time;
430
+ });
431
+ if (clusterTime == null) {
432
+ throw new Error('Could not get clusterTime');
433
+ }
434
+
435
+ if (signal.aborted) {
436
+ return;
437
+ }
438
+
439
+ if (doc) {
440
+ yield this.makeActiveCheckpoint(doc);
441
+ }
442
+
443
+ const stream = this.db.sync_rules.watch(pipeline, {
444
+ fullDocument: 'updateLookup',
445
+ // Start at the cluster time where we got the initial doc, to make sure
446
+ // we don't skip any updates.
447
+ // This may result in the first operation being a duplicate, but we filter
448
+ // it out anyway.
449
+ startAtOperationTime: clusterTime
450
+ });
451
+
452
+ signal.addEventListener(
453
+ 'abort',
454
+ () => {
455
+ stream.close();
456
+ },
457
+ { once: true }
458
+ );
459
+
460
+ let lastOp: storage.ActiveCheckpoint | null = null;
461
+
462
+ for await (const update of stream.stream()) {
463
+ if (signal.aborted) {
464
+ break;
465
+ }
466
+ if (update.operationType != 'insert' && update.operationType != 'update') {
467
+ continue;
468
+ }
469
+ const doc = update.fullDocument!;
470
+ if (doc == null) {
471
+ continue;
472
+ }
473
+
474
+ const op = this.makeActiveCheckpoint(doc);
475
+ // Check for LSN / checkpoint changes - ignore other metadata changes
476
+ if (lastOp == null || op.lsn != lastOp.lsn || op.checkpoint != lastOp.checkpoint) {
477
+ lastOp = op;
478
+ yield op;
479
+ }
480
+ }
481
+ }
482
+
483
+ // Nothing is done here until a subscriber starts to iterate
484
+ private readonly sharedIter = new sync.BroadcastIterable((signal) => {
485
+ return this.watchActiveCheckpoint(signal);
486
+ });
487
+
488
+ /**
489
+ * User-specific watch on the latest checkpoint and/or write checkpoint.
490
+ */
491
+ async *watchWriteCheckpoint(user_id: string, signal: AbortSignal): AsyncIterable<storage.WriteCheckpoint> {
492
+ let lastCheckpoint: utils.OpId | null = null;
493
+ let lastWriteCheckpoint: bigint | null = null;
494
+
495
+ const iter = wrapWithAbort(this.sharedIter, signal);
496
+ for await (const cp of iter) {
497
+ const { checkpoint, lsn } = cp;
498
+
499
+ // lsn changes are not important by itself.
500
+ // What is important is:
501
+ // 1. checkpoint (op_id) changes.
502
+ // 2. write checkpoint changes for the specific user
503
+ const bucketStorage = await cp.getBucketStorage();
504
+ if (!bucketStorage) {
505
+ continue;
506
+ }
507
+
508
+ const lsnFilters: Record<string, string> = lsn ? { 1: lsn } : {};
509
+
510
+ const currentWriteCheckpoint = await bucketStorage.lastWriteCheckpoint({
511
+ user_id,
512
+ heads: {
513
+ ...lsnFilters
514
+ }
515
+ });
516
+
517
+ if (currentWriteCheckpoint == lastWriteCheckpoint && checkpoint == lastCheckpoint) {
518
+ // No change - wait for next one
519
+ // In some cases, many LSNs may be produced in a short time.
520
+ // Add a delay to throttle the write checkpoint lookup a bit.
521
+ await timers.setTimeout(20 + 10 * Math.random());
522
+ continue;
523
+ }
524
+
525
+ lastWriteCheckpoint = currentWriteCheckpoint;
526
+ lastCheckpoint = checkpoint;
527
+
528
+ yield { base: cp, writeCheckpoint: currentWriteCheckpoint };
529
+ }
530
+ }
531
+ }