@powersync/service-module-mongodb-storage 0.17.0 → 0.18.1

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 (185) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/storage/MongoBucketStorage.d.ts +34 -16
  3. package/dist/storage/MongoBucketStorage.js +219 -70
  4. package/dist/storage/MongoBucketStorage.js.map +1 -1
  5. package/dist/storage/implementation/MongoBucketBatch.d.ts +42 -23
  6. package/dist/storage/implementation/MongoBucketBatch.js +61 -44
  7. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  8. package/dist/storage/implementation/MongoChecksums.d.ts +10 -9
  9. package/dist/storage/implementation/MongoChecksums.js +3 -111
  10. package/dist/storage/implementation/MongoChecksums.js.map +1 -1
  11. package/dist/storage/implementation/MongoCompactor.d.ts +2 -0
  12. package/dist/storage/implementation/MongoCompactor.js +18 -9
  13. package/dist/storage/implementation/MongoCompactor.js.map +1 -1
  14. package/dist/storage/implementation/MongoHydrationState.d.ts +11 -0
  15. package/dist/storage/implementation/MongoHydrationState.js +49 -0
  16. package/dist/storage/implementation/MongoHydrationState.js.map +1 -0
  17. package/dist/storage/implementation/MongoParameterCompactor.d.ts +6 -5
  18. package/dist/storage/implementation/MongoParameterCompactor.js +24 -1
  19. package/dist/storage/implementation/MongoParameterCompactor.js.map +1 -1
  20. package/dist/storage/implementation/MongoParsedSyncConfigSet.d.ts +13 -0
  21. package/dist/storage/implementation/MongoParsedSyncConfigSet.js +64 -0
  22. package/dist/storage/implementation/MongoParsedSyncConfigSet.js.map +1 -0
  23. package/dist/storage/implementation/MongoPersistedReplicationStream.d.ts +36 -0
  24. package/dist/storage/implementation/MongoPersistedReplicationStream.js +90 -0
  25. package/dist/storage/implementation/MongoPersistedReplicationStream.js.map +1 -0
  26. package/dist/storage/implementation/MongoPersistedSyncConfigContent.d.ts +25 -0
  27. package/dist/storage/implementation/MongoPersistedSyncConfigContent.js +123 -0
  28. package/dist/storage/implementation/MongoPersistedSyncConfigContent.js.map +1 -0
  29. package/dist/storage/implementation/MongoStorageProvider.js +5 -2
  30. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  31. package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +41 -23
  32. package/dist/storage/implementation/MongoSyncBucketStorage.js +51 -43
  33. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  34. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +1 -1
  35. package/dist/storage/implementation/MongoSyncRulesLock.js +3 -3
  36. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  37. package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.d.ts +6 -0
  38. package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.js +2 -0
  39. package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.js.map +1 -0
  40. package/dist/storage/implementation/common/PersistedBatch.d.ts +1 -2
  41. package/dist/storage/implementation/common/PersistedBatch.js +5 -0
  42. package/dist/storage/implementation/common/PersistedBatch.js.map +1 -1
  43. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js +1 -1
  44. package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js.map +1 -1
  45. package/dist/storage/implementation/createMongoSyncBucketStorage.d.ts +2 -2
  46. package/dist/storage/implementation/createMongoSyncBucketStorage.js +4 -4
  47. package/dist/storage/implementation/createMongoSyncBucketStorage.js.map +1 -1
  48. package/dist/storage/implementation/db.js +9 -14
  49. package/dist/storage/implementation/db.js.map +1 -1
  50. package/dist/storage/implementation/models.d.ts +4 -13
  51. package/dist/storage/implementation/models.js.map +1 -1
  52. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +9 -1
  53. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +42 -26
  54. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  55. package/dist/storage/implementation/v1/MongoChecksumsV1.js +114 -3
  56. package/dist/storage/implementation/v1/MongoChecksumsV1.js.map +1 -1
  57. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.d.ts +15 -17
  58. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js +47 -45
  59. package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js.map +1 -1
  60. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.d.ts +2 -1
  61. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js +3 -0
  62. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js.map +1 -1
  63. package/dist/storage/implementation/v1/models.d.ts +10 -1
  64. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +8 -4
  65. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +286 -259
  66. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  67. package/dist/storage/implementation/v3/MongoChecksumsV3.d.ts +27 -7
  68. package/dist/storage/implementation/v3/MongoChecksumsV3.js +202 -18
  69. package/dist/storage/implementation/v3/MongoChecksumsV3.js.map +1 -1
  70. package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +19 -2
  71. package/dist/storage/implementation/v3/MongoCompactorV3.js +511 -22
  72. package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
  73. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.d.ts +62 -0
  74. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js +350 -0
  75. package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js.map +1 -0
  76. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.d.ts +40 -28
  77. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js +232 -116
  78. package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js.map +1 -1
  79. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +1 -1
  80. package/dist/storage/implementation/v3/PersistedBatchV3.js +43 -20
  81. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  82. package/dist/storage/implementation/v3/SingleBucketStoreV3.js +52 -16
  83. package/dist/storage/implementation/v3/SingleBucketStoreV3.js.map +1 -1
  84. package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +3 -3
  85. package/dist/storage/implementation/v3/SourceRecordStoreV3.js +13 -11
  86. package/dist/storage/implementation/v3/SourceRecordStoreV3.js.map +1 -1
  87. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.d.ts +13 -12
  88. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js +29 -27
  89. package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js.map +1 -1
  90. package/dist/storage/implementation/v3/bucket-format.d.ts +4 -0
  91. package/dist/storage/implementation/v3/bucket-format.js +58 -0
  92. package/dist/storage/implementation/v3/bucket-format.js.map +1 -0
  93. package/dist/storage/implementation/v3/chunking.d.ts +10 -0
  94. package/dist/storage/implementation/v3/chunking.js +28 -0
  95. package/dist/storage/implementation/v3/chunking.js.map +1 -0
  96. package/dist/storage/implementation/v3/models.d.ts +64 -21
  97. package/dist/storage/implementation/v3/models.js +11 -28
  98. package/dist/storage/implementation/v3/models.js.map +1 -1
  99. package/dist/storage/implementation/v3/source-table-utils.d.ts +55 -0
  100. package/dist/storage/implementation/v3/source-table-utils.js +214 -0
  101. package/dist/storage/implementation/v3/source-table-utils.js.map +1 -0
  102. package/dist/storage/storage-index.d.ts +4 -4
  103. package/dist/storage/storage-index.js +4 -4
  104. package/dist/storage/storage-index.js.map +1 -1
  105. package/dist/types/types.d.ts +2 -2
  106. package/dist/utils/test-utils.d.ts +1 -2
  107. package/dist/utils/test-utils.js +5 -1
  108. package/dist/utils/test-utils.js.map +1 -1
  109. package/dist/utils/util.d.ts +1 -1
  110. package/dist/utils/util.js +3 -2
  111. package/dist/utils/util.js.map +1 -1
  112. package/package.json +9 -19
  113. package/src/storage/MongoBucketStorage.ts +334 -87
  114. package/src/storage/implementation/MongoBucketBatch.ts +86 -58
  115. package/src/storage/implementation/MongoChecksums.ts +6 -138
  116. package/src/storage/implementation/MongoCompactor.ts +19 -9
  117. package/src/storage/implementation/MongoHydrationState.ts +61 -0
  118. package/src/storage/implementation/MongoParameterCompactor.ts +24 -5
  119. package/src/storage/implementation/MongoParsedSyncConfigSet.ts +88 -0
  120. package/src/storage/implementation/MongoPersistedReplicationStream.ts +118 -0
  121. package/src/storage/implementation/MongoPersistedSyncConfigContent.ts +154 -0
  122. package/src/storage/implementation/MongoStorageProvider.ts +5 -2
  123. package/src/storage/implementation/MongoSyncBucketStorage.ts +70 -56
  124. package/src/storage/implementation/MongoSyncRulesLock.ts +7 -4
  125. package/src/storage/implementation/common/MongoSyncBucketStorageCheckpoint.ts +7 -0
  126. package/src/storage/implementation/common/PersistedBatch.ts +7 -3
  127. package/src/storage/implementation/common/VersionedPowerSyncMongoBase.ts +1 -1
  128. package/src/storage/implementation/createMongoSyncBucketStorage.ts +21 -7
  129. package/src/storage/implementation/db.ts +11 -19
  130. package/src/storage/implementation/models.ts +4 -14
  131. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +55 -34
  132. package/src/storage/implementation/v1/MongoChecksumsV1.ts +137 -4
  133. package/src/storage/implementation/v1/MongoSyncBucketStorageV1.ts +70 -64
  134. package/src/storage/implementation/v1/VersionedPowerSyncMongoV1.ts +11 -1
  135. package/src/storage/implementation/v1/models.ts +11 -1
  136. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +358 -314
  137. package/src/storage/implementation/v3/MongoChecksumsV3.ts +262 -26
  138. package/src/storage/implementation/v3/MongoCompactorV3.ts +646 -29
  139. package/src/storage/implementation/v3/MongoStoppedSyncConfigCleanup.ts +480 -0
  140. package/src/storage/implementation/v3/MongoSyncBucketStorageV3.ts +315 -157
  141. package/src/storage/implementation/v3/PersistedBatchV3.ts +62 -36
  142. package/src/storage/implementation/v3/SingleBucketStoreV3.ts +59 -19
  143. package/src/storage/implementation/v3/SourceRecordStoreV3.ts +12 -12
  144. package/src/storage/implementation/v3/VersionedPowerSyncMongoV3.ts +41 -36
  145. package/src/storage/implementation/v3/bucket-format.ts +70 -0
  146. package/src/storage/implementation/v3/chunking.ts +38 -0
  147. package/src/storage/implementation/v3/models.ts +93 -55
  148. package/src/storage/implementation/v3/source-table-utils.ts +392 -0
  149. package/src/storage/storage-index.ts +12 -4
  150. package/src/utils/test-utils.ts +6 -3
  151. package/src/utils/util.ts +3 -2
  152. package/test/src/__snapshots__/storage.test.ts.snap +0 -75
  153. package/test/src/__snapshots__/storage_sync.test.ts.snap +48 -48
  154. package/test/src/cleanup-stopped-sync-configs.test.ts +648 -0
  155. package/test/src/storage.test.ts +11 -11
  156. package/test/src/storage_compacting.test.ts +1956 -6
  157. package/test/src/storage_sync.test.ts +1077 -68
  158. package/test/src/storeCurrentData.test.ts +17 -7
  159. package/test/src/util.ts +2 -1
  160. package/tsconfig.json +1 -4
  161. package/tsconfig.tsbuildinfo +1 -1
  162. package/dist/storage/implementation/BucketDefinitionMapping.d.ts +0 -15
  163. package/dist/storage/implementation/BucketDefinitionMapping.js +0 -58
  164. package/dist/storage/implementation/BucketDefinitionMapping.js.map +0 -1
  165. package/dist/storage/implementation/MongoPersistedSyncRules.d.ts +0 -14
  166. package/dist/storage/implementation/MongoPersistedSyncRules.js +0 -67
  167. package/dist/storage/implementation/MongoPersistedSyncRules.js.map +0 -1
  168. package/dist/storage/implementation/MongoPersistedSyncRulesContent.d.ts +0 -29
  169. package/dist/storage/implementation/MongoPersistedSyncRulesContent.js +0 -76
  170. package/dist/storage/implementation/MongoPersistedSyncRulesContent.js.map +0 -1
  171. package/dist/storage/implementation/common/MongoSyncBucketStorageContext.d.ts +0 -13
  172. package/dist/storage/implementation/common/MongoSyncBucketStorageContext.js +0 -2
  173. package/dist/storage/implementation/common/MongoSyncBucketStorageContext.js.map +0 -1
  174. package/dist/storage/implementation/v3/MongoParameterCompactorV3.d.ts +0 -9
  175. package/dist/storage/implementation/v3/MongoParameterCompactorV3.js +0 -18
  176. package/dist/storage/implementation/v3/MongoParameterCompactorV3.js.map +0 -1
  177. package/dist/storage/implementation/v3/MongoParameterLookupV3.d.ts +0 -4
  178. package/dist/storage/implementation/v3/MongoParameterLookupV3.js +0 -9
  179. package/dist/storage/implementation/v3/MongoParameterLookupV3.js.map +0 -1
  180. package/src/storage/implementation/BucketDefinitionMapping.ts +0 -75
  181. package/src/storage/implementation/MongoPersistedSyncRules.ts +0 -82
  182. package/src/storage/implementation/MongoPersistedSyncRulesContent.ts +0 -101
  183. package/src/storage/implementation/common/MongoSyncBucketStorageContext.ts +0 -15
  184. package/src/storage/implementation/v3/MongoParameterCompactorV3.ts +0 -24
  185. package/src/storage/implementation/v3/MongoParameterLookupV3.ts +0 -11
@@ -1,15 +1,25 @@
1
- import { InternalOpId, SerializedSyncPlan, SyncRuleState } from '@powersync/service-core';
2
- import { BucketDefinitionId, ParameterIndexId } from '@powersync/service-sync-rules';
1
+ import {
2
+ InternalOpId,
3
+ PersistedDefinitionMapping,
4
+ SerializedSyncPlan,
5
+ SyncRuleState,
6
+ deserializeParameterLookup as deserializeParameterLookupCore
7
+ } from '@powersync/service-core';
8
+ import {
9
+ BucketDefinitionId,
10
+ ParameterIndexId,
11
+ ScopedParameterLookup,
12
+ SqliteJsonValue
13
+ } from '@powersync/service-sync-rules';
3
14
  import * as bson from 'bson';
4
- import { BucketDataDoc, BucketKey } from '../common/BucketDataDoc.js';
5
15
  import {
6
- BucketDataDocumentBase,
7
16
  BucketDataKey,
8
17
  BucketParameterDocumentBase,
9
18
  BucketStateDocumentBase,
10
19
  CurrentBucket,
20
+ OpType,
11
21
  ReplicaId,
12
- SourceTableDocument,
22
+ SourceTableDocumentSnapshotStatus,
13
23
  SourceTableKey,
14
24
  SyncRuleCheckpointFields,
15
25
  SyncRuleDocumentBase,
@@ -19,7 +29,7 @@ import {
19
29
  /**
20
30
  * Embedded in sync_rules.sync_configs.
21
31
  */
22
- export interface SyncRuleConfigStateV3 extends SyncRuleCheckpointFields<bigint | null> {
32
+ export interface SyncRuleConfigStateV3 extends SyncRuleCheckpointFields {
23
33
  _id: bson.ObjectId;
24
34
 
25
35
  /**
@@ -47,6 +57,31 @@ export interface ReplicationStreamDocumentV3 extends SyncRuleDocumentBase {
47
57
  * but the model allows multiple configs in any state.
48
58
  */
49
59
  sync_configs: SyncRuleConfigStateV3[];
60
+
61
+ /**
62
+ * The monotonic head of the stream's op sequence: the highest op id persisted to bucket data,
63
+ * whether or not yet covered by a checkpoint.
64
+ *
65
+ * This is shared across all sync configs of the stream (they share the global op sequence).
66
+ * It is never cleared, only `$max`-advanced. A newly-appended config that replicates nothing
67
+ * adopts this value as its checkpoint rather than starting at 0.
68
+ *
69
+ * Stored as a mongo Long, nullable.
70
+ */
71
+ last_persisted_op?: bigint | null;
72
+
73
+ /**
74
+ * The stream's replication position: all source changes up to this LSN have been processed,
75
+ * and the resulting ops persisted. Replication resumes from here.
76
+ *
77
+ * Like {@link last_persisted_op}, this is shared across all sync configs of the stream -
78
+ * per-config last_checkpoint_lsn values are consistency markers, not replication positions.
79
+ *
80
+ * Set via setResumeLsn() (snapshot start, and per-batch progress during streaming), and
81
+ * advanced on every commit/keepalive - including checkpoint-blocked ones, since commit
82
+ * flushes first and blocking only delays consistency markers, not data persistence.
83
+ */
84
+ resume_lsn?: string | null;
50
85
  }
51
86
 
52
87
  /**
@@ -70,16 +105,7 @@ export interface SyncConfigDefinition {
70
105
  content: string;
71
106
  serialized_plan?: SerializedSyncPlan | null;
72
107
 
73
- rule_mapping: {
74
- /**
75
- * Map of uniqueName -> id, unique per replication stream.
76
- */
77
- definitions: Record<string, string>;
78
- /**
79
- * Map of (lookupName, queryId) -> id, unique per replication stream.
80
- */
81
- parameter_indexes: Record<string, string>;
82
- };
108
+ rule_mapping: PersistedDefinitionMapping;
83
109
  }
84
110
 
85
111
  export interface CurrentBucketV3 extends CurrentBucket {
@@ -108,50 +134,26 @@ export interface BucketParameterDocumentV3 extends BucketParameterDocumentBase<S
108
134
 
109
135
  export type BucketDataKeyV3 = BucketDataKey;
110
136
 
111
- export interface BucketDataDocumentV3 extends BucketDataDocumentBase {
112
- _id: BucketDataKeyV3;
113
- }
114
-
115
- export function serializeBucketDataV3(document: BucketDataDoc): BucketDataDocumentV3 {
116
- const { bucketKey, o } = document;
117
- return {
118
- _id: {
119
- b: bucketKey.bucket,
120
- o: o
121
- },
122
- // List fields directly, so that we don't accidentally persist any unknown fields
123
- op: document.op,
124
- source_table: document.source_table,
125
- source_key: document.source_key,
126
- table: document.table,
127
- row_id: document.row_id,
128
- checksum: document.checksum,
129
- data: document.data,
130
- target_op: document.target_op
131
- };
132
- }
133
-
134
- export function loadBucketDataDocumentV3(
135
- context: Pick<BucketKey, 'replicationStreamId' | 'definitionId'>,
136
- doc: BucketDataDocumentV3
137
- ): BucketDataDoc {
138
- const { _id, ...rest } = doc;
139
- return {
140
- bucketKey: {
141
- ...context,
142
- bucket: _id.b
143
- },
144
- o: _id.o,
145
- ...rest
146
- };
147
- }
148
-
149
137
  export function taggedBucketParameterDocumentToV3(document: TaggedBucketParameterDocument): BucketParameterDocumentV3 {
150
138
  const { index: _index, ...rest } = document;
151
139
  return rest as BucketParameterDocumentV3;
152
140
  }
153
141
 
154
- export interface SourceTableDocumentV3 extends SourceTableDocument {
142
+ export interface ReplicaIdColumn {
143
+ name: string;
144
+ type_oid?: number;
145
+ type?: string;
146
+ }
147
+
148
+ export interface SourceTableDocumentV3 {
149
+ _id: bson.ObjectId;
150
+ connection_id: number;
151
+ relation_id: number | string | undefined;
152
+ schema_name: string;
153
+ table_name: string;
154
+ replica_id_columns: ReplicaIdColumn[];
155
+ snapshot_done: boolean;
156
+ snapshot_status: SourceTableDocumentSnapshotStatus | undefined;
155
157
  bucket_data_source_ids: BucketDefinitionId[];
156
158
  parameter_lookup_source_ids: ParameterIndexId[];
157
159
  latest_pending_delete?: InternalOpId | undefined;
@@ -162,3 +164,39 @@ export interface BucketStateDocumentV3 extends BucketStateDocumentBase {
162
164
  d: BucketDefinitionId;
163
165
  };
164
166
  }
167
+
168
+ export interface BucketOperation {
169
+ o: bigint;
170
+ op: OpType;
171
+ source_table?: bson.ObjectId;
172
+ source_key?: ReplicaId;
173
+ table?: string;
174
+ row_id?: string;
175
+ checksum: bigint;
176
+ data: string | null;
177
+ }
178
+
179
+ export interface BucketDataDocumentV3 {
180
+ _id: BucketDataKey;
181
+ min_op: bigint;
182
+ checksum: bigint;
183
+ count: number;
184
+ size: number;
185
+ target_op?: bigint | null;
186
+ ops: BucketOperation[];
187
+ }
188
+
189
+ export function serializeParameterLookup(lookup: ScopedParameterLookup): bson.Binary {
190
+ return new bson.Binary(bson.serialize({ l: lookup.values.slice(2) }));
191
+ }
192
+
193
+ export function deserializeParameterLookup(lookup: bson.Binary, indexId: ParameterIndexId): SqliteJsonValue[] {
194
+ return [indexId, '', ...deserializeParameterLookupCore(lookup)];
195
+ }
196
+
197
+ export function taggedBucketParameterDocumentToTagged(
198
+ document: TaggedBucketParameterDocument
199
+ ): BucketParameterDocumentV3 {
200
+ const { index: _index, ...rest } = document;
201
+ return rest as BucketParameterDocumentV3;
202
+ }
@@ -0,0 +1,392 @@
1
+ import { ReplicationAssertionError } from '@powersync/lib-services-framework';
2
+ import { BucketDefinitionMapping, ColumnDescriptor, storage } from '@powersync/service-core';
3
+ import {
4
+ BucketDataSource,
5
+ BucketDefinitionId,
6
+ HydratedSyncConfig,
7
+ MatchingSources,
8
+ ParameterIndexId,
9
+ ParameterIndexLookupCreator,
10
+ SourceTableRef
11
+ } from '@powersync/service-sync-rules';
12
+ import * as bson from 'bson';
13
+ import { ReplicaIdColumn, SourceTableDocumentV3 } from './models.js';
14
+
15
+ export interface SourceTableIdentity {
16
+ schema: string;
17
+ name: string;
18
+ objectId: number | string | undefined;
19
+ replicaIdColumns: ReplicaIdColumn[];
20
+ }
21
+
22
+ export interface SourceTableMembershipIds {
23
+ bucketDataSourceIds: BucketDefinitionId[];
24
+ parameterLookupSourceIds: ParameterIndexId[];
25
+ }
26
+
27
+ export interface SourceTableDesiredResolution {
28
+ bucketSourceById: Map<BucketDefinitionId, BucketDataSource>;
29
+ parameterLookupSourceById: Map<ParameterIndexId, ParameterIndexLookupCreator>;
30
+ triggersEvent: boolean;
31
+ }
32
+
33
+ export interface SourceTableReconciliationContext {
34
+ connectionId: number;
35
+ connectionTag: string;
36
+ identity: SourceTableIdentity;
37
+ storeCurrentData: boolean;
38
+ syncConfig: HydratedSyncConfig;
39
+ mapping: BucketDefinitionMapping;
40
+ desired: SourceTableDesiredResolution;
41
+ }
42
+
43
+ export interface SourceTableReconciliationPlan {
44
+ /** Retained source tables, with memberships narrowed to the desired set. */
45
+ tables: storage.SourceTable[];
46
+ /** Membership narrowing to persist for retained snapshot-incomplete docs. */
47
+ narrowingUpdates: SourceTableMembershipUpdate[];
48
+ /**
49
+ * Memberships for a new source-table doc covering desired ids no existing doc covers,
50
+ * or null if no new doc is needed. Empty memberships indicate an event-only table.
51
+ */
52
+ newTableMemberships: SourceTableMembershipIds | null;
53
+ /** Identity-overlapping docs that conflict with the current identity and must be dropped. */
54
+ dropDocs: SourceTableDocumentV3[];
55
+ }
56
+
57
+ export interface SourceTableMembershipUpdate {
58
+ id: bson.ObjectId;
59
+ memberships: SourceTableMembershipIds;
60
+ }
61
+
62
+ export interface NewSourceTable {
63
+ doc: SourceTableDocumentV3;
64
+ table: storage.SourceTable;
65
+ }
66
+
67
+ export function sourceTableDesiredResolution(
68
+ syncConfig: HydratedSyncConfig,
69
+ ref: SourceTableRef,
70
+ mapping: BucketDefinitionMapping
71
+ ): SourceTableDesiredResolution {
72
+ const matchingSources = syncConfig.getMatchingSources(ref);
73
+ return {
74
+ bucketSourceById: new Map(
75
+ matchingSources.bucketDataSources.map((source) => [mapping.bucketSourceId(source), source] as const)
76
+ ),
77
+ parameterLookupSourceById: new Map(
78
+ matchingSources.parameterLookupSources.map((source) => [mapping.parameterLookupId(source), source] as const)
79
+ ),
80
+ triggersEvent: syncConfig.tableTriggersEvent(ref)
81
+ };
82
+ }
83
+
84
+ export function planSourceTableReconciliation(
85
+ candidateDocs: SourceTableDocumentV3[],
86
+ context: SourceTableReconciliationContext
87
+ ): SourceTableReconciliationPlan {
88
+ return new SourceTableReconciliationPlanner(context).plan(candidateDocs);
89
+ }
90
+
91
+ function sameStringArray(left: string[], right: string[]) {
92
+ return left.length == right.length && left.every((value, index) => value == right[index]);
93
+ }
94
+
95
+ function matchingSourcesFor(
96
+ desired: SourceTableDesiredResolution,
97
+ memberships: SourceTableMembershipIds
98
+ ): MatchingSources {
99
+ return {
100
+ bucketDataSources: memberships.bucketDataSourceIds.map((id) => desired.bucketSourceById.get(id)!),
101
+ parameterLookupSources: memberships.parameterLookupSourceIds.map((id) => desired.parameterLookupSourceById.get(id)!)
102
+ };
103
+ }
104
+
105
+ function intersectMembershipIds(
106
+ doc: SourceTableDocumentV3,
107
+ desired: SourceTableDesiredResolution
108
+ ): SourceTableMembershipIds {
109
+ return {
110
+ bucketDataSourceIds: doc.bucket_data_source_ids.filter((id) => desired.bucketSourceById.has(id)),
111
+ parameterLookupSourceIds: doc.parameter_lookup_source_ids.filter((id) => desired.parameterLookupSourceById.has(id))
112
+ };
113
+ }
114
+
115
+ function hasMembershipIds(memberships: SourceTableMembershipIds) {
116
+ return memberships.bucketDataSourceIds.length > 0 || memberships.parameterLookupSourceIds.length > 0;
117
+ }
118
+
119
+ function sameMembershipIds(doc: SourceTableDocumentV3, memberships: SourceTableMembershipIds) {
120
+ return (
121
+ sameStringArray(doc.bucket_data_source_ids, memberships.bucketDataSourceIds) &&
122
+ sameStringArray(doc.parameter_lookup_source_ids, memberships.parameterLookupSourceIds)
123
+ );
124
+ }
125
+
126
+ class SourceTableReconciliationPlanner {
127
+ private readonly coveredBucketDataSourceIds = new Set<string>();
128
+ private readonly coveredParameterLookupSourceIds = new Set<string>();
129
+ private readonly retainedDocIds = new Set<string>();
130
+ private readonly tables: storage.SourceTable[] = [];
131
+ private readonly narrowingUpdates: SourceTableMembershipUpdate[] = [];
132
+ private retainedEventOnlyTable = false;
133
+
134
+ constructor(private readonly context: SourceTableReconciliationContext) {}
135
+
136
+ plan(candidateDocs: SourceTableDocumentV3[]): SourceTableReconciliationPlan {
137
+ const { identity } = this.context;
138
+ for (const doc of candidateDocs) {
139
+ if (matchingSourceTableIdentity(doc, identity)) {
140
+ this.retainDoc(doc);
141
+ }
142
+ }
143
+
144
+ return {
145
+ tables: this.tables,
146
+ narrowingUpdates: this.narrowingUpdates,
147
+ newTableMemberships: this.newTableMemberships(),
148
+ // Non-retained overlapping docs represent renames / relation-id changes /
149
+ // replica-identity changes. Same-identity stale docs are retained in production.
150
+ dropDocs: candidateDocs.filter(
151
+ (doc) => !this.retainedDocIds.has(doc._id.toHexString()) && !matchingSourceTableIdentity(doc, identity)
152
+ )
153
+ };
154
+ }
155
+
156
+ private retainDoc(doc: SourceTableDocumentV3) {
157
+ const memberships = intersectMembershipIds(doc, this.context.desired);
158
+ const coversDesiredMembership = hasMembershipIds(memberships);
159
+ const coversEventOnlyTable =
160
+ !this.desiredHasMembership() && this.context.desired.triggersEvent && !this.retainedEventOnlyTable;
161
+
162
+ this.recordCoverage(doc, memberships);
163
+ this.planNarrowingUpdate(doc, memberships, coversDesiredMembership, coversEventOnlyTable);
164
+
165
+ if (coversDesiredMembership || coversEventOnlyTable) {
166
+ this.retainedEventOnlyTable ||= coversEventOnlyTable;
167
+ this.retainedDocIds.add(doc._id.toHexString());
168
+ this.tables.push(this.sourceTableFor(doc, memberships));
169
+ }
170
+ }
171
+
172
+ private desiredHasMembership() {
173
+ const { desired } = this.context;
174
+ return desired.bucketSourceById.size > 0 || desired.parameterLookupSourceById.size > 0;
175
+ }
176
+
177
+ private recordCoverage(doc: SourceTableDocumentV3, memberships: SourceTableMembershipIds) {
178
+ this.addCoverage(doc, 'bucket data source', this.coveredBucketDataSourceIds, memberships.bucketDataSourceIds);
179
+ this.addCoverage(
180
+ doc,
181
+ 'parameter lookup source',
182
+ this.coveredParameterLookupSourceIds,
183
+ memberships.parameterLookupSourceIds
184
+ );
185
+ }
186
+
187
+ // Membership sets must be pairwise disjoint across the docs of one physical table:
188
+ // each desired id is covered by exactly one doc, so each definition receives each
189
+ // row exactly once. The algorithm maintains this (new docs only get uncovered ids,
190
+ // narrowing only removes ids) - overlap means the persisted state is corrupt.
191
+ private addCoverage(doc: SourceTableDocumentV3, kind: string, covered: Set<string>, ids: string[]) {
192
+ const { schema, name } = this.context.identity;
193
+ for (const id of ids) {
194
+ if (covered.has(id)) {
195
+ throw new ReplicationAssertionError(
196
+ `Source table ${doc._id} duplicates coverage of ${kind} ${id} for ${schema}.${name}`
197
+ );
198
+ }
199
+ covered.add(id);
200
+ }
201
+ }
202
+
203
+ private planNarrowingUpdate(
204
+ doc: SourceTableDocumentV3,
205
+ memberships: SourceTableMembershipIds,
206
+ coversDesiredMembership: boolean,
207
+ coversEventOnlyTable: boolean
208
+ ) {
209
+ const shouldNarrow =
210
+ (coversDesiredMembership || coversEventOnlyTable) && !doc.snapshot_done && !sameMembershipIds(doc, memberships);
211
+
212
+ if (!shouldNarrow) {
213
+ return;
214
+ }
215
+
216
+ this.narrowingUpdates.push({
217
+ id: doc._id,
218
+ memberships
219
+ });
220
+ }
221
+
222
+ private newTableMemberships(): SourceTableMembershipIds | null {
223
+ const { desired } = this.context;
224
+ const uncovered: SourceTableMembershipIds = {
225
+ bucketDataSourceIds: [...desired.bucketSourceById.keys()].filter(
226
+ (id) => !this.coveredBucketDataSourceIds.has(id)
227
+ ),
228
+ parameterLookupSourceIds: [...desired.parameterLookupSourceById.keys()].filter(
229
+ (id) => !this.coveredParameterLookupSourceIds.has(id)
230
+ )
231
+ };
232
+ if (hasMembershipIds(uncovered) || (desired.triggersEvent && this.tables.length == 0)) {
233
+ return uncovered;
234
+ }
235
+ return null;
236
+ }
237
+
238
+ private sourceTableFor(doc: SourceTableDocumentV3, memberships: SourceTableMembershipIds): storage.SourceTable {
239
+ const { connectionTag, syncConfig, mapping, desired, storeCurrentData } = this.context;
240
+ const table = sourceTableFromDocument(
241
+ doc,
242
+ connectionTag,
243
+ syncConfig,
244
+ mapping,
245
+ matchingSourcesFor(desired, memberships),
246
+ memberships
247
+ );
248
+ table.storeCurrentData = storeCurrentData;
249
+ return table;
250
+ }
251
+ }
252
+
253
+ function sameReplicaIdColumns(left: ReplicaIdColumn[] | undefined, right: ReplicaIdColumn[]) {
254
+ return (
255
+ left != null &&
256
+ left.length == right.length &&
257
+ left.every(
258
+ (column, index) =>
259
+ column.name == right[index].name && column.type == right[index].type && column.type_oid == right[index].type_oid
260
+ )
261
+ );
262
+ }
263
+
264
+ function matchingSourceTableIdentity(doc: SourceTableDocumentV3, identity: SourceTableIdentity) {
265
+ return (
266
+ doc.schema_name == identity.schema &&
267
+ doc.table_name == identity.name &&
268
+ (identity.objectId == null || doc.relation_id == identity.objectId) &&
269
+ sameReplicaIdColumns(doc.replica_id_columns, identity.replicaIdColumns)
270
+ );
271
+ }
272
+
273
+ export function overlappingSourceTableFilter(
274
+ connectionId: number,
275
+ identity: Pick<SourceTableIdentity, 'schema' | 'name' | 'objectId'>
276
+ ): Record<string, unknown> {
277
+ const clauses = [{ schema_name: identity.schema, table_name: identity.name }] as Record<string, unknown>[];
278
+ if (identity.objectId != null) {
279
+ clauses.push({ relation_id: identity.objectId });
280
+ }
281
+
282
+ return {
283
+ connection_id: connectionId,
284
+ $or: clauses
285
+ };
286
+ }
287
+
288
+ export function createNewSourceTable(
289
+ id: bson.ObjectId,
290
+ memberships: SourceTableMembershipIds,
291
+ context: SourceTableReconciliationContext
292
+ ): NewSourceTable {
293
+ const { connectionId, connectionTag, identity, syncConfig, mapping, desired, storeCurrentData } = context;
294
+ const doc: SourceTableDocumentV3 = {
295
+ _id: id,
296
+ connection_id: connectionId,
297
+ relation_id: identity.objectId,
298
+ schema_name: identity.schema,
299
+ table_name: identity.name,
300
+ replica_id_columns: identity.replicaIdColumns,
301
+ snapshot_done: false,
302
+ snapshot_status: undefined,
303
+ bucket_data_source_ids: memberships.bucketDataSourceIds,
304
+ parameter_lookup_source_ids: memberships.parameterLookupSourceIds
305
+ };
306
+ const table = sourceTableFromDocument(
307
+ doc,
308
+ connectionTag,
309
+ syncConfig,
310
+ mapping,
311
+ matchingSourcesFor(desired, memberships),
312
+ memberships
313
+ );
314
+ table.storeCurrentData = storeCurrentData;
315
+
316
+ return { doc, table };
317
+ }
318
+
319
+ export function designateEventCarrier(tables: storage.SourceTable[], triggersEvent: boolean) {
320
+ if (!triggersEvent) {
321
+ return;
322
+ }
323
+
324
+ const eventCarrier = tables.find((table) => table.snapshotComplete) ?? tables[0];
325
+ for (const table of tables) {
326
+ table.syncEvent = table === eventCarrier;
327
+ }
328
+ }
329
+
330
+ function sourceTableMembershipsFromDocument(
331
+ doc: SourceTableDocumentV3,
332
+ syncConfig: HydratedSyncConfig,
333
+ mapping: BucketDefinitionMapping
334
+ ): MatchingSources {
335
+ const bucketDataSourceIds = new Set(doc.bucket_data_source_ids);
336
+ const parameterLookupSourceIds = new Set(doc.parameter_lookup_source_ids);
337
+
338
+ return {
339
+ bucketDataSources: syncConfig.bucketDataSources.filter((source) =>
340
+ bucketDataSourceIds.has(mapping.bucketSourceId(source))
341
+ ),
342
+ parameterLookupSources: syncConfig.bucketParameterLookupSources.filter((source) =>
343
+ parameterLookupSourceIds.has(mapping.parameterLookupId(source))
344
+ )
345
+ };
346
+ }
347
+
348
+ export function sourceTableFromDocument(
349
+ doc: SourceTableDocumentV3,
350
+ connectionTag: string,
351
+ syncConfig: HydratedSyncConfig,
352
+ mapping: BucketDefinitionMapping,
353
+ memberships?: MatchingSources,
354
+ membershipIds?: SourceTableMembershipIds
355
+ ): storage.SourceTable {
356
+ const resolvedMemberships = memberships ?? sourceTableMembershipsFromDocument(doc, syncConfig, mapping);
357
+ const resolvedMembershipIds = membershipIds ?? {
358
+ bucketDataSourceIds: resolvedMemberships.bucketDataSources.map((source) => mapping.bucketSourceId(source)),
359
+ parameterLookupSourceIds: resolvedMemberships.parameterLookupSources.map((source) =>
360
+ mapping.parameterLookupId(source)
361
+ )
362
+ };
363
+ const table = new storage.SourceTable({
364
+ id: doc._id,
365
+ ref: {
366
+ connectionTag,
367
+ schema: doc.schema_name,
368
+ name: doc.table_name
369
+ },
370
+ objectId: doc.relation_id,
371
+ replicaIdColumns: doc.replica_id_columns!.map(
372
+ (c) => ({ name: c.name, typeId: c.type_oid, type: c.type }) satisfies ColumnDescriptor
373
+ ),
374
+ snapshotComplete: doc.snapshot_done,
375
+ bucketDataSources: resolvedMemberships.bucketDataSources,
376
+ parameterLookupSources: resolvedMemberships.parameterLookupSources,
377
+ bucketDataSourceIds: new Set(resolvedMembershipIds.bucketDataSourceIds),
378
+ parameterLookupSourceIds: new Set(resolvedMembershipIds.parameterLookupSourceIds)
379
+ });
380
+ table.syncData = table.bucketDataSources.length > 0;
381
+ table.syncParameters = table.parameterLookupSources.length > 0;
382
+ table.syncEvent = syncConfig.tableTriggersEvent(table.ref);
383
+ table.snapshotStatus =
384
+ doc.snapshot_status == null
385
+ ? undefined
386
+ : {
387
+ lastKey: doc.snapshot_status.last_key?.buffer ?? null,
388
+ totalEstimatedCount: doc.snapshot_status.total_estimated_count,
389
+ replicatedCount: doc.snapshot_status.replicated_count
390
+ };
391
+ return table;
392
+ }
@@ -1,17 +1,25 @@
1
1
  export * as test_utils from '../utils/test-utils.js';
2
2
  export * from '../utils/util.js';
3
- export * from './implementation/BucketDefinitionMapping.js';
4
3
  export * from './implementation/common/PersistedBatch.js';
5
4
  export * from './implementation/createMongoSyncBucketStorage.js';
6
5
  export * from './implementation/db.js';
7
6
  export * from './implementation/models.js';
8
7
  export * from './implementation/MongoIdSequence.js';
9
- export * from './implementation/MongoPersistedSyncRules.js';
10
- export * from './implementation/MongoPersistedSyncRulesContent.js';
8
+ export * from './implementation/MongoParsedSyncConfigSet.js';
9
+ export * from './implementation/MongoPersistedReplicationStream.js';
11
10
  export * from './implementation/MongoStorageProvider.js';
12
11
  export * from './implementation/MongoSyncRulesLock.js';
13
12
  export * from './implementation/OperationBatch.js';
14
13
  export * from './implementation/v1/models.js';
15
- export * from './implementation/v3/models.js';
14
+ export { loadBucketDataDocument, serializeBucketData } from './implementation/v3/bucket-format.js';
15
+ export {
16
+ BucketDataDocumentV3,
17
+ BucketOperation,
18
+ RecordedLookupV3,
19
+ ReplicationStreamDocumentV3,
20
+ SyncConfigDefinition,
21
+ SyncRuleConfigStateV3,
22
+ taggedBucketParameterDocumentToTagged
23
+ } from './implementation/v3/models.js';
16
24
  export * from './MongoBucketStorage.js';
17
25
  export * from './MongoReportStorage.js';
@@ -7,8 +7,7 @@ import { PowerSyncMongo } from '../storage/implementation/db.js';
7
7
  export type MongoTestStorageOptions = {
8
8
  url: string;
9
9
  isCI: boolean;
10
- internalOptions?: MongoBucketStorageOptions;
11
- };
10
+ } & Omit<MongoBucketStorageOptions, 'replicationStreamNamePrefix'>;
12
11
 
13
12
  export function mongoTestStorageFactoryGenerator(factoryOptions: MongoTestStorageOptions) {
14
13
  return {
@@ -27,7 +26,11 @@ export function mongoTestStorageFactoryGenerator(factoryOptions: MongoTestStorag
27
26
  await db.clear();
28
27
  }
29
28
 
30
- return new MongoBucketStorage(db, { slot_name_prefix: 'test_' }, factoryOptions.internalOptions);
29
+ return new MongoBucketStorage(db, {
30
+ replicationStreamNamePrefix: 'test_',
31
+ checksumOptions: factoryOptions.checksumOptions,
32
+ supportsMultipleSyncConfigs: factoryOptions.supportsMultipleSyncConfigs
33
+ });
31
34
  },
32
35
  tableIdStrings: false
33
36
  };
package/src/utils/util.ts CHANGED
@@ -26,9 +26,9 @@ export function idPrefixFilter<T>(prefix: Partial<T>, rest: (keyof T)[]): mongo.
26
26
  return filter;
27
27
  }
28
28
 
29
- export function generateSlotName(prefix: string, sync_rules_id: number) {
29
+ export function generateReplicationStreamName(prefix: string, replicationStreamId: number) {
30
30
  const slot_suffix = crypto.randomBytes(2).toString('hex');
31
- return `${prefix}${sync_rules_id}_${slot_suffix}`;
31
+ return `${prefix}${replicationStreamId}_${slot_suffix}`;
32
32
  }
33
33
 
34
34
  /**
@@ -141,6 +141,7 @@ export async function retryOnMongoMaxTimeMSExpired<T>(
141
141
  }
142
142
  ): Promise<T> {
143
143
  let retryCount = 0;
144
+ // Retry indefinitely on MaxTimeMSExpired errors with exponential backoff.
144
145
  while (true) {
145
146
  if (options.signal?.aborted) {
146
147
  throw new ReplicationAbortedError(options.abortMessage ?? 'Aborted MongoDB operation', options.signal.reason);