@powersync/service-core 0.13.0 → 0.15.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 (181) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/entry/commands/compact-action.js +14 -14
  3. package/dist/entry/commands/compact-action.js.map +1 -1
  4. package/dist/entry/commands/migrate-action.js +15 -4
  5. package/dist/entry/commands/migrate-action.js.map +1 -1
  6. package/dist/index.d.ts +1 -3
  7. package/dist/index.js +1 -3
  8. package/dist/index.js.map +1 -1
  9. package/dist/migrations/PowerSyncMigrationManager.d.ts +17 -0
  10. package/dist/migrations/PowerSyncMigrationManager.js +21 -0
  11. package/dist/migrations/PowerSyncMigrationManager.js.map +1 -0
  12. package/dist/migrations/ensure-automatic-migrations.d.ts +4 -0
  13. package/dist/migrations/ensure-automatic-migrations.js +14 -0
  14. package/dist/migrations/ensure-automatic-migrations.js.map +1 -0
  15. package/dist/migrations/migrations-index.d.ts +2 -3
  16. package/dist/migrations/migrations-index.js +2 -3
  17. package/dist/migrations/migrations-index.js.map +1 -1
  18. package/dist/routes/configure-fastify.d.ts +12 -12
  19. package/dist/routes/endpoints/admin.d.ts +24 -24
  20. package/dist/storage/BucketStorage.d.ts +51 -3
  21. package/dist/storage/BucketStorage.js +26 -0
  22. package/dist/storage/BucketStorage.js.map +1 -1
  23. package/dist/storage/bson.d.ts +24 -0
  24. package/dist/storage/bson.js +73 -0
  25. package/dist/storage/bson.js.map +1 -0
  26. package/dist/storage/storage-index.d.ts +3 -14
  27. package/dist/storage/storage-index.js +3 -14
  28. package/dist/storage/storage-index.js.map +1 -1
  29. package/dist/sync/sync.js +3 -1
  30. package/dist/sync/sync.js.map +1 -1
  31. package/dist/system/ServiceContext.d.ts +3 -0
  32. package/dist/system/ServiceContext.js +11 -3
  33. package/dist/system/ServiceContext.js.map +1 -1
  34. package/dist/util/config/types.d.ts +2 -2
  35. package/dist/util/utils.d.ts +17 -1
  36. package/dist/util/utils.js +49 -1
  37. package/dist/util/utils.js.map +1 -1
  38. package/package.json +7 -8
  39. package/src/entry/commands/compact-action.ts +19 -14
  40. package/src/entry/commands/migrate-action.ts +17 -4
  41. package/src/index.ts +1 -4
  42. package/src/migrations/PowerSyncMigrationManager.ts +42 -0
  43. package/src/migrations/ensure-automatic-migrations.ts +15 -0
  44. package/src/migrations/migrations-index.ts +2 -3
  45. package/src/storage/BucketStorage.ts +59 -3
  46. package/src/storage/bson.ts +78 -0
  47. package/src/storage/storage-index.ts +3 -15
  48. package/src/sync/sync.ts +3 -1
  49. package/src/system/ServiceContext.ts +17 -4
  50. package/src/util/config/types.ts +2 -2
  51. package/src/util/utils.ts +47 -1
  52. package/test/src/env.ts +0 -1
  53. package/tsconfig.tsbuildinfo +1 -1
  54. package/dist/db/db-index.d.ts +0 -1
  55. package/dist/db/db-index.js +0 -2
  56. package/dist/db/db-index.js.map +0 -1
  57. package/dist/db/mongo.d.ts +0 -35
  58. package/dist/db/mongo.js +0 -73
  59. package/dist/db/mongo.js.map +0 -1
  60. package/dist/locks/LockManager.d.ts +0 -10
  61. package/dist/locks/LockManager.js +0 -7
  62. package/dist/locks/LockManager.js.map +0 -1
  63. package/dist/locks/MongoLocks.d.ts +0 -36
  64. package/dist/locks/MongoLocks.js +0 -81
  65. package/dist/locks/MongoLocks.js.map +0 -1
  66. package/dist/locks/locks-index.d.ts +0 -2
  67. package/dist/locks/locks-index.js +0 -3
  68. package/dist/locks/locks-index.js.map +0 -1
  69. package/dist/migrations/db/migrations/1684951997326-init.d.ts +0 -3
  70. package/dist/migrations/db/migrations/1684951997326-init.js +0 -33
  71. package/dist/migrations/db/migrations/1684951997326-init.js.map +0 -1
  72. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.d.ts +0 -2
  73. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.js +0 -5
  74. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.js.map +0 -1
  75. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.d.ts +0 -3
  76. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js +0 -56
  77. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js.map +0 -1
  78. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.d.ts +0 -3
  79. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js +0 -29
  80. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js.map +0 -1
  81. package/dist/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.d.ts +0 -3
  82. package/dist/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.js +0 -31
  83. package/dist/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.js.map +0 -1
  84. package/dist/migrations/definitions.d.ts +0 -18
  85. package/dist/migrations/definitions.js +0 -6
  86. package/dist/migrations/definitions.js.map +0 -1
  87. package/dist/migrations/executor.d.ts +0 -16
  88. package/dist/migrations/executor.js +0 -64
  89. package/dist/migrations/executor.js.map +0 -1
  90. package/dist/migrations/migrations.d.ts +0 -18
  91. package/dist/migrations/migrations.js +0 -110
  92. package/dist/migrations/migrations.js.map +0 -1
  93. package/dist/migrations/store/migration-store.d.ts +0 -11
  94. package/dist/migrations/store/migration-store.js +0 -46
  95. package/dist/migrations/store/migration-store.js.map +0 -1
  96. package/dist/storage/MongoBucketStorage.d.ts +0 -48
  97. package/dist/storage/MongoBucketStorage.js +0 -427
  98. package/dist/storage/MongoBucketStorage.js.map +0 -1
  99. package/dist/storage/mongo/MongoBucketBatch.d.ts +0 -74
  100. package/dist/storage/mongo/MongoBucketBatch.js +0 -683
  101. package/dist/storage/mongo/MongoBucketBatch.js.map +0 -1
  102. package/dist/storage/mongo/MongoCompactor.d.ts +0 -40
  103. package/dist/storage/mongo/MongoCompactor.js +0 -310
  104. package/dist/storage/mongo/MongoCompactor.js.map +0 -1
  105. package/dist/storage/mongo/MongoIdSequence.d.ts +0 -12
  106. package/dist/storage/mongo/MongoIdSequence.js +0 -21
  107. package/dist/storage/mongo/MongoIdSequence.js.map +0 -1
  108. package/dist/storage/mongo/MongoPersistedSyncRules.d.ts +0 -9
  109. package/dist/storage/mongo/MongoPersistedSyncRules.js +0 -9
  110. package/dist/storage/mongo/MongoPersistedSyncRules.js.map +0 -1
  111. package/dist/storage/mongo/MongoPersistedSyncRulesContent.d.ts +0 -20
  112. package/dist/storage/mongo/MongoPersistedSyncRulesContent.js +0 -26
  113. package/dist/storage/mongo/MongoPersistedSyncRulesContent.js.map +0 -1
  114. package/dist/storage/mongo/MongoStorageProvider.d.ts +0 -5
  115. package/dist/storage/mongo/MongoStorageProvider.js +0 -26
  116. package/dist/storage/mongo/MongoStorageProvider.js.map +0 -1
  117. package/dist/storage/mongo/MongoSyncBucketStorage.d.ts +0 -38
  118. package/dist/storage/mongo/MongoSyncBucketStorage.js +0 -534
  119. package/dist/storage/mongo/MongoSyncBucketStorage.js.map +0 -1
  120. package/dist/storage/mongo/MongoSyncRulesLock.d.ts +0 -16
  121. package/dist/storage/mongo/MongoSyncRulesLock.js +0 -65
  122. package/dist/storage/mongo/MongoSyncRulesLock.js.map +0 -1
  123. package/dist/storage/mongo/MongoWriteCheckpointAPI.d.ts +0 -20
  124. package/dist/storage/mongo/MongoWriteCheckpointAPI.js +0 -104
  125. package/dist/storage/mongo/MongoWriteCheckpointAPI.js.map +0 -1
  126. package/dist/storage/mongo/OperationBatch.d.ts +0 -35
  127. package/dist/storage/mongo/OperationBatch.js +0 -119
  128. package/dist/storage/mongo/OperationBatch.js.map +0 -1
  129. package/dist/storage/mongo/PersistedBatch.d.ts +0 -46
  130. package/dist/storage/mongo/PersistedBatch.js +0 -223
  131. package/dist/storage/mongo/PersistedBatch.js.map +0 -1
  132. package/dist/storage/mongo/config.d.ts +0 -19
  133. package/dist/storage/mongo/config.js +0 -26
  134. package/dist/storage/mongo/config.js.map +0 -1
  135. package/dist/storage/mongo/db.d.ts +0 -36
  136. package/dist/storage/mongo/db.js +0 -47
  137. package/dist/storage/mongo/db.js.map +0 -1
  138. package/dist/storage/mongo/models.d.ts +0 -163
  139. package/dist/storage/mongo/models.js +0 -27
  140. package/dist/storage/mongo/models.js.map +0 -1
  141. package/dist/storage/mongo/util.d.ts +0 -54
  142. package/dist/storage/mongo/util.js +0 -190
  143. package/dist/storage/mongo/util.js.map +0 -1
  144. package/src/db/db-index.ts +0 -1
  145. package/src/db/mongo.ts +0 -81
  146. package/src/locks/LockManager.ts +0 -16
  147. package/src/locks/MongoLocks.ts +0 -142
  148. package/src/locks/locks-index.ts +0 -2
  149. package/src/migrations/db/migrations/1684951997326-init.ts +0 -38
  150. package/src/migrations/db/migrations/1688556755264-initial-sync-rules.ts +0 -5
  151. package/src/migrations/db/migrations/1702295701188-sync-rule-state.ts +0 -102
  152. package/src/migrations/db/migrations/1711543888062-write-checkpoint-index.ts +0 -34
  153. package/src/migrations/db/migrations/1727099539247-custom-write-checkpoint-index.ts +0 -37
  154. package/src/migrations/definitions.ts +0 -21
  155. package/src/migrations/executor.ts +0 -87
  156. package/src/migrations/migrations.ts +0 -142
  157. package/src/migrations/store/migration-store.ts +0 -63
  158. package/src/storage/MongoBucketStorage.ts +0 -541
  159. package/src/storage/mongo/MongoBucketBatch.ts +0 -900
  160. package/src/storage/mongo/MongoCompactor.ts +0 -393
  161. package/src/storage/mongo/MongoIdSequence.ts +0 -24
  162. package/src/storage/mongo/MongoPersistedSyncRules.ts +0 -16
  163. package/src/storage/mongo/MongoPersistedSyncRulesContent.ts +0 -50
  164. package/src/storage/mongo/MongoStorageProvider.ts +0 -31
  165. package/src/storage/mongo/MongoSyncBucketStorage.ts +0 -640
  166. package/src/storage/mongo/MongoSyncRulesLock.ts +0 -85
  167. package/src/storage/mongo/MongoWriteCheckpointAPI.ts +0 -154
  168. package/src/storage/mongo/OperationBatch.ts +0 -131
  169. package/src/storage/mongo/PersistedBatch.ts +0 -285
  170. package/src/storage/mongo/config.ts +0 -40
  171. package/src/storage/mongo/db.ts +0 -88
  172. package/src/storage/mongo/models.ts +0 -187
  173. package/src/storage/mongo/util.ts +0 -203
  174. package/test/src/__snapshots__/sync.test.ts.snap +0 -332
  175. package/test/src/bucket_validation.test.ts +0 -143
  176. package/test/src/bucket_validation.ts +0 -60
  177. package/test/src/compacting.test.ts +0 -295
  178. package/test/src/data_storage.test.ts +0 -1569
  179. package/test/src/stream_utils.ts +0 -42
  180. package/test/src/sync.test.ts +0 -511
  181. package/test/src/util.ts +0 -150
@@ -1,88 +0,0 @@
1
- import * as mongo from 'mongodb';
2
-
3
- import { configFile } from '@powersync/service-types';
4
- import * as db from '../../db/db-index.js';
5
- import * as locks from '../../locks/locks-index.js';
6
- import {
7
- BucketDataDocument,
8
- BucketParameterDocument,
9
- CurrentDataDocument,
10
- CustomWriteCheckpointDocument,
11
- IdSequenceDocument,
12
- InstanceDocument,
13
- SourceTableDocument,
14
- SyncRuleDocument,
15
- WriteCheckpointDocument
16
- } from './models.js';
17
- import { BSON_DESERIALIZE_OPTIONS } from './util.js';
18
-
19
- export interface PowerSyncMongoOptions {
20
- /**
21
- * Optional - uses the database from the MongoClient connection URI if not specified.
22
- */
23
- database?: string;
24
- }
25
-
26
- export function createPowerSyncMongo(config: configFile.PowerSyncConfig['storage']) {
27
- return new PowerSyncMongo(db.mongo.createMongoClient(config), { database: config.database });
28
- }
29
-
30
- export class PowerSyncMongo {
31
- readonly current_data: mongo.Collection<CurrentDataDocument>;
32
- readonly bucket_data: mongo.Collection<BucketDataDocument>;
33
- readonly bucket_parameters: mongo.Collection<BucketParameterDocument>;
34
- readonly op_id_sequence: mongo.Collection<IdSequenceDocument>;
35
- readonly sync_rules: mongo.Collection<SyncRuleDocument>;
36
- readonly source_tables: mongo.Collection<SourceTableDocument>;
37
- readonly custom_write_checkpoints: mongo.Collection<CustomWriteCheckpointDocument>;
38
- readonly write_checkpoints: mongo.Collection<WriteCheckpointDocument>;
39
- readonly instance: mongo.Collection<InstanceDocument>;
40
- readonly locks: mongo.Collection<locks.Lock>;
41
-
42
- readonly client: mongo.MongoClient;
43
- readonly db: mongo.Db;
44
-
45
- constructor(client: mongo.MongoClient, options?: PowerSyncMongoOptions) {
46
- this.client = client;
47
-
48
- const db = client.db(options?.database, {
49
- ...BSON_DESERIALIZE_OPTIONS
50
- });
51
- this.db = db;
52
-
53
- this.current_data = db.collection<CurrentDataDocument>('current_data');
54
- this.bucket_data = db.collection('bucket_data');
55
- this.bucket_parameters = db.collection('bucket_parameters');
56
- this.op_id_sequence = db.collection('op_id_sequence');
57
- this.sync_rules = db.collection('sync_rules');
58
- this.source_tables = db.collection('source_tables');
59
- this.custom_write_checkpoints = db.collection('custom_write_checkpoints');
60
- this.write_checkpoints = db.collection('write_checkpoints');
61
- this.instance = db.collection('instance');
62
- this.locks = this.db.collection('locks');
63
- }
64
-
65
- /**
66
- * Clear all collections.
67
- */
68
- async clear() {
69
- await this.current_data.deleteMany({});
70
- await this.bucket_data.deleteMany({});
71
- await this.bucket_parameters.deleteMany({});
72
- await this.op_id_sequence.deleteMany({});
73
- await this.sync_rules.deleteMany({});
74
- await this.source_tables.deleteMany({});
75
- await this.write_checkpoints.deleteMany({});
76
- await this.instance.deleteOne({});
77
- await this.locks.deleteMany({});
78
- }
79
-
80
- /**
81
- * Drop the entire database.
82
- *
83
- * Primarily for tests.
84
- */
85
- async drop() {
86
- await this.db.dropDatabase();
87
- }
88
- }
@@ -1,187 +0,0 @@
1
- import { SqliteJsonValue } from '@powersync/service-sync-rules';
2
- import * as bson from 'bson';
3
-
4
- /**
5
- * Replica id uniquely identifying a row on the source database.
6
- *
7
- * Can be any value serializable to BSON.
8
- *
9
- * If the value is an entire document, the data serialized to a v5 UUID may be a good choice here.
10
- */
11
- export type ReplicaId = bson.UUID | bson.Document | any;
12
-
13
- export interface SourceKey {
14
- /** group_id */
15
- g: number;
16
- /** source table id */
17
- t: bson.ObjectId;
18
- /** source key */
19
- k: ReplicaId;
20
- }
21
-
22
- export interface BucketDataKey {
23
- /** group_id */
24
- g: number;
25
- /** bucket name */
26
- b: string;
27
- /** op_id */
28
- o: bigint;
29
- }
30
-
31
- export interface CurrentDataDocument {
32
- _id: SourceKey;
33
- data: bson.Binary;
34
- buckets: CurrentBucket[];
35
- lookups: bson.Binary[];
36
- }
37
-
38
- export interface CurrentBucket {
39
- bucket: string;
40
- table: string;
41
- id: string;
42
- }
43
-
44
- export interface BucketParameterDocument {
45
- _id: bigint;
46
- key: SourceKey;
47
- lookup: bson.Binary;
48
- bucket_parameters: Record<string, SqliteJsonValue>[];
49
- }
50
-
51
- export interface BucketDataDocument {
52
- _id: BucketDataKey;
53
- op: OpType;
54
- source_table?: bson.ObjectId;
55
- source_key?: ReplicaId;
56
- table?: string;
57
- row_id?: string;
58
- checksum: number;
59
- data: string | null;
60
- target_op?: bigint | null;
61
- }
62
-
63
- export type OpType = 'PUT' | 'REMOVE' | 'MOVE' | 'CLEAR';
64
-
65
- export interface SourceTableDocument {
66
- _id: bson.ObjectId;
67
- group_id: number;
68
- connection_id: number;
69
- relation_id: number | string | undefined;
70
- schema_name: string;
71
- table_name: string;
72
- replica_id_columns: string[] | null;
73
- replica_id_columns2: { name: string; type_oid?: number; type?: string }[] | undefined;
74
- snapshot_done: boolean | undefined;
75
- }
76
-
77
- export interface IdSequenceDocument {
78
- _id: string;
79
- op_id: bigint;
80
- }
81
-
82
- export enum SyncRuleState {
83
- /**
84
- * New sync rules - needs to be processed (initial replication).
85
- *
86
- * While multiple sets of sync rules _can_ be in PROCESSING,
87
- * it's generally pointless, so we only keep one in that state.
88
- */
89
- PROCESSING = 'PROCESSING',
90
-
91
- /**
92
- * Sync rule processing is done, and can be used for sync.
93
- *
94
- * Only one set of sync rules should be in ACTIVE state.
95
- */
96
- ACTIVE = 'ACTIVE',
97
- /**
98
- * This state is used when the sync rules has been replaced,
99
- * and replication is or should be stopped.
100
- */
101
- STOP = 'STOP',
102
- /**
103
- * After sync rules have been stopped, the data needs to be
104
- * deleted. Once deleted, the state is TERMINATED.
105
- */
106
- TERMINATED = 'TERMINATED'
107
- }
108
-
109
- export interface SyncRuleDocument {
110
- _id: number;
111
-
112
- state: SyncRuleState;
113
-
114
- /**
115
- * True if initial snapshot has been replicated.
116
- *
117
- * Can only be false if state == PROCESSING.
118
- */
119
- snapshot_done: boolean;
120
-
121
- /**
122
- * The last consistent checkpoint.
123
- *
124
- * There may be higher OpIds used in the database if we're in the middle of replicating a large transaction.
125
- */
126
- last_checkpoint: bigint | null;
127
-
128
- /**
129
- * The LSN associated with the last consistent checkpoint.
130
- */
131
- last_checkpoint_lsn: string | null;
132
-
133
- /**
134
- * If set, no new checkpoints may be created < this value.
135
- */
136
- no_checkpoint_before: string | null;
137
-
138
- /**
139
- * Goes together with no_checkpoint_before.
140
- *
141
- * If a keepalive is triggered that creates the checkpoint > no_checkpoint_before,
142
- * then the checkpoint must be equal to this keepalive_op.
143
- */
144
- keepalive_op: string | null;
145
-
146
- slot_name: string | null;
147
-
148
- /**
149
- * Last time we persisted a checkpoint.
150
- *
151
- * This may be old if no data is incoming.
152
- */
153
- last_checkpoint_ts: Date | null;
154
-
155
- /**
156
- * Last time we persisted a checkpoint or keepalive.
157
- *
158
- * This should stay fairly current while replicating.
159
- */
160
- last_keepalive_ts: Date | null;
161
-
162
- /**
163
- * If an error is stopping replication, it will be stored here.
164
- */
165
- last_fatal_error: string | null;
166
-
167
- content: string;
168
- }
169
-
170
- export interface CustomWriteCheckpointDocument {
171
- _id: bson.ObjectId;
172
- user_id: string;
173
- checkpoint: bigint;
174
- sync_rules_id: number;
175
- }
176
-
177
- export interface WriteCheckpointDocument {
178
- _id: bson.ObjectId;
179
- user_id: string;
180
- lsns: Record<string, string>;
181
- client_id: bigint;
182
- }
183
-
184
- export interface InstanceDocument {
185
- // The instance UUID
186
- _id: string;
187
- }
@@ -1,203 +0,0 @@
1
- import { SqliteJsonValue } from '@powersync/service-sync-rules';
2
- import * as bson from 'bson';
3
- import * as crypto from 'crypto';
4
- import * as mongo from 'mongodb';
5
- import * as uuid from 'uuid';
6
- import { OplogEntry } from '../../util/protocol-types.js';
7
- import { ID_NAMESPACE, timestampToOpId } from '../../util/utils.js';
8
- import { BucketDataDocument, ReplicaId } from './models.js';
9
-
10
- /**
11
- * Lookup serialization must be number-agnostic. I.e. normalize numbers, instead of preserving numbers.
12
- * @param lookup
13
- */
14
-
15
- export function serializeLookup(lookup: SqliteJsonValue[]) {
16
- const normalized = lookup.map((value) => {
17
- if (typeof value == 'number' && Number.isInteger(value)) {
18
- return BigInt(value);
19
- } else {
20
- return value;
21
- }
22
- });
23
- return new bson.Binary(bson.serialize({ l: normalized }));
24
- }
25
-
26
- export function idPrefixFilter<T>(prefix: Partial<T>, rest: (keyof T)[]): mongo.Condition<T> {
27
- let filter = {
28
- $gte: {
29
- ...prefix
30
- } as any,
31
- $lt: {
32
- ...prefix
33
- } as any
34
- };
35
-
36
- for (let key of rest) {
37
- filter.$gte[key] = new bson.MinKey();
38
- filter.$lt[key] = new bson.MaxKey();
39
- }
40
-
41
- return filter;
42
- }
43
-
44
- export function generateSlotName(prefix: string, sync_rules_id: number) {
45
- const slot_suffix = crypto.randomBytes(2).toString('hex');
46
- return `${prefix}${sync_rules_id}_${slot_suffix}`;
47
- }
48
-
49
- /**
50
- * Read a single batch of data from a cursor, then close it.
51
- *
52
- * We do our best to avoid MongoDB fetching any more data than this single batch.
53
- *
54
- * This is similar to using `singleBatch: true` in find options.
55
- * However, that makes `has_more` detection very difficult, since the cursor is always closed
56
- * after the first batch. Instead, we do a workaround to only fetch a single batch below.
57
- *
58
- * For this to be effective, set batchSize = limit in the find command.
59
- */
60
- export async function readSingleBatch<T>(cursor: mongo.FindCursor<T>): Promise<{ data: T[]; hasMore: boolean }> {
61
- try {
62
- let data: T[];
63
- let hasMore = true;
64
- // Let MongoDB load the first batch of data
65
- const hasAny = await cursor.hasNext();
66
- // Now it's in memory, and we can read it
67
- data = cursor.readBufferedDocuments();
68
- if (!hasAny || cursor.id?.isZero()) {
69
- // A zero id means the cursor is exhaused.
70
- // No results (hasAny == false) means even this batch doesn't have data.
71
- // This should similar results as `await cursor.hasNext()`, but without
72
- // actually fetching the next batch.
73
- //
74
- // Note that it is safe (but slightly inefficient) to return `hasMore: true`
75
- // without there being more data, as long as the next batch
76
- // will return `hasMore: false`.
77
- hasMore = false;
78
- }
79
- return { data, hasMore };
80
- } finally {
81
- // Match the from the cursor iterator logic here:
82
- // https://github.com/mongodb/node-mongodb-native/blob/e02534e7d1c627bf50b85ca39f5995dbf165ad44/src/cursor/abstract_cursor.ts#L327-L331
83
- if (!cursor.closed) {
84
- await cursor.close();
85
- }
86
- }
87
- }
88
-
89
- export const BSON_DESERIALIZE_OPTIONS: bson.DeserializeOptions = {
90
- // use bigint instead of Long
91
- useBigInt64: true
92
- };
93
-
94
- export function mapOpEntry(row: BucketDataDocument): OplogEntry {
95
- if (row.op == 'PUT' || row.op == 'REMOVE') {
96
- return {
97
- op_id: timestampToOpId(row._id.o),
98
- op: row.op,
99
- object_type: row.table,
100
- object_id: row.row_id,
101
- checksum: Number(row.checksum),
102
- subkey: replicaIdToSubkey(row.source_table!, row.source_key!),
103
- data: row.data
104
- };
105
- } else {
106
- // MOVE, CLEAR
107
-
108
- return {
109
- op_id: timestampToOpId(row._id.o),
110
- op: row.op,
111
- checksum: Number(row.checksum)
112
- };
113
- }
114
- }
115
-
116
- /**
117
- * Returns true if two ReplicaId values are the same (serializes to the same BSON value).
118
- */
119
- export function replicaIdEquals(a: ReplicaId, b: ReplicaId) {
120
- if (a === b) {
121
- return true;
122
- } else if (typeof a == 'string' && typeof b == 'string') {
123
- return a == b;
124
- } else if (isUUID(a) && isUUID(b)) {
125
- return a.equals(b);
126
- } else if (a == null && b == null) {
127
- return true;
128
- } else if (a != null || b != null) {
129
- return false;
130
- } else {
131
- // There are many possible primitive values, this covers them all
132
- return (bson.serialize({ id: a }) as Buffer).equals(bson.serialize({ id: b }));
133
- }
134
- }
135
-
136
- export function replicaIdToSubkey(table: bson.ObjectId, id: ReplicaId): string {
137
- if (isUUID(id)) {
138
- // Special case for UUID for backwards-compatiblity
139
- return `${table.toHexString()}/${id.toHexString()}`;
140
- } else {
141
- // Hashed UUID from the table and id
142
- const repr = bson.serialize({ table, id });
143
- return uuid.v5(repr, ID_NAMESPACE);
144
- }
145
- }
146
-
147
- /**
148
- * True if this is a bson.UUID.
149
- *
150
- * Works even with multiple copies of the bson package.
151
- */
152
- export function isUUID(value: any): value is bson.UUID {
153
- if (value == null || typeof value != 'object') {
154
- return false;
155
- }
156
- const uuid = value as bson.UUID;
157
- return uuid._bsontype == 'Binary' && uuid.sub_type == bson.Binary.SUBTYPE_UUID;
158
- }
159
-
160
- /**
161
- * MongoDB bulkWrite internally splits the operations into batches
162
- * so that no batch exceeds 16MB. However, there are cases where
163
- * the batch size is very close to 16MB, where additional metadata
164
- * on the server pushes it over the limit, resulting in this error
165
- * from the server:
166
- *
167
- * > MongoBulkWriteError: BSONObj size: 16814023 (0x1008FC7) is invalid. Size must be between 0 and 16793600(16MB) First element: insert: "bucket_data"
168
- *
169
- * We work around the issue by doing our own batching, limiting the
170
- * batch size to 15MB. This does add additional overhead with
171
- * BSON.calculateObjectSize.
172
- */
173
- export async function safeBulkWrite<T extends mongo.Document>(
174
- collection: mongo.Collection<T>,
175
- operations: mongo.AnyBulkWriteOperation<T>[],
176
- options: mongo.BulkWriteOptions
177
- ) {
178
- // Must be below 16MB.
179
- // We could probably go a little closer, but 15MB is a safe threshold.
180
- const BULK_WRITE_LIMIT = 15 * 1024 * 1024;
181
-
182
- let batch: mongo.AnyBulkWriteOperation<T>[] = [];
183
- let currentSize = 0;
184
- // Estimated overhead per operation, should be smaller in reality.
185
- const keySize = 8;
186
- for (let op of operations) {
187
- const bsonSize =
188
- mongo.BSON.calculateObjectSize(op, {
189
- checkKeys: false,
190
- ignoreUndefined: true
191
- } as any) + keySize;
192
- if (batch.length > 0 && currentSize + bsonSize > BULK_WRITE_LIMIT) {
193
- await collection.bulkWrite(batch, options);
194
- currentSize = 0;
195
- batch = [];
196
- }
197
- batch.push(op);
198
- currentSize += bsonSize;
199
- }
200
- if (batch.length > 0) {
201
- await collection.bulkWrite(batch, options);
202
- }
203
- }