@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.
- package/CHANGELOG.md +27 -0
- package/dist/storage/MongoBucketStorage.d.ts +34 -16
- package/dist/storage/MongoBucketStorage.js +219 -70
- package/dist/storage/MongoBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoBucketBatch.d.ts +42 -23
- package/dist/storage/implementation/MongoBucketBatch.js +61 -44
- package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
- package/dist/storage/implementation/MongoChecksums.d.ts +10 -9
- package/dist/storage/implementation/MongoChecksums.js +3 -111
- package/dist/storage/implementation/MongoChecksums.js.map +1 -1
- package/dist/storage/implementation/MongoCompactor.d.ts +2 -0
- package/dist/storage/implementation/MongoCompactor.js +18 -9
- package/dist/storage/implementation/MongoCompactor.js.map +1 -1
- package/dist/storage/implementation/MongoHydrationState.d.ts +11 -0
- package/dist/storage/implementation/MongoHydrationState.js +49 -0
- package/dist/storage/implementation/MongoHydrationState.js.map +1 -0
- package/dist/storage/implementation/MongoParameterCompactor.d.ts +6 -5
- package/dist/storage/implementation/MongoParameterCompactor.js +24 -1
- package/dist/storage/implementation/MongoParameterCompactor.js.map +1 -1
- package/dist/storage/implementation/MongoParsedSyncConfigSet.d.ts +13 -0
- package/dist/storage/implementation/MongoParsedSyncConfigSet.js +64 -0
- package/dist/storage/implementation/MongoParsedSyncConfigSet.js.map +1 -0
- package/dist/storage/implementation/MongoPersistedReplicationStream.d.ts +36 -0
- package/dist/storage/implementation/MongoPersistedReplicationStream.js +90 -0
- package/dist/storage/implementation/MongoPersistedReplicationStream.js.map +1 -0
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.d.ts +25 -0
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.js +123 -0
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.js.map +1 -0
- package/dist/storage/implementation/MongoStorageProvider.js +5 -2
- package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
- package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +41 -23
- package/dist/storage/implementation/MongoSyncBucketStorage.js +51 -43
- package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.d.ts +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.js +3 -3
- package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
- package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.d.ts +6 -0
- package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.js +2 -0
- package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.js.map +1 -0
- package/dist/storage/implementation/common/PersistedBatch.d.ts +1 -2
- package/dist/storage/implementation/common/PersistedBatch.js +5 -0
- package/dist/storage/implementation/common/PersistedBatch.js.map +1 -1
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js +1 -1
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js.map +1 -1
- package/dist/storage/implementation/createMongoSyncBucketStorage.d.ts +2 -2
- package/dist/storage/implementation/createMongoSyncBucketStorage.js +4 -4
- package/dist/storage/implementation/createMongoSyncBucketStorage.js.map +1 -1
- package/dist/storage/implementation/db.js +9 -14
- package/dist/storage/implementation/db.js.map +1 -1
- package/dist/storage/implementation/models.d.ts +4 -13
- package/dist/storage/implementation/models.js.map +1 -1
- package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +9 -1
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js +42 -26
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoChecksumsV1.js +114 -3
- package/dist/storage/implementation/v1/MongoChecksumsV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.d.ts +15 -17
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js +47 -45
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js.map +1 -1
- package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.d.ts +2 -1
- package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js +3 -0
- package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js.map +1 -1
- package/dist/storage/implementation/v1/models.d.ts +10 -1
- package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +8 -4
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js +286 -259
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoChecksumsV3.d.ts +27 -7
- package/dist/storage/implementation/v3/MongoChecksumsV3.js +202 -18
- package/dist/storage/implementation/v3/MongoChecksumsV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +19 -2
- package/dist/storage/implementation/v3/MongoCompactorV3.js +511 -22
- package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.d.ts +62 -0
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js +350 -0
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js.map +1 -0
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.d.ts +40 -28
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js +232 -116
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js.map +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.js +43 -20
- package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/SingleBucketStoreV3.js +52 -16
- package/dist/storage/implementation/v3/SingleBucketStoreV3.js.map +1 -1
- package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +3 -3
- package/dist/storage/implementation/v3/SourceRecordStoreV3.js +13 -11
- package/dist/storage/implementation/v3/SourceRecordStoreV3.js.map +1 -1
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.d.ts +13 -12
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js +29 -27
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js.map +1 -1
- package/dist/storage/implementation/v3/bucket-format.d.ts +4 -0
- package/dist/storage/implementation/v3/bucket-format.js +58 -0
- package/dist/storage/implementation/v3/bucket-format.js.map +1 -0
- package/dist/storage/implementation/v3/chunking.d.ts +10 -0
- package/dist/storage/implementation/v3/chunking.js +28 -0
- package/dist/storage/implementation/v3/chunking.js.map +1 -0
- package/dist/storage/implementation/v3/models.d.ts +64 -21
- package/dist/storage/implementation/v3/models.js +11 -28
- package/dist/storage/implementation/v3/models.js.map +1 -1
- package/dist/storage/implementation/v3/source-table-utils.d.ts +55 -0
- package/dist/storage/implementation/v3/source-table-utils.js +214 -0
- package/dist/storage/implementation/v3/source-table-utils.js.map +1 -0
- package/dist/storage/storage-index.d.ts +4 -4
- package/dist/storage/storage-index.js +4 -4
- package/dist/storage/storage-index.js.map +1 -1
- package/dist/types/types.d.ts +2 -2
- package/dist/utils/test-utils.d.ts +1 -2
- package/dist/utils/test-utils.js +5 -1
- package/dist/utils/test-utils.js.map +1 -1
- package/dist/utils/util.d.ts +1 -1
- package/dist/utils/util.js +3 -2
- package/dist/utils/util.js.map +1 -1
- package/package.json +9 -19
- package/src/storage/MongoBucketStorage.ts +334 -87
- package/src/storage/implementation/MongoBucketBatch.ts +86 -58
- package/src/storage/implementation/MongoChecksums.ts +6 -138
- package/src/storage/implementation/MongoCompactor.ts +19 -9
- package/src/storage/implementation/MongoHydrationState.ts +61 -0
- package/src/storage/implementation/MongoParameterCompactor.ts +24 -5
- package/src/storage/implementation/MongoParsedSyncConfigSet.ts +88 -0
- package/src/storage/implementation/MongoPersistedReplicationStream.ts +118 -0
- package/src/storage/implementation/MongoPersistedSyncConfigContent.ts +154 -0
- package/src/storage/implementation/MongoStorageProvider.ts +5 -2
- package/src/storage/implementation/MongoSyncBucketStorage.ts +70 -56
- package/src/storage/implementation/MongoSyncRulesLock.ts +7 -4
- package/src/storage/implementation/common/MongoSyncBucketStorageCheckpoint.ts +7 -0
- package/src/storage/implementation/common/PersistedBatch.ts +7 -3
- package/src/storage/implementation/common/VersionedPowerSyncMongoBase.ts +1 -1
- package/src/storage/implementation/createMongoSyncBucketStorage.ts +21 -7
- package/src/storage/implementation/db.ts +11 -19
- package/src/storage/implementation/models.ts +4 -14
- package/src/storage/implementation/v1/MongoBucketBatchV1.ts +55 -34
- package/src/storage/implementation/v1/MongoChecksumsV1.ts +137 -4
- package/src/storage/implementation/v1/MongoSyncBucketStorageV1.ts +70 -64
- package/src/storage/implementation/v1/VersionedPowerSyncMongoV1.ts +11 -1
- package/src/storage/implementation/v1/models.ts +11 -1
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +358 -314
- package/src/storage/implementation/v3/MongoChecksumsV3.ts +262 -26
- package/src/storage/implementation/v3/MongoCompactorV3.ts +646 -29
- package/src/storage/implementation/v3/MongoStoppedSyncConfigCleanup.ts +480 -0
- package/src/storage/implementation/v3/MongoSyncBucketStorageV3.ts +315 -157
- package/src/storage/implementation/v3/PersistedBatchV3.ts +62 -36
- package/src/storage/implementation/v3/SingleBucketStoreV3.ts +59 -19
- package/src/storage/implementation/v3/SourceRecordStoreV3.ts +12 -12
- package/src/storage/implementation/v3/VersionedPowerSyncMongoV3.ts +41 -36
- package/src/storage/implementation/v3/bucket-format.ts +70 -0
- package/src/storage/implementation/v3/chunking.ts +38 -0
- package/src/storage/implementation/v3/models.ts +93 -55
- package/src/storage/implementation/v3/source-table-utils.ts +392 -0
- package/src/storage/storage-index.ts +12 -4
- package/src/utils/test-utils.ts +6 -3
- package/src/utils/util.ts +3 -2
- package/test/src/__snapshots__/storage.test.ts.snap +0 -75
- package/test/src/__snapshots__/storage_sync.test.ts.snap +48 -48
- package/test/src/cleanup-stopped-sync-configs.test.ts +648 -0
- package/test/src/storage.test.ts +11 -11
- package/test/src/storage_compacting.test.ts +1956 -6
- package/test/src/storage_sync.test.ts +1077 -68
- package/test/src/storeCurrentData.test.ts +17 -7
- package/test/src/util.ts +2 -1
- package/tsconfig.json +1 -4
- package/tsconfig.tsbuildinfo +1 -1
- package/dist/storage/implementation/BucketDefinitionMapping.d.ts +0 -15
- package/dist/storage/implementation/BucketDefinitionMapping.js +0 -58
- package/dist/storage/implementation/BucketDefinitionMapping.js.map +0 -1
- package/dist/storage/implementation/MongoPersistedSyncRules.d.ts +0 -14
- package/dist/storage/implementation/MongoPersistedSyncRules.js +0 -67
- package/dist/storage/implementation/MongoPersistedSyncRules.js.map +0 -1
- package/dist/storage/implementation/MongoPersistedSyncRulesContent.d.ts +0 -29
- package/dist/storage/implementation/MongoPersistedSyncRulesContent.js +0 -76
- package/dist/storage/implementation/MongoPersistedSyncRulesContent.js.map +0 -1
- package/dist/storage/implementation/common/MongoSyncBucketStorageContext.d.ts +0 -13
- package/dist/storage/implementation/common/MongoSyncBucketStorageContext.js +0 -2
- package/dist/storage/implementation/common/MongoSyncBucketStorageContext.js.map +0 -1
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.d.ts +0 -9
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.js +0 -18
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.js.map +0 -1
- package/dist/storage/implementation/v3/MongoParameterLookupV3.d.ts +0 -4
- package/dist/storage/implementation/v3/MongoParameterLookupV3.js +0 -9
- package/dist/storage/implementation/v3/MongoParameterLookupV3.js.map +0 -1
- package/src/storage/implementation/BucketDefinitionMapping.ts +0 -75
- package/src/storage/implementation/MongoPersistedSyncRules.ts +0 -82
- package/src/storage/implementation/MongoPersistedSyncRulesContent.ts +0 -101
- package/src/storage/implementation/common/MongoSyncBucketStorageContext.ts +0 -15
- package/src/storage/implementation/v3/MongoParameterCompactorV3.ts +0 -24
- package/src/storage/implementation/v3/MongoParameterLookupV3.ts +0 -11
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import * as lib_mongo from '@powersync/lib-service-mongodb';
|
|
2
|
+
import { Logger, ReplicationAbortedError } from '@powersync/lib-services-framework';
|
|
3
|
+
import { SingleSyncConfigBucketDefinitionMapping, storage } from '@powersync/service-core';
|
|
4
|
+
import { BucketDefinitionId, ParameterIndexId, SyncConfig } from '@powersync/service-sync-rules';
|
|
5
|
+
import * as bson from 'bson';
|
|
6
|
+
import { idPrefixFilter, retryOnMongoMaxTimeMSExpired } from '../../../utils/util.js';
|
|
7
|
+
import { VersionedPowerSyncMongoV3 } from './VersionedPowerSyncMongoV3.js';
|
|
8
|
+
import {
|
|
9
|
+
BucketStateDocumentV3,
|
|
10
|
+
ReplicationStreamDocumentV3,
|
|
11
|
+
SourceTableDocumentV3,
|
|
12
|
+
SyncConfigDefinition
|
|
13
|
+
} from './models.js';
|
|
14
|
+
|
|
15
|
+
type SyncConfigState = ReplicationStreamDocumentV3['sync_configs'][number];
|
|
16
|
+
|
|
17
|
+
const LIVE_STATES = new Set<storage.SyncRuleState>([
|
|
18
|
+
storage.SyncRuleState.ACTIVE,
|
|
19
|
+
storage.SyncRuleState.PROCESSING,
|
|
20
|
+
storage.SyncRuleState.ERRORED
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
const EMPTY_RESULT: storage.CleanupStoppedSyncConfigsResult = {
|
|
24
|
+
stoppedSyncConfigsRemoved: 0,
|
|
25
|
+
bucketDataCollectionsDropped: 0,
|
|
26
|
+
parameterIndexCollectionsDropped: 0,
|
|
27
|
+
bucketStateDocumentsDeleted: 0,
|
|
28
|
+
sourceRecordCollectionsDropped: 0,
|
|
29
|
+
sourceTablesUpdated: 0,
|
|
30
|
+
sourceTablesDeleted: 0
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export interface MongoStoppedSyncConfigCleanupOptions extends storage.CleanupStoppedSyncConfigsOptions {
|
|
34
|
+
replicationStreamId: number;
|
|
35
|
+
db: VersionedPowerSyncMongoV3;
|
|
36
|
+
logger: Logger;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class MongoStoppedSyncConfigCleanup {
|
|
40
|
+
private readonly db: VersionedPowerSyncMongoV3;
|
|
41
|
+
private readonly replicationStreamId: number;
|
|
42
|
+
private readonly signal: AbortSignal | undefined;
|
|
43
|
+
private readonly logger: Logger;
|
|
44
|
+
private readonly defaultSchema: string;
|
|
45
|
+
private readonly sourceConnectionTag: string;
|
|
46
|
+
|
|
47
|
+
constructor(options: MongoStoppedSyncConfigCleanupOptions) {
|
|
48
|
+
this.db = options.db;
|
|
49
|
+
this.replicationStreamId = options.replicationStreamId;
|
|
50
|
+
this.signal = options.signal;
|
|
51
|
+
this.logger = options.logger;
|
|
52
|
+
this.defaultSchema = options.defaultSchema;
|
|
53
|
+
this.sourceConnectionTag = options.sourceConnectionTag;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async run(): Promise<storage.CleanupStoppedSyncConfigsResult> {
|
|
57
|
+
this.throwIfAborted();
|
|
58
|
+
|
|
59
|
+
const doc = await this.db.sync_rules.findOne<ReplicationStreamDocumentV3>(
|
|
60
|
+
{ _id: this.replicationStreamId },
|
|
61
|
+
{ projection: { sync_configs: 1 } }
|
|
62
|
+
);
|
|
63
|
+
if (doc == null || doc.sync_configs.length == 0) {
|
|
64
|
+
return { ...EMPTY_RESULT };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const stoppedStates = doc.sync_configs.filter((config) => config.state == storage.SyncRuleState.STOP);
|
|
68
|
+
if (stoppedStates.length == 0) {
|
|
69
|
+
return { ...EMPTY_RESULT };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const liveStates = doc.sync_configs.filter((config) => LIVE_STATES.has(config.state));
|
|
73
|
+
const configDocs = await this.loadSyncConfigDefinitions([...stoppedStates, ...liveStates]);
|
|
74
|
+
const stoppedIds = new Set(stoppedStates.map((state) => state._id.toHexString()));
|
|
75
|
+
const liveIds = new Set(liveStates.map((state) => state._id.toHexString()));
|
|
76
|
+
const stoppedConfigDocs = configDocs.filter((config) => stoppedIds.has(config._id.toHexString()));
|
|
77
|
+
const liveConfigDocs = configDocs.filter((config) => liveIds.has(config._id.toHexString()));
|
|
78
|
+
|
|
79
|
+
const stoppedStorageIds = this.storageIdsFor(stoppedConfigDocs);
|
|
80
|
+
const liveStorageIds = this.storageIdsFor(liveConfigDocs);
|
|
81
|
+
const unusedBucketDefinitionIds = difference(
|
|
82
|
+
stoppedStorageIds.bucketDefinitionIds,
|
|
83
|
+
liveStorageIds.bucketDefinitionIds
|
|
84
|
+
);
|
|
85
|
+
const unusedParameterIndexIds = difference(stoppedStorageIds.parameterIndexIds, liveStorageIds.parameterIndexIds);
|
|
86
|
+
|
|
87
|
+
const result: storage.CleanupStoppedSyncConfigsResult = {
|
|
88
|
+
...EMPTY_RESULT
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
if (unusedBucketDefinitionIds.length > 0 || unusedParameterIndexIds.length > 0) {
|
|
92
|
+
await this.cleanupSourceTableMemberships(
|
|
93
|
+
unusedBucketDefinitionIds,
|
|
94
|
+
unusedParameterIndexIds,
|
|
95
|
+
liveConfigDocs,
|
|
96
|
+
result
|
|
97
|
+
);
|
|
98
|
+
result.bucketDataCollectionsDropped = await this.dropBucketDataCollections(unusedBucketDefinitionIds);
|
|
99
|
+
result.bucketStateDocumentsDeleted = await this.deleteBucketStateDocuments(unusedBucketDefinitionIds);
|
|
100
|
+
result.parameterIndexCollectionsDropped = await this.dropParameterIndexCollections(unusedParameterIndexIds);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Event-only source tables carry empty membership arrays, so they are never selected by the
|
|
104
|
+
// membership filter above. Clean them up separately, regardless of whether any bucket or
|
|
105
|
+
// parameter ids became unused (a stopped config may have contributed only an event trigger).
|
|
106
|
+
await this.cleanupEventOnlySourceTables(liveConfigDocs, result);
|
|
107
|
+
|
|
108
|
+
result.stoppedSyncConfigsRemoved = await this.pruneStoppedSyncConfigStates(stoppedStates);
|
|
109
|
+
|
|
110
|
+
if (result.stoppedSyncConfigsRemoved > 0) {
|
|
111
|
+
this.logger.info(
|
|
112
|
+
`Cleaned up ${result.stoppedSyncConfigsRemoved} stopped sync config${result.stoppedSyncConfigsRemoved == 1 ? '' : 's'}`,
|
|
113
|
+
result
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private async loadSyncConfigDefinitions(states: SyncConfigState[]): Promise<SyncConfigDefinition[]> {
|
|
120
|
+
const ids = [...new Map(states.map((state) => [state._id.toHexString(), state._id])).values()];
|
|
121
|
+
if (ids.length == 0) {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
return this.db.syncConfigDefinitions.find({ _id: { $in: ids } }).toArray();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private storageIdsFor(configs: Pick<SyncConfigDefinition, 'rule_mapping'>[]) {
|
|
128
|
+
const mappings = configs.map((config) =>
|
|
129
|
+
SingleSyncConfigBucketDefinitionMapping.fromPersistedMapping(config.rule_mapping)
|
|
130
|
+
);
|
|
131
|
+
return {
|
|
132
|
+
bucketDefinitionIds: [...new Set(mappings.flatMap((mapping) => mapping.allBucketDefinitionIds()))],
|
|
133
|
+
parameterIndexIds: [...new Set(mappings.flatMap((mapping) => mapping.allParameterIndexIds()))]
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async cleanupSourceTableMemberships(
|
|
138
|
+
unusedBucketDefinitionIds: BucketDefinitionId[],
|
|
139
|
+
unusedParameterIndexIds: ParameterIndexId[],
|
|
140
|
+
liveConfigDocs: SyncConfigDefinition[],
|
|
141
|
+
result: storage.CleanupStoppedSyncConfigsResult
|
|
142
|
+
) {
|
|
143
|
+
const update: Record<string, unknown> = {};
|
|
144
|
+
if (unusedBucketDefinitionIds.length > 0) {
|
|
145
|
+
update.bucket_data_source_ids = { $in: unusedBucketDefinitionIds };
|
|
146
|
+
}
|
|
147
|
+
if (unusedParameterIndexIds.length > 0) {
|
|
148
|
+
update.parameter_lookup_source_ids = { $in: unusedParameterIndexIds };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Keep obsolete membership ids as the durable cleanup marker until each source table is
|
|
152
|
+
// either deleted or retained. If interrupted after dropping a source_records collection,
|
|
153
|
+
// the next run can still rediscover the source table from these obsolete ids and retry.
|
|
154
|
+
const filter = this.sourceTableMembershipFilter(unusedBucketDefinitionIds, unusedParameterIndexIds);
|
|
155
|
+
const candidateSourceTables = await this.db
|
|
156
|
+
.sourceTables(this.replicationStreamId)
|
|
157
|
+
.find(filter, {
|
|
158
|
+
projection: {
|
|
159
|
+
_id: 1,
|
|
160
|
+
bucket_data_source_ids: 1,
|
|
161
|
+
parameter_lookup_source_ids: 1,
|
|
162
|
+
schema_name: 1,
|
|
163
|
+
table_name: 1
|
|
164
|
+
}
|
|
165
|
+
})
|
|
166
|
+
.toArray();
|
|
167
|
+
if (candidateSourceTables.length == 0) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const liveSyncConfigs = this.parseSyncConfigs(liveConfigDocs);
|
|
171
|
+
|
|
172
|
+
const deletableSourceTables = candidateSourceTables.filter(
|
|
173
|
+
(sourceTable) =>
|
|
174
|
+
this.membershipsBecomeEmpty(sourceTable, unusedBucketDefinitionIds, unusedParameterIndexIds) &&
|
|
175
|
+
!this.triggersLiveEvent(sourceTable, liveSyncConfigs)
|
|
176
|
+
);
|
|
177
|
+
const retainedSourceTables = candidateSourceTables.filter(
|
|
178
|
+
(sourceTable) => !deletableSourceTables.some((deletable) => deletable._id.equals(sourceTable._id))
|
|
179
|
+
);
|
|
180
|
+
const retainedSourceTableIds = retainedSourceTables.map((sourceTable) => sourceTable._id);
|
|
181
|
+
|
|
182
|
+
await this.deleteSourceTables(
|
|
183
|
+
deletableSourceTables.map((table) => table._id),
|
|
184
|
+
(ids) => this.deletableSourceTableFilter(ids, unusedBucketDefinitionIds, unusedParameterIndexIds),
|
|
185
|
+
result
|
|
186
|
+
);
|
|
187
|
+
|
|
188
|
+
// A retained source table whose memberships become empty is kept alive only by a live event
|
|
189
|
+
// (otherwise it would be deletable). It becomes event-only, and event-only save() never reads
|
|
190
|
+
// or writes current_data, so its source_records collection is now dead weight. Drop it before
|
|
191
|
+
// the $pull below, so the obsolete membership ids remain as a recovery marker if interrupted.
|
|
192
|
+
// Existing source-table docs only ever shrink their memberships, so this table cannot resume
|
|
193
|
+
// data sync on the same doc and need current_data again.
|
|
194
|
+
const becomingEventOnlySourceTableIds = retainedSourceTables
|
|
195
|
+
.filter((sourceTable) =>
|
|
196
|
+
this.membershipsBecomeEmpty(sourceTable, unusedBucketDefinitionIds, unusedParameterIndexIds)
|
|
197
|
+
)
|
|
198
|
+
.map((sourceTable) => sourceTable._id);
|
|
199
|
+
for (const sourceTableId of becomingEventOnlySourceTableIds) {
|
|
200
|
+
this.throwIfAborted();
|
|
201
|
+
await this.dropCollection(this.db.sourceRecords(this.replicationStreamId, sourceTableId));
|
|
202
|
+
result.sourceRecordCollectionsDropped += 1;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (retainedSourceTableIds.length > 0) {
|
|
206
|
+
this.throwIfAborted();
|
|
207
|
+
const updateResult = await this.db.sourceTables(this.replicationStreamId).updateMany(
|
|
208
|
+
{ _id: { $in: retainedSourceTableIds } },
|
|
209
|
+
{
|
|
210
|
+
$pull: update
|
|
211
|
+
},
|
|
212
|
+
{ maxTimeMS: lib_mongo.db.MONGO_CLEAR_OPERATION_TIMEOUT_MS }
|
|
213
|
+
);
|
|
214
|
+
result.sourceTablesUpdated += updateResult.modifiedCount;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Clean up event-only source tables that no live sync config still triggers events for.
|
|
220
|
+
*
|
|
221
|
+
* Event-only source tables carry empty membership arrays (see source-table-utils:
|
|
222
|
+
* "Empty memberships indicate an event-only table"), so the membership filter never selects
|
|
223
|
+
* them. Without this, the source_tables row and its source_records collection leak when the
|
|
224
|
+
* config that contributed the event trigger is stopped.
|
|
225
|
+
*/
|
|
226
|
+
private async cleanupEventOnlySourceTables(
|
|
227
|
+
liveConfigDocs: SyncConfigDefinition[],
|
|
228
|
+
result: storage.CleanupStoppedSyncConfigsResult
|
|
229
|
+
) {
|
|
230
|
+
const candidateSourceTables = await this.db
|
|
231
|
+
.sourceTables(this.replicationStreamId)
|
|
232
|
+
.find(this.eventOnlySourceTableFilter(), {
|
|
233
|
+
projection: {
|
|
234
|
+
_id: 1,
|
|
235
|
+
bucket_data_source_ids: 1,
|
|
236
|
+
parameter_lookup_source_ids: 1,
|
|
237
|
+
schema_name: 1,
|
|
238
|
+
table_name: 1
|
|
239
|
+
}
|
|
240
|
+
})
|
|
241
|
+
.toArray();
|
|
242
|
+
if (candidateSourceTables.length == 0) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const liveSyncConfigs = this.parseSyncConfigs(liveConfigDocs);
|
|
247
|
+
const deletableSourceTableIds = candidateSourceTables
|
|
248
|
+
.filter((sourceTable) => !this.triggersLiveEvent(sourceTable, liveSyncConfigs))
|
|
249
|
+
.map((sourceTable) => sourceTable._id);
|
|
250
|
+
|
|
251
|
+
await this.deleteSourceTables(deletableSourceTableIds, (ids) => this.eventOnlyDeletableFilter(ids), result);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Drop the given source tables and their source_records collections.
|
|
256
|
+
*
|
|
257
|
+
* `refetchFilter` re-applies the deletability predicate against the latest persisted state, so
|
|
258
|
+
* a source table that became live through another writer after planning is not deleted. The
|
|
259
|
+
* sourceRecords collection is dropped before the related sourceTables row, so an interruption
|
|
260
|
+
* can be recovered on the next run.
|
|
261
|
+
*/
|
|
262
|
+
private async deleteSourceTables(
|
|
263
|
+
deletableSourceTableIds: bson.ObjectId[],
|
|
264
|
+
refetchFilter: (ids: bson.ObjectId[]) => Record<string, unknown>,
|
|
265
|
+
result: storage.CleanupStoppedSyncConfigsResult
|
|
266
|
+
) {
|
|
267
|
+
if (deletableSourceTableIds.length == 0) {
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const sourceTablesToDelete = await this.db
|
|
271
|
+
.sourceTables(this.replicationStreamId)
|
|
272
|
+
.find(refetchFilter(deletableSourceTableIds), { projection: { _id: 1 } })
|
|
273
|
+
.toArray();
|
|
274
|
+
|
|
275
|
+
for (const sourceTable of sourceTablesToDelete) {
|
|
276
|
+
this.throwIfAborted();
|
|
277
|
+
await this.dropCollection(this.db.sourceRecords(this.replicationStreamId, sourceTable._id));
|
|
278
|
+
result.sourceRecordCollectionsDropped += 1;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (sourceTablesToDelete.length > 0) {
|
|
282
|
+
this.throwIfAborted();
|
|
283
|
+
const deleteResult = await this.db
|
|
284
|
+
.sourceTables(this.replicationStreamId)
|
|
285
|
+
.deleteMany(refetchFilter(sourceTablesToDelete.map((table) => table._id)), {
|
|
286
|
+
maxTimeMS: lib_mongo.db.MONGO_CLEAR_OPERATION_TIMEOUT_MS
|
|
287
|
+
});
|
|
288
|
+
result.sourceTablesDeleted += deleteResult.deletedCount;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private membershipsBecomeEmpty(
|
|
293
|
+
sourceTable: Pick<SourceTableDocumentV3, 'bucket_data_source_ids' | 'parameter_lookup_source_ids'>,
|
|
294
|
+
unusedBucketDefinitionIds: BucketDefinitionId[],
|
|
295
|
+
unusedParameterIndexIds: ParameterIndexId[]
|
|
296
|
+
): boolean {
|
|
297
|
+
const unusedBucketDefinitionIdSet = new Set(unusedBucketDefinitionIds);
|
|
298
|
+
const unusedParameterIndexIdSet = new Set(unusedParameterIndexIds);
|
|
299
|
+
return (
|
|
300
|
+
sourceTable.bucket_data_source_ids.every((id) => unusedBucketDefinitionIdSet.has(id)) &&
|
|
301
|
+
sourceTable.parameter_lookup_source_ids.every((id) => unusedParameterIndexIdSet.has(id))
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private deletableSourceTableFilter(
|
|
306
|
+
ids: bson.ObjectId[],
|
|
307
|
+
unusedBucketDefinitionIds: BucketDefinitionId[],
|
|
308
|
+
unusedParameterIndexIds: ParameterIndexId[]
|
|
309
|
+
): Record<string, unknown> {
|
|
310
|
+
return {
|
|
311
|
+
_id: { $in: ids },
|
|
312
|
+
bucket_data_source_ids: { $not: { $elemMatch: { $nin: unusedBucketDefinitionIds } } },
|
|
313
|
+
parameter_lookup_source_ids: { $not: { $elemMatch: { $nin: unusedParameterIndexIds } } }
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private eventOnlySourceTableFilter(): Record<string, unknown> {
|
|
318
|
+
return {
|
|
319
|
+
bucket_data_source_ids: { $size: 0 },
|
|
320
|
+
parameter_lookup_source_ids: { $size: 0 }
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private eventOnlyDeletableFilter(ids: bson.ObjectId[]): Record<string, unknown> {
|
|
325
|
+
return {
|
|
326
|
+
_id: { $in: ids },
|
|
327
|
+
...this.eventOnlySourceTableFilter()
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
private parseSyncConfigs(configDocs: SyncConfigDefinition[]): SyncConfig[] {
|
|
332
|
+
// This is ugly - we should not need to re-parse to achieve this.
|
|
333
|
+
// Revisit persistence for this later.
|
|
334
|
+
return configDocs.map((config) => {
|
|
335
|
+
return storage.parsePersistedSyncConfigContent({
|
|
336
|
+
content: config.content,
|
|
337
|
+
compiledPlan: config.serialized_plan ?? null,
|
|
338
|
+
storageVersion: config.storage_version,
|
|
339
|
+
parseOptions: {
|
|
340
|
+
defaultSchema: this.defaultSchema
|
|
341
|
+
}
|
|
342
|
+
}).config;
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
private triggersLiveEvent(sourceTable: SourceTableDocumentV3, liveSyncConfigs: SyncConfig[]): boolean {
|
|
347
|
+
return liveSyncConfigs.some((syncConfig) =>
|
|
348
|
+
syncConfig.tableTriggersEvent({
|
|
349
|
+
connectionTag: this.sourceConnectionTag,
|
|
350
|
+
schema: sourceTable.schema_name,
|
|
351
|
+
name: sourceTable.table_name
|
|
352
|
+
})
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
private sourceTableMembershipFilter(
|
|
357
|
+
bucketDefinitionIds: BucketDefinitionId[],
|
|
358
|
+
parameterIndexIds: ParameterIndexId[]
|
|
359
|
+
): Partial<SourceTableDocumentV3> | Record<string, unknown> {
|
|
360
|
+
const clauses: Record<string, unknown>[] = [];
|
|
361
|
+
if (bucketDefinitionIds.length > 0) {
|
|
362
|
+
clauses.push({ bucket_data_source_ids: { $in: bucketDefinitionIds } });
|
|
363
|
+
}
|
|
364
|
+
if (parameterIndexIds.length > 0) {
|
|
365
|
+
clauses.push({ parameter_lookup_source_ids: { $in: parameterIndexIds } });
|
|
366
|
+
}
|
|
367
|
+
if (clauses.length == 0) {
|
|
368
|
+
return { _id: { $exists: false } };
|
|
369
|
+
}
|
|
370
|
+
return { $or: clauses };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private async dropBucketDataCollections(definitionIds: BucketDefinitionId[]): Promise<number> {
|
|
374
|
+
for (const definitionId of definitionIds) {
|
|
375
|
+
this.throwIfAborted();
|
|
376
|
+
await this.dropCollection(this.db.bucketData(this.replicationStreamId, definitionId));
|
|
377
|
+
}
|
|
378
|
+
return definitionIds.length;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Delete bucket_state documents for the unused bucket definitions.
|
|
383
|
+
*
|
|
384
|
+
* The bucket_state collection is shared across all bucket definitions of the
|
|
385
|
+
* stream (keyed by `_id`, an ordered `{ d, b }` compound), so we delete the individual documents.
|
|
386
|
+
*
|
|
387
|
+
* There can be hundreds of millions of buckets, so we delete per definition using a range filter
|
|
388
|
+
* on `_id` (which uses the `_id` index) rather than a slow `_id.d` field scan, and retry on
|
|
389
|
+
* MaxTimeMSExpired so each call makes progress in batches.
|
|
390
|
+
*/
|
|
391
|
+
private async deleteBucketStateDocuments(definitionIds: BucketDefinitionId[]): Promise<number> {
|
|
392
|
+
const collection = this.db.bucketState(this.replicationStreamId);
|
|
393
|
+
let deletedCount = 0;
|
|
394
|
+
for (const definitionId of definitionIds) {
|
|
395
|
+
this.throwIfAborted();
|
|
396
|
+
const result = await retryOnMongoMaxTimeMSExpired(
|
|
397
|
+
() =>
|
|
398
|
+
collection.deleteMany(
|
|
399
|
+
{
|
|
400
|
+
_id: idPrefixFilter<BucketStateDocumentV3['_id']>({ d: definitionId }, ['b'])
|
|
401
|
+
},
|
|
402
|
+
{ maxTimeMS: lib_mongo.db.MONGO_CLEAR_OPERATION_TIMEOUT_MS }
|
|
403
|
+
),
|
|
404
|
+
{
|
|
405
|
+
signal: this.signal,
|
|
406
|
+
abortMessage: 'Aborted stopped sync config cleanup',
|
|
407
|
+
retryDelayMs: lib_mongo.db.MONGO_CLEAR_OPERATION_TIMEOUT_MS / 5,
|
|
408
|
+
onRetry: () => {
|
|
409
|
+
this.logger.info(
|
|
410
|
+
`Cleared batch of bucket state in ${lib_mongo.db.MONGO_CLEAR_OPERATION_TIMEOUT_MS}ms, continuing...`
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
);
|
|
415
|
+
deletedCount += result.deletedCount;
|
|
416
|
+
}
|
|
417
|
+
return deletedCount;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private async dropParameterIndexCollections(indexIds: ParameterIndexId[]): Promise<number> {
|
|
421
|
+
for (const indexId of indexIds) {
|
|
422
|
+
this.throwIfAborted();
|
|
423
|
+
await this.dropCollection(this.db.parameterIndex(this.replicationStreamId, indexId));
|
|
424
|
+
}
|
|
425
|
+
return indexIds.length;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
private async dropCollection<T extends lib_mongo.mongo.Document>(
|
|
429
|
+
collection: lib_mongo.mongo.Collection<T>
|
|
430
|
+
): Promise<void> {
|
|
431
|
+
await collection.drop({ maxTimeMS: lib_mongo.db.MONGO_CLEAR_OPERATION_TIMEOUT_MS }).catch((error) => {
|
|
432
|
+
if (lib_mongo.isMongoServerError(error) && error.codeName === 'NamespaceNotFound') {
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
throw error;
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private async pruneStoppedSyncConfigStates(stoppedStates: SyncConfigState[]): Promise<number> {
|
|
440
|
+
this.throwIfAborted();
|
|
441
|
+
const stoppedIds = stoppedStates.map((state) => state._id);
|
|
442
|
+
const result = await this.db.sync_rules.updateOne(
|
|
443
|
+
{
|
|
444
|
+
_id: this.replicationStreamId,
|
|
445
|
+
sync_configs: {
|
|
446
|
+
$not: {
|
|
447
|
+
$elemMatch: {
|
|
448
|
+
_id: { $in: stoppedIds },
|
|
449
|
+
state: { $ne: storage.SyncRuleState.STOP }
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
},
|
|
454
|
+
{
|
|
455
|
+
$pull: {
|
|
456
|
+
sync_configs: {
|
|
457
|
+
_id: { $in: stoppedIds },
|
|
458
|
+
state: storage.SyncRuleState.STOP
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
} as bson.Document
|
|
462
|
+
);
|
|
463
|
+
if (result.modifiedCount == 0 && stoppedIds.length > 0) {
|
|
464
|
+
this.logger.warn(`Skipped pruning stopped sync configs`);
|
|
465
|
+
return 0;
|
|
466
|
+
}
|
|
467
|
+
return stoppedStates.length;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
private throwIfAborted() {
|
|
471
|
+
if (this.signal?.aborted) {
|
|
472
|
+
throw new ReplicationAbortedError('Aborted stopped sync config cleanup', this.signal.reason);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function difference<T>(left: T[], right: T[]): T[] {
|
|
478
|
+
const rightSet = new Set(right);
|
|
479
|
+
return left.filter((value) => !rightSet.has(value));
|
|
480
|
+
}
|