@powersync/service-module-mongodb-storage 0.20.0 → 0.22.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.
- package/CHANGELOG.md +62 -0
- package/dist/storage/MongoBucketStorage.d.ts +36 -3
- package/dist/storage/MongoBucketStorage.js +372 -207
- package/dist/storage/MongoBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoBucketBatch.d.ts +17 -5
- package/dist/storage/implementation/MongoBucketBatch.js +44 -17
- package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
- package/dist/storage/implementation/MongoCompactor.d.ts +19 -79
- package/dist/storage/implementation/MongoCompactor.js +27 -238
- package/dist/storage/implementation/MongoCompactor.js.map +1 -1
- package/dist/storage/implementation/MongoParameterCompactor.d.ts +83 -10
- package/dist/storage/implementation/MongoParameterCompactor.js +309 -96
- package/dist/storage/implementation/MongoParameterCompactor.js.map +1 -1
- package/dist/storage/implementation/MongoParsedSyncConfigSet.d.ts +9 -1
- package/dist/storage/implementation/MongoParsedSyncConfigSet.js +29 -0
- package/dist/storage/implementation/MongoParsedSyncConfigSet.js.map +1 -1
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.js +4 -2
- package/dist/storage/implementation/MongoPersistedSyncConfigContent.js.map +1 -1
- package/dist/storage/implementation/MongoStorageProvider.js +7 -3
- package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
- package/dist/storage/implementation/MongoSyncBucketStorage.d.ts +27 -11
- package/dist/storage/implementation/MongoSyncBucketStorage.js +78 -31
- package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.js +21 -9
- package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
- package/dist/storage/implementation/MongoWriteBatch.d.ts +49 -0
- package/dist/storage/implementation/MongoWriteBatch.js +149 -0
- package/dist/storage/implementation/MongoWriteBatch.js.map +1 -0
- package/dist/storage/implementation/MongoWriteCheckpointAPI.d.ts +9 -7
- package/dist/storage/implementation/MongoWriteCheckpointAPI.js +9 -30
- package/dist/storage/implementation/MongoWriteCheckpointAPI.js.map +1 -1
- package/dist/storage/implementation/SyncRuleStateUpdate.d.ts +11 -5
- package/dist/storage/implementation/SyncRuleStateUpdate.js +14 -6
- package/dist/storage/implementation/SyncRuleStateUpdate.js.map +1 -1
- package/dist/storage/implementation/common/MongoSyncBucketStorageCheckpoint.d.ts +22 -2
- package/dist/storage/implementation/common/PersistedBatch.d.ts +32 -4
- package/dist/storage/implementation/common/PersistedBatch.js +49 -6
- package/dist/storage/implementation/common/PersistedBatch.js.map +1 -1
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.d.ts +3 -0
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js +3 -0
- package/dist/storage/implementation/common/VersionedPowerSyncMongoBase.js.map +1 -1
- package/dist/storage/implementation/db.d.ts +9 -1
- package/dist/storage/implementation/db.js +27 -1
- package/dist/storage/implementation/db.js.map +1 -1
- package/dist/storage/implementation/models.d.ts +31 -0
- package/dist/storage/implementation/models.js.map +1 -1
- package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +2 -0
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js +33 -4
- package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoCompactorV1.d.ts +38 -6
- package/dist/storage/implementation/v1/MongoCompactorV1.js +247 -20
- package/dist/storage/implementation/v1/MongoCompactorV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoParameterCompactorV1.d.ts +16 -2
- package/dist/storage/implementation/v1/MongoParameterCompactorV1.js +20 -9
- package/dist/storage/implementation/v1/MongoParameterCompactorV1.js.map +1 -1
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.d.ts +18 -11
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js +65 -16
- package/dist/storage/implementation/v1/MongoSyncBucketStorageV1.js.map +1 -1
- package/dist/storage/implementation/v1/PersistedBatchV1.d.ts +7 -5
- package/dist/storage/implementation/v1/PersistedBatchV1.js +22 -28
- package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
- package/dist/storage/implementation/v1/models.js +1 -0
- package/dist/storage/implementation/v1/models.js.map +1 -1
- package/dist/storage/implementation/v3/CompactionLease.d.ts +50 -0
- package/dist/storage/implementation/v3/CompactionLease.js +131 -0
- package/dist/storage/implementation/v3/CompactionLease.js.map +1 -0
- package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +10 -2
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js +100 -26
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +82 -25
- package/dist/storage/implementation/v3/MongoCompactorV3.js +698 -159
- package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.d.ts +18 -0
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.js +23 -0
- package/dist/storage/implementation/v3/MongoParameterCompactorV3.js.map +1 -0
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.d.ts +2 -15
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js +60 -92
- package/dist/storage/implementation/v3/MongoStoppedSyncConfigCleanup.js.map +1 -1
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.d.ts +19 -9
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js +91 -31
- package/dist/storage/implementation/v3/MongoSyncBucketStorageV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.d.ts +26 -0
- package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js +82 -0
- package/dist/storage/implementation/v3/MongoWriteCheckpointAPIV3.js.map +1 -0
- package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -8
- package/dist/storage/implementation/v3/PersistedBatchV3.js +76 -42
- package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.d.ts +12 -2
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js +42 -3
- package/dist/storage/implementation/v3/VersionedPowerSyncMongoV3.js.map +1 -1
- package/dist/storage/implementation/v3/bucket-format.js +2 -0
- package/dist/storage/implementation/v3/bucket-format.js.map +1 -1
- package/dist/storage/implementation/v3/compact-utils.d.ts +107 -0
- package/dist/storage/implementation/v3/compact-utils.js +216 -0
- package/dist/storage/implementation/v3/compact-utils.js.map +1 -0
- package/dist/storage/implementation/v3/compaction-constants.d.ts +5 -0
- package/dist/storage/implementation/v3/compaction-constants.js +6 -0
- package/dist/storage/implementation/v3/compaction-constants.js.map +1 -0
- package/dist/storage/implementation/v3/models.d.ts +84 -4
- package/dist/storage/implementation/v3/models.js.map +1 -1
- package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.d.ts +7 -8
- package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js +16 -5
- package/dist/storage/implementation/v3/object-storage/BucketDataObjectStorage.js.map +1 -1
- package/dist/storage/implementation/v3/object-storage/ObjectStorage.d.ts +14 -11
- package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.d.ts +6 -8
- package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js +17 -11
- package/dist/storage/implementation/v3/object-storage/ObjectStorageLifecycle.js.map +1 -1
- package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.d.ts +38 -0
- package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js +164 -0
- package/dist/storage/implementation/v3/object-storage/ObjectStorageUsage.js.map +1 -0
- package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.d.ts +37 -12
- package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js +197 -25
- package/dist/storage/implementation/v3/object-storage/S3ObjectStorage.js.map +1 -1
- package/dist/storage/implementation/v3/source-table-utils.d.ts +6 -6
- package/dist/storage/implementation/v3/source-table-utils.js +30 -37
- package/dist/storage/implementation/v3/source-table-utils.js.map +1 -1
- package/dist/storage/storage-index.d.ts +2 -1
- package/dist/storage/storage-index.js +1 -0
- package/dist/storage/storage-index.js.map +1 -1
- package/dist/types/types.d.ts +28 -1
- package/dist/types/types.js +28 -7
- package/dist/types/types.js.map +1 -1
- package/dist/utils/test-utils.js +1 -0
- package/dist/utils/test-utils.js.map +1 -1
- package/dist/utils/util.js +3 -1
- package/dist/utils/util.js.map +1 -1
- package/package.json +10 -9
- package/src/storage/MongoBucketStorage.ts +507 -269
- package/src/storage/implementation/MongoBucketBatch.ts +67 -24
- package/src/storage/implementation/MongoCompactor.ts +35 -346
- package/src/storage/implementation/MongoParameterCompactor.ts +388 -102
- package/src/storage/implementation/MongoParsedSyncConfigSet.ts +34 -0
- package/src/storage/implementation/MongoPersistedSyncConfigContent.ts +4 -2
- package/src/storage/implementation/MongoStorageProvider.ts +15 -3
- package/src/storage/implementation/MongoSyncBucketStorage.ts +114 -40
- package/src/storage/implementation/MongoSyncRulesLock.ts +22 -9
- package/src/storage/implementation/MongoWriteBatch.ts +172 -0
- package/src/storage/implementation/MongoWriteCheckpointAPI.ts +16 -46
- package/src/storage/implementation/SyncRuleStateUpdate.ts +13 -6
- package/src/storage/implementation/common/MongoSyncBucketStorageCheckpoint.ts +24 -2
- package/src/storage/implementation/common/PersistedBatch.ts +66 -10
- package/src/storage/implementation/common/VersionedPowerSyncMongoBase.ts +4 -0
- package/src/storage/implementation/db.ts +35 -2
- package/src/storage/implementation/models.ts +34 -0
- package/src/storage/implementation/v1/MongoBucketBatchV1.ts +46 -6
- package/src/storage/implementation/v1/MongoCompactorV1.ts +327 -40
- package/src/storage/implementation/v1/MongoParameterCompactorV1.ts +25 -9
- package/src/storage/implementation/v1/MongoSyncBucketStorageV1.ts +87 -27
- package/src/storage/implementation/v1/PersistedBatchV1.ts +25 -30
- package/src/storage/implementation/v1/models.ts +1 -0
- package/src/storage/implementation/v3/CompactionLease.ts +152 -0
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +138 -34
- package/src/storage/implementation/v3/MongoCompactorV3.ts +958 -225
- package/src/storage/implementation/v3/MongoParameterCompactorV3.ts +34 -0
- package/src/storage/implementation/v3/MongoStoppedSyncConfigCleanup.ts +100 -109
- package/src/storage/implementation/v3/MongoSyncBucketStorageV3.ts +111 -41
- package/src/storage/implementation/v3/MongoWriteCheckpointAPIV3.ts +111 -0
- package/src/storage/implementation/v3/PersistedBatchV3.ts +93 -48
- package/src/storage/implementation/v3/VersionedPowerSyncMongoV3.ts +55 -4
- package/src/storage/implementation/v3/bucket-format.ts +2 -0
- package/src/storage/implementation/v3/compact-utils.ts +320 -0
- package/src/storage/implementation/v3/compaction-constants.ts +5 -0
- package/src/storage/implementation/v3/models.ts +91 -3
- package/src/storage/implementation/v3/object-storage/BucketDataObjectStorage.ts +24 -9
- package/src/storage/implementation/v3/object-storage/ObjectStorage.ts +20 -5
- package/src/storage/implementation/v3/object-storage/ObjectStorageLifecycle.ts +26 -14
- package/src/storage/implementation/v3/object-storage/ObjectStorageUsage.ts +229 -0
- package/src/storage/implementation/v3/object-storage/S3ObjectStorage.ts +279 -29
- package/src/storage/implementation/v3/source-table-utils.ts +39 -41
- package/src/storage/storage-index.ts +2 -0
- package/src/types/types.ts +42 -7
- package/src/utils/test-utils.ts +1 -0
- package/src/utils/util.ts +3 -1
- package/test/src/__snapshots__/storage.test.ts.snap +25 -0
- package/test/src/__snapshots__/storage_sync.test.ts.snap +605 -16
- package/test/src/chunk_compaction_config.test.ts +38 -0
- package/test/src/cleanup-stopped-sync-configs.test.ts +40 -13
- package/test/src/compact-utils.test.ts +226 -0
- package/test/src/helpers/MemoryObjectStorage.ts +14 -6
- package/test/src/object_storage_usage.test.ts +267 -0
- package/test/src/parameter_compacting_v1.test.ts +120 -0
- package/test/src/parameter_compacting_v3.test.ts +192 -0
- package/test/src/parameter_compaction_fence.test.ts +276 -0
- package/test/src/storage.test.ts +273 -22
- package/test/src/storage_compacting.test.ts +968 -246
- package/test/src/storage_s3_checksums.test.ts +3 -4
- package/test/src/storage_s3_compaction_lifecycle.test.ts +138 -12
- package/test/src/storage_s3_reading.test.ts +290 -2
- package/test/src/storage_s3_writing.test.ts +1 -0
- package/test/src/storage_sync.test.ts +336 -41
- package/test/src/util.ts +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import * as lib_mongo from '@powersync/lib-service-mongodb';
|
|
2
|
+
import { mongo } from '@powersync/lib-service-mongodb';
|
|
3
|
+
import { ReplicationAssertionError } from '@powersync/lib-services-framework';
|
|
4
|
+
import { BucketDefinitionId } from '@powersync/service-sync-rules';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { MongoWriteBatch } from '../../MongoWriteBatch.js';
|
|
7
|
+
import { BucketDataDocumentV3, ObjectStorageUsageDocument } from '../models.js';
|
|
8
|
+
import { VersionedPowerSyncMongoV3 } from '../VersionedPowerSyncMongoV3.js';
|
|
9
|
+
|
|
10
|
+
export const OBJECT_STORAGE_USAGE_BASE_WRITER_ID = '__base__';
|
|
11
|
+
export const DEFAULT_OBJECT_STORAGE_USAGE_STALE_WRITER_MS = 30 * 60 * 1000;
|
|
12
|
+
export const DEFAULT_OBJECT_STORAGE_USAGE_FOLD_LIMIT = 100;
|
|
13
|
+
|
|
14
|
+
export interface ReplicationStreamObjectStorageDefinitionUsageResult {
|
|
15
|
+
replication_stream_id: number;
|
|
16
|
+
definition_id: BucketDefinitionId;
|
|
17
|
+
active_bytes: bigint;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createObjectStorageUsageWriterId(): string {
|
|
21
|
+
return randomUUID();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Tracks active S3 references. Values are signed writer-local deltas, so reference changes and
|
|
26
|
+
* accounting updates can be committed together without making replication and compaction share a
|
|
27
|
+
* hot counter document.
|
|
28
|
+
*/
|
|
29
|
+
export class ObjectStorageUsage {
|
|
30
|
+
constructor(
|
|
31
|
+
private readonly db: VersionedPowerSyncMongoV3,
|
|
32
|
+
private readonly replicationStreamId: number,
|
|
33
|
+
readonly writerId?: string
|
|
34
|
+
) {
|
|
35
|
+
if (writerId === OBJECT_STORAGE_USAGE_BASE_WRITER_ID) {
|
|
36
|
+
throw new ReplicationAssertionError('The reserved object-storage usage writer id cannot be used by a writer');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static bytes(document: Pick<BucketDataDocumentV3, 'storage_ref'>): bigint {
|
|
41
|
+
return BigInt(document.storage_ref?.file_size ?? 0);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
static async readAllDefinitionUsage(
|
|
45
|
+
db: VersionedPowerSyncMongoV3
|
|
46
|
+
): Promise<ReplicationStreamObjectStorageDefinitionUsageResult[]> {
|
|
47
|
+
return db.client.withSession({ snapshot: true }, async (session) => {
|
|
48
|
+
// Deliberately read the whole usage collection. The number of replication streams is
|
|
49
|
+
// expected to stay low, so a collection scan is cheaper than issuing one _id range query
|
|
50
|
+
// per stream (and the usage collection is bounded by streams and writers, not buckets).
|
|
51
|
+
const entries = await db.objectStorageUsage
|
|
52
|
+
.aggregate<{
|
|
53
|
+
_id: { replication_stream_id: number; definition_id: BucketDefinitionId };
|
|
54
|
+
active_bytes: bigint;
|
|
55
|
+
}>(
|
|
56
|
+
[
|
|
57
|
+
{ $project: { replication_stream_id: '$_id.g', definitions: { $objectToArray: '$definitions' } } },
|
|
58
|
+
{ $unwind: '$definitions' },
|
|
59
|
+
{
|
|
60
|
+
$group: {
|
|
61
|
+
_id: {
|
|
62
|
+
replication_stream_id: '$replication_stream_id',
|
|
63
|
+
definition_id: '$definitions.k'
|
|
64
|
+
},
|
|
65
|
+
active_bytes: { $sum: '$definitions.v' }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
],
|
|
69
|
+
{ session, readConcern: 'snapshot' }
|
|
70
|
+
)
|
|
71
|
+
.toArray()
|
|
72
|
+
.catch((error) => {
|
|
73
|
+
if (lib_mongo.isMongoNamespaceNotFoundError(error)) {
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
throw error;
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
return entries.map((entry) => {
|
|
80
|
+
const activeBytes = BigInt(entry.active_bytes ?? 0);
|
|
81
|
+
if (activeBytes < 0n) {
|
|
82
|
+
return {
|
|
83
|
+
replication_stream_id: entry._id.replication_stream_id,
|
|
84
|
+
definition_id: entry._id.definition_id,
|
|
85
|
+
active_bytes: 0n
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
replication_stream_id: entry._id.replication_stream_id,
|
|
90
|
+
definition_id: entry._id.definition_id,
|
|
91
|
+
active_bytes: activeBytes
|
|
92
|
+
};
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
applyDelta(definitionId: BucketDefinitionId, delta: bigint, writes: MongoWriteBatch): void {
|
|
98
|
+
this.applyDeltas(new Map([[definitionId, delta]]), writes);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
applyDeltas(deltas: ReadonlyMap<BucketDefinitionId, bigint>, writes: MongoWriteBatch): void {
|
|
102
|
+
if (this.writerId == null) {
|
|
103
|
+
throw new ReplicationAssertionError('A writer id is required to apply object-storage usage');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const increments: Record<string, bigint> = {};
|
|
107
|
+
for (const [definitionId, delta] of deltas) {
|
|
108
|
+
if (delta === 0n) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
increments[this.definitionPath(definitionId)] = delta;
|
|
112
|
+
}
|
|
113
|
+
if (Object.keys(increments).length === 0) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
writes.updateOne(
|
|
118
|
+
this.db.objectStorageUsage,
|
|
119
|
+
{ _id: this.documentId() },
|
|
120
|
+
{ $inc: increments, $currentDate: { updated_at: true } },
|
|
121
|
+
{ upsert: true }
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async removeDefinition(definitionId: BucketDefinitionId, session: mongo.ClientSession): Promise<void> {
|
|
126
|
+
await this.db.objectStorageUsage.updateMany(
|
|
127
|
+
{ '_id.g': this.replicationStreamId },
|
|
128
|
+
{ $unset: { [this.definitionPath(definitionId)]: 1 } },
|
|
129
|
+
{ session }
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async removeStream(session: mongo.ClientSession): Promise<void> {
|
|
134
|
+
await this.db.objectStorageUsage.deleteMany({ '_id.g': this.replicationStreamId }, { session });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async foldStaleWriterDeltas(
|
|
138
|
+
options: {
|
|
139
|
+
staleWriterMs?: number;
|
|
140
|
+
limit?: number;
|
|
141
|
+
} = {}
|
|
142
|
+
): Promise<void> {
|
|
143
|
+
const staleWriterMs = options.staleWriterMs ?? DEFAULT_OBJECT_STORAGE_USAGE_STALE_WRITER_MS;
|
|
144
|
+
const limit = options.limit ?? DEFAULT_OBJECT_STORAGE_USAGE_FOLD_LIMIT;
|
|
145
|
+
if (limit <= 0) {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
await this.db.client.withSession((session) =>
|
|
150
|
+
session.withTransaction(
|
|
151
|
+
async () => {
|
|
152
|
+
const staleDocuments = await this.db.objectStorageUsage
|
|
153
|
+
.find(
|
|
154
|
+
{
|
|
155
|
+
'_id.g': this.replicationStreamId,
|
|
156
|
+
'_id.w': { $ne: OBJECT_STORAGE_USAGE_BASE_WRITER_ID },
|
|
157
|
+
$expr: {
|
|
158
|
+
$lt: [
|
|
159
|
+
'$updated_at',
|
|
160
|
+
{ $dateSubtract: { startDate: '$$NOW', unit: 'millisecond', amount: staleWriterMs } }
|
|
161
|
+
]
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
{ session, sort: { updated_at: 1 }, limit }
|
|
165
|
+
)
|
|
166
|
+
.toArray();
|
|
167
|
+
if (staleDocuments.length === 0) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const deltas = new Map<BucketDefinitionId, bigint>();
|
|
172
|
+
for (const document of staleDocuments) {
|
|
173
|
+
for (const [definitionId, delta] of Object.entries(document.definitions ?? {})) {
|
|
174
|
+
this.validateDefinitionId(definitionId);
|
|
175
|
+
deltas.set(definitionId, (deltas.get(definitionId) ?? 0n) + BigInt(delta));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const increments: Record<string, bigint> = {};
|
|
180
|
+
for (const [definitionId, delta] of deltas) {
|
|
181
|
+
if (delta !== 0n) {
|
|
182
|
+
increments[this.definitionPath(definitionId)] = delta;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (Object.keys(increments).length > 0) {
|
|
186
|
+
await this.db.objectStorageUsage.updateOne(
|
|
187
|
+
{ _id: this.documentId(OBJECT_STORAGE_USAGE_BASE_WRITER_ID) },
|
|
188
|
+
{
|
|
189
|
+
$inc: increments,
|
|
190
|
+
$currentDate: { updated_at: true }
|
|
191
|
+
},
|
|
192
|
+
{ upsert: true, session }
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
await this.db.objectStorageUsage.deleteMany(
|
|
197
|
+
{
|
|
198
|
+
'_id.g': this.replicationStreamId,
|
|
199
|
+
_id: { $in: staleDocuments.map((document) => document._id) }
|
|
200
|
+
},
|
|
201
|
+
{ session }
|
|
202
|
+
);
|
|
203
|
+
},
|
|
204
|
+
{ readConcern: { level: 'snapshot' }, writeConcern: { w: 'majority' } }
|
|
205
|
+
)
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private definitionPath(definitionId: BucketDefinitionId): string {
|
|
210
|
+
this.validateDefinitionId(definitionId);
|
|
211
|
+
return `definitions.${definitionId}`;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private documentId(writerId = this.writerId): ObjectStorageUsageDocument['_id'] {
|
|
215
|
+
if (writerId == null) {
|
|
216
|
+
throw new ReplicationAssertionError('A writer id is required to identify object-storage usage');
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
g: this.replicationStreamId,
|
|
220
|
+
w: writerId
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private validateDefinitionId(definitionId: BucketDefinitionId): void {
|
|
225
|
+
if (definitionId.length === 0 || definitionId.includes('.') || definitionId.includes('$')) {
|
|
226
|
+
throw new ReplicationAssertionError(`Invalid bucket definition id for object-storage usage: ${definitionId}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -6,20 +6,174 @@ import {
|
|
|
6
6
|
PutObjectCommand,
|
|
7
7
|
S3Client
|
|
8
8
|
} from '@aws-sdk/client-s3';
|
|
9
|
+
import { logger } from '@powersync/lib-services-framework';
|
|
9
10
|
import { acquireSemaphoreAbortable, isAbortError } from '@powersync/service-core';
|
|
11
|
+
import { loadConfigsForDefaultMode, type DefaultsMode, type ResolvedDefaultsMode } from '@smithy/core/client';
|
|
10
12
|
import { isThrottlingError, isTransientError } from '@smithy/core/retry';
|
|
13
|
+
import { NodeHttpHandler } from '@smithy/node-http-handler';
|
|
11
14
|
import { Semaphore, SemaphoreInterface } from 'async-mutex';
|
|
12
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
ObjectStorageError,
|
|
17
|
+
type ObjectStorage,
|
|
18
|
+
type ObjectStorageOperationOptions,
|
|
19
|
+
type ObjectStoragePutMetadata
|
|
20
|
+
} from './ObjectStorage.js';
|
|
21
|
+
|
|
22
|
+
// Never statically import (or re-export) this module!
|
|
23
|
+
// We want to avoid loading the AWS SDK unless the user has configured S3 object storage, since it's a large dependency.
|
|
13
24
|
|
|
14
|
-
const DEFAULT_S3_OPERATION_CONCURRENCY =
|
|
25
|
+
const DEFAULT_S3_OPERATION_CONCURRENCY = 64;
|
|
15
26
|
const S3_DELETE_PREFIX_BATCH_SIZE = 1000;
|
|
16
27
|
/**
|
|
17
|
-
*
|
|
28
|
+
* Keep prefix deletion below the default shared limit to leave capacity for other operations.
|
|
18
29
|
*/
|
|
19
30
|
const S3_DELETE_PREFIX_CONCURRENCY = 12;
|
|
20
31
|
const MAX_S3_PREFIX_BYTES = 256;
|
|
21
32
|
const SAFE_S3_KEY_BYTES = 896;
|
|
22
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Timeouts are derived from the AWS defaults mode, rather than being individually configurable.
|
|
36
|
+
*
|
|
37
|
+
* The mode - AWS_DEFAULTS_MODE or the defaults_mode storage option - describes the expected latency
|
|
38
|
+
* between this service and the object storage endpoint. We use the connection timeout it defines
|
|
39
|
+
* as the baseline for the other timeouts:
|
|
40
|
+
*
|
|
41
|
+
* | mode | connection | request | operation | queue |
|
|
42
|
+
* | ---------------------- | ---------- | ------- | --------- | ----- |
|
|
43
|
+
* | in-region | 1.1s | 5.5s | 11s | 44s |
|
|
44
|
+
* | standard, cross-region | 3.1s | 15.5s | 31s | 124s |
|
|
45
|
+
* | mobile | 30s | 150s | 300s | 1200s |
|
|
46
|
+
*
|
|
47
|
+
* The multipliers are sized for the objects we store: bucket data chunks target 1MB, and are
|
|
48
|
+
* bounded by the 16MB BSON document limit. Even at the upper bound, the request timeout only has to
|
|
49
|
+
* cover a transfer of a few MB/s, and the operation timeout leaves room for a second attempt.
|
|
50
|
+
*
|
|
51
|
+
* `legacy`, the mode used when nothing is configured, does not define any timeouts, and is treated
|
|
52
|
+
* as `standard` here. Running without timeouts is not an option: a stalled request holds one of the
|
|
53
|
+
* limited operation slots until the process restarts, and enough of those block all reads.
|
|
54
|
+
*
|
|
55
|
+
* `auto` is also treated as `standard` - see resolveConfiguredDefaultsMode() below.
|
|
56
|
+
*/
|
|
57
|
+
const BASELINE_CONNECTION_TIMEOUT_MS = 3_100;
|
|
58
|
+
const REQUEST_TIMEOUT_FACTOR = 5;
|
|
59
|
+
const OPERATION_TIMEOUT_FACTOR = 2;
|
|
60
|
+
/**
|
|
61
|
+
* Don't keep idle http sockets around for longer than this timeout.
|
|
62
|
+
*
|
|
63
|
+
* This covers the case where we have large bursts of activity during replication, followed by
|
|
64
|
+
* long periods of inactivity.
|
|
65
|
+
*/
|
|
66
|
+
const SOCKET_IDLE_TIMEOUT_MS = 60_000;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* How long an operation may wait for a concurrency slot, as a multiple of the operation timeout.
|
|
70
|
+
*
|
|
71
|
+
* Every slot holder now releases within the operation timeout, so the queue always drains: this is
|
|
72
|
+
* a backpressure limit rather than a deadlock guard. Waiting this long means at least
|
|
73
|
+
* `factor * concurrencyLimit` operations ahead of us each took their full deadline - 256 at the
|
|
74
|
+
* default concurrency. Real operations complete in a fraction of the deadline, so the number of
|
|
75
|
+
* queued operations this actually tolerates is far higher, well above the ~2000 uploads that the
|
|
76
|
+
* largest possible replication flush (MAX_TRANSACTION_DOC_COUNT) can enqueue at once.
|
|
77
|
+
*/
|
|
78
|
+
const QUEUE_TIMEOUT_FACTOR = 4;
|
|
79
|
+
|
|
80
|
+
export interface S3TimeoutProfile {
|
|
81
|
+
/**
|
|
82
|
+
* Per attempt: establishing the connection, including waiting for a socket from the pool.
|
|
83
|
+
*/
|
|
84
|
+
connectionTimeoutMs: number;
|
|
85
|
+
/**
|
|
86
|
+
* Per attempt: from starting the request until the response headers are received. For uploads
|
|
87
|
+
* this includes sending the body.
|
|
88
|
+
*/
|
|
89
|
+
requestTimeoutMs: number;
|
|
90
|
+
/**
|
|
91
|
+
* The complete operation, including SDK retries and streaming the response body.
|
|
92
|
+
*
|
|
93
|
+
* The SDK timeouts above stop applying once the response headers are received, so this is what
|
|
94
|
+
* bounds how long a single operation can occupy a concurrency slot.
|
|
95
|
+
*/
|
|
96
|
+
operationTimeoutMs: number;
|
|
97
|
+
/**
|
|
98
|
+
* Waiting for a concurrency slot, before the operation itself starts.
|
|
99
|
+
*/
|
|
100
|
+
queueTimeoutMs: number;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function resolveTimeoutProfile(mode: ResolvedDefaultsMode): S3TimeoutProfile {
|
|
104
|
+
// Only connectionTimeout is currently vended by the SDK, but requestTimeout is part of the same
|
|
105
|
+
// contract - use it as the hint if a future version starts defining it.
|
|
106
|
+
const { connectionTimeout, requestTimeout } = loadConfigsForDefaultMode(mode);
|
|
107
|
+
const connectionTimeoutMs = connectionTimeout ?? BASELINE_CONNECTION_TIMEOUT_MS;
|
|
108
|
+
const requestTimeoutMs = requestTimeout ?? connectionTimeoutMs * REQUEST_TIMEOUT_FACTOR;
|
|
109
|
+
const operationTimeoutMs = requestTimeoutMs * OPERATION_TIMEOUT_FACTOR;
|
|
110
|
+
return {
|
|
111
|
+
connectionTimeoutMs,
|
|
112
|
+
requestTimeoutMs,
|
|
113
|
+
operationTimeoutMs,
|
|
114
|
+
queueTimeoutMs: operationTimeoutMs * QUEUE_TIMEOUT_FACTOR
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const AWS_DEFAULTS_MODE_ENV = 'AWS_DEFAULTS_MODE';
|
|
119
|
+
const RESOLVED_DEFAULTS_MODES: ResolvedDefaultsMode[] = ['standard', 'in-region', 'cross-region', 'mobile', 'legacy'];
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Resolve the configured AWS defaults mode: the explicit option, then the AWS_DEFAULTS_MODE
|
|
123
|
+
* environment variable, then `legacy`, which is also the AWS default.
|
|
124
|
+
*
|
|
125
|
+
* Unlike the SDK's own lookup, this does not read defaults_mode from the AWS shared config file.
|
|
126
|
+
* That lookup is asynchronous, and the mode is only used to pick timeouts, which we want available
|
|
127
|
+
* synchronously so that operations never have to wait on configuration.
|
|
128
|
+
*
|
|
129
|
+
* `auto` is substituted with `standard`. It asks the SDK to detect whether it is running in the
|
|
130
|
+
* same region as the endpoint, which means querying the EC2 instance metadata service on startup:
|
|
131
|
+
*
|
|
132
|
+
* - The detection only succeeds on EC2-family compute with instance metadata reachable. Anywhere
|
|
133
|
+
* else - including EC2 with IMDS disabled or behind a low hop limit - it silently falls back to
|
|
134
|
+
* `standard`, so the timeouts differ by deployment with no indication of why.
|
|
135
|
+
* - It requires a resolvable region, and fails the client outright when there is none.
|
|
136
|
+
* - Timeouts that depend on where the process happens to run are hard to reason about when
|
|
137
|
+
* diagnosing a stall.
|
|
138
|
+
*
|
|
139
|
+
* Deployments that want the tighter in-region timeouts should ask for them explicitly.
|
|
140
|
+
*/
|
|
141
|
+
function resolveConfiguredDefaultsMode(configured?: DefaultsMode): ResolvedDefaultsMode {
|
|
142
|
+
// An empty environment variable is treated as unset, matching the SDK.
|
|
143
|
+
const mode = (configured || process.env[AWS_DEFAULTS_MODE_ENV] || 'legacy').toLowerCase();
|
|
144
|
+
if (mode === 'auto') {
|
|
145
|
+
logger.warn(
|
|
146
|
+
`Ignoring AWS defaults mode "auto" for object storage, using "standard" instead. ` +
|
|
147
|
+
`Configure storage.object_storage.defaults_mode to select a mode explicitly.`
|
|
148
|
+
);
|
|
149
|
+
return 'standard';
|
|
150
|
+
}
|
|
151
|
+
const resolved = RESOLVED_DEFAULTS_MODES.find((candidate) => candidate === mode);
|
|
152
|
+
if (resolved == null) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
`Invalid AWS defaults mode ${JSON.stringify(mode)}, expected one of ${RESOLVED_DEFAULTS_MODES.join(', ')}, auto`
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
return resolved;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* An S3 operation holding a concurrency slot, released when the operation is disposed.
|
|
162
|
+
*/
|
|
163
|
+
interface S3Operation extends AsyncDisposable {
|
|
164
|
+
/**
|
|
165
|
+
* The caller's signal, combined with the operation deadline.
|
|
166
|
+
*
|
|
167
|
+
* Use this for the request itself, so that neither a stalled request nor a stalled response body
|
|
168
|
+
* can hold on to the slot indefinitely.
|
|
169
|
+
*/
|
|
170
|
+
signal: AbortSignal;
|
|
171
|
+
/**
|
|
172
|
+
* The error to report for a failed operation.
|
|
173
|
+
*/
|
|
174
|
+
error(cause: unknown): Error;
|
|
175
|
+
}
|
|
176
|
+
|
|
23
177
|
export interface S3ObjectStorageOptions {
|
|
24
178
|
bucket: string;
|
|
25
179
|
region?: string;
|
|
@@ -29,6 +183,12 @@ export interface S3ObjectStorageOptions {
|
|
|
29
183
|
accessKeyId?: string;
|
|
30
184
|
secretAccessKey?: string;
|
|
31
185
|
concurrencyLimit?: number;
|
|
186
|
+
/**
|
|
187
|
+
* AWS defaults mode, used as the baseline for the request timeouts.
|
|
188
|
+
*
|
|
189
|
+
* Defaults to the AWS_DEFAULTS_MODE environment variable. `auto` is treated as `standard`.
|
|
190
|
+
*/
|
|
191
|
+
defaultsMode?: DefaultsMode;
|
|
32
192
|
}
|
|
33
193
|
|
|
34
194
|
export class S3ObjectStorage implements ObjectStorage {
|
|
@@ -39,6 +199,7 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
39
199
|
private bucket: string;
|
|
40
200
|
private prefix: string;
|
|
41
201
|
private readonly operationSemaphore: SemaphoreInterface;
|
|
202
|
+
private readonly timeouts: S3TimeoutProfile;
|
|
42
203
|
|
|
43
204
|
constructor(options: S3ObjectStorageOptions) {
|
|
44
205
|
const concurrencyLimit = options.concurrencyLimit ?? DEFAULT_S3_OPERATION_CONCURRENCY;
|
|
@@ -60,10 +221,31 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
60
221
|
this.bucket = options.bucket;
|
|
61
222
|
this.prefix = prefix;
|
|
62
223
|
this.operationSemaphore = new Semaphore(concurrencyLimit);
|
|
224
|
+
|
|
225
|
+
// Resolve the mode once, and share it with the client so that its own defaults agree with ours.
|
|
226
|
+
const defaultsMode = resolveConfiguredDefaultsMode(options.defaultsMode);
|
|
227
|
+
this.timeouts = resolveTimeoutProfile(defaultsMode);
|
|
228
|
+
|
|
63
229
|
this.client = new S3Client({
|
|
64
230
|
region: options.region,
|
|
65
231
|
endpoint: options.endpoint,
|
|
66
232
|
forcePathStyle: options.forcePathStyle,
|
|
233
|
+
defaultsMode,
|
|
234
|
+
requestHandler: new NodeHttpHandler({
|
|
235
|
+
// Match the shared request limit instead of queuing again at the HTTP pool.
|
|
236
|
+
httpAgent: {
|
|
237
|
+
keepAlive: true,
|
|
238
|
+
maxSockets: concurrencyLimit,
|
|
239
|
+
// The timeout here is a little more general than an "idle timeout", but it does cover the
|
|
240
|
+
// case of closing idle sockets after a period of inactivity.
|
|
241
|
+
timeout: SOCKET_IDLE_TIMEOUT_MS
|
|
242
|
+
},
|
|
243
|
+
httpsAgent: { keepAlive: true, maxSockets: concurrencyLimit, timeout: SOCKET_IDLE_TIMEOUT_MS },
|
|
244
|
+
connectionTimeout: this.timeouts.connectionTimeoutMs,
|
|
245
|
+
requestTimeout: this.timeouts.requestTimeoutMs,
|
|
246
|
+
// Without this, exceeding requestTimeout only logs a warning.
|
|
247
|
+
throwOnRequestTimeout: true
|
|
248
|
+
}),
|
|
67
249
|
credentials:
|
|
68
250
|
options.accessKeyId && options.secretAccessKey
|
|
69
251
|
? { accessKeyId: options.accessKeyId, secretAccessKey: options.secretAccessKey }
|
|
@@ -71,9 +253,14 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
71
253
|
});
|
|
72
254
|
}
|
|
73
255
|
|
|
74
|
-
async put(
|
|
256
|
+
async put(
|
|
257
|
+
path: string,
|
|
258
|
+
data: Uint8Array,
|
|
259
|
+
metadata: ObjectStoragePutMetadata,
|
|
260
|
+
options?: ObjectStorageOperationOptions
|
|
261
|
+
): Promise<void> {
|
|
75
262
|
const fullPath = this.fullPath(path);
|
|
76
|
-
await using
|
|
263
|
+
await using operation = await this.withOperation('upload', fullPath, options?.signal);
|
|
77
264
|
try {
|
|
78
265
|
await this.client.send(
|
|
79
266
|
new PutObjectCommand({
|
|
@@ -82,20 +269,22 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
82
269
|
Body: data,
|
|
83
270
|
ContentType: metadata.contentType,
|
|
84
271
|
ContentEncoding: metadata.contentEncoding ?? undefined
|
|
85
|
-
})
|
|
272
|
+
}),
|
|
273
|
+
{ abortSignal: operation.signal }
|
|
86
274
|
);
|
|
87
275
|
} catch (error) {
|
|
88
|
-
throw
|
|
276
|
+
throw operation.error(error);
|
|
89
277
|
}
|
|
90
278
|
}
|
|
91
279
|
|
|
92
280
|
async get(
|
|
93
281
|
path: string,
|
|
94
|
-
options?:
|
|
282
|
+
options?: ObjectStorageOperationOptions
|
|
95
283
|
): Promise<{ data: Uint8Array; metadata: ObjectStoragePutMetadata }> {
|
|
96
284
|
const fullPath = this.fullPath(path);
|
|
97
|
-
|
|
98
|
-
|
|
285
|
+
await using operation = await this.withOperation('download', fullPath, options?.signal);
|
|
286
|
+
// Includes the operation deadline, which also covers streaming the response body below.
|
|
287
|
+
const signal = operation.signal;
|
|
99
288
|
try {
|
|
100
289
|
const response = await this.client.send(
|
|
101
290
|
new GetObjectCommand({
|
|
@@ -116,7 +305,7 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
116
305
|
let offset = 0;
|
|
117
306
|
const stream = response.Body as AsyncIterable<Uint8Array>;
|
|
118
307
|
for await (const chunk of stream) {
|
|
119
|
-
signal
|
|
308
|
+
signal.throwIfAborted();
|
|
120
309
|
const nextOffset = offset + chunk.byteLength;
|
|
121
310
|
if (nextOffset > contentLength) {
|
|
122
311
|
throw new Error(
|
|
@@ -143,11 +332,11 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
143
332
|
if (err.name === 'NoSuchKey' || err.Code === 'NoSuchKey') {
|
|
144
333
|
throw new ObjectStorageError(`S3 object not found: ${fullPath}`, { cause: err, retryable: false });
|
|
145
334
|
}
|
|
146
|
-
throw
|
|
335
|
+
throw operation.error(err);
|
|
147
336
|
}
|
|
148
337
|
}
|
|
149
338
|
|
|
150
|
-
async *list(prefix: string, options?:
|
|
339
|
+
async *list(prefix: string, options?: ObjectStorageOperationOptions): AsyncIterable<string> {
|
|
151
340
|
const fullPrefix = this.fullPath(prefix);
|
|
152
341
|
let continuationToken: string | undefined;
|
|
153
342
|
const signal = options?.signal;
|
|
@@ -168,12 +357,12 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
168
357
|
} while (continuationToken != null);
|
|
169
358
|
}
|
|
170
359
|
|
|
171
|
-
async delete(paths: string[]): Promise<void> {
|
|
360
|
+
async delete(paths: string[], options?: ObjectStorageOperationOptions): Promise<void> {
|
|
172
361
|
const fullPaths = paths.map((path) => ({ Key: this.fullPath(path) }));
|
|
173
|
-
await this.deleteFullPaths(fullPaths);
|
|
362
|
+
await this.deleteFullPaths(fullPaths, options?.signal);
|
|
174
363
|
}
|
|
175
364
|
|
|
176
|
-
async deletePrefix(prefix: string, options?:
|
|
365
|
+
async deletePrefix(prefix: string, options?: ObjectStorageOperationOptions): Promise<{ objectCount: number }> {
|
|
177
366
|
const fullPrefix = this.fullPath(prefix);
|
|
178
367
|
const signal = options?.signal;
|
|
179
368
|
let continuationToken: string | undefined;
|
|
@@ -238,8 +427,10 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
238
427
|
continuationToken: string | undefined,
|
|
239
428
|
signal?: AbortSignal
|
|
240
429
|
): Promise<ListObjectsV2CommandOutput> {
|
|
430
|
+
// Acquired outside the try, matching the other operations: withOperation() already reports its
|
|
431
|
+
// own failures as ObjectStorageError.
|
|
432
|
+
await using operation = await this.withOperation('list', fullPrefix, signal);
|
|
241
433
|
try {
|
|
242
|
-
await using _ = await this.withOperation(signal);
|
|
243
434
|
return await this.client.send(
|
|
244
435
|
new ListObjectsV2Command({
|
|
245
436
|
Bucket: this.bucket,
|
|
@@ -247,16 +438,16 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
247
438
|
ContinuationToken: continuationToken,
|
|
248
439
|
MaxKeys: S3_DELETE_PREFIX_BATCH_SIZE
|
|
249
440
|
}),
|
|
250
|
-
{ abortSignal: signal }
|
|
441
|
+
{ abortSignal: operation.signal }
|
|
251
442
|
);
|
|
252
443
|
} catch (error) {
|
|
253
|
-
throw
|
|
444
|
+
throw operation.error(error);
|
|
254
445
|
}
|
|
255
446
|
}
|
|
256
447
|
|
|
257
448
|
private async deleteFullPaths(fullPaths: { Key: string }[], signal?: AbortSignal): Promise<void> {
|
|
258
449
|
if (fullPaths.length === 0) return;
|
|
259
|
-
await using
|
|
450
|
+
await using operation = await this.withOperation('delete', `${fullPaths.length} objects`, signal);
|
|
260
451
|
let response;
|
|
261
452
|
try {
|
|
262
453
|
response = await this.client.send(
|
|
@@ -264,10 +455,10 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
264
455
|
Bucket: this.bucket,
|
|
265
456
|
Delete: { Objects: fullPaths, Quiet: true }
|
|
266
457
|
}),
|
|
267
|
-
{ abortSignal: signal }
|
|
458
|
+
{ abortSignal: operation.signal }
|
|
268
459
|
);
|
|
269
460
|
} catch (error) {
|
|
270
|
-
throw
|
|
461
|
+
throw operation.error(error);
|
|
271
462
|
}
|
|
272
463
|
if (response.Errors?.length) {
|
|
273
464
|
const errors = response.Errors.map((error) => `${error.Key}: ${error.Code}`).join(', ');
|
|
@@ -287,14 +478,28 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
287
478
|
return fullPath;
|
|
288
479
|
}
|
|
289
480
|
|
|
290
|
-
private async withOperation(signal?: AbortSignal): Promise<
|
|
481
|
+
private async withOperation(operation: string, target: string, signal?: AbortSignal): Promise<S3Operation> {
|
|
291
482
|
signal?.throwIfAborted();
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
483
|
+
const { operationTimeoutMs, queueTimeoutMs } = this.timeouts;
|
|
484
|
+
|
|
485
|
+
// Waiting for a slot is bounded even when the caller has no signal of its own, which is the
|
|
486
|
+
// case for uploads and deletes.
|
|
487
|
+
const queueDeadline = timeoutSignal(queueTimeoutMs, () =>
|
|
488
|
+
s3TimeoutError(operation, target, `timed out after ${queueTimeoutMs} ms waiting for a concurrency slot`)
|
|
489
|
+
);
|
|
490
|
+
let acquired;
|
|
491
|
+
try {
|
|
492
|
+
acquired = await acquireSemaphoreAbortable(
|
|
493
|
+
this.operationSemaphore,
|
|
494
|
+
signal ? AbortSignal.any([signal, queueDeadline.signal]) : queueDeadline.signal
|
|
495
|
+
);
|
|
496
|
+
} finally {
|
|
497
|
+
queueDeadline.cancel();
|
|
498
|
+
}
|
|
295
499
|
if (acquired === 'aborted') {
|
|
296
|
-
|
|
297
|
-
|
|
500
|
+
// A caller abort takes precedence: it is a cancellation, not an S3 failure.
|
|
501
|
+
signal?.throwIfAborted();
|
|
502
|
+
throw queueDeadline.signal.reason;
|
|
298
503
|
}
|
|
299
504
|
|
|
300
505
|
const [, release] = acquired;
|
|
@@ -302,12 +507,57 @@ export class S3ObjectStorage implements ObjectStorage {
|
|
|
302
507
|
release();
|
|
303
508
|
signal.throwIfAborted();
|
|
304
509
|
}
|
|
510
|
+
// This deadline only starts once the operation holds a slot - queueing is covered above.
|
|
511
|
+
const deadline = timeoutSignal(operationTimeoutMs, () =>
|
|
512
|
+
s3TimeoutError(operation, target, `did not complete within ${operationTimeoutMs} ms`)
|
|
513
|
+
);
|
|
514
|
+
const operationSignal = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
|
|
305
515
|
return {
|
|
306
|
-
|
|
516
|
+
signal: operationSignal,
|
|
517
|
+
error: (cause) => {
|
|
518
|
+
// Aborting a request that is already streaming destroys the socket, and the failure
|
|
519
|
+
// surfaces as a generic "aborted" error that says nothing about the cause. The abort
|
|
520
|
+
// reason is always the better answer: the caller's reason when the caller stopped us -
|
|
521
|
+
// callers abort with the error that stopped them, and upstream handling matches on that
|
|
522
|
+
// type - and an already-classified timeout when the deadline did.
|
|
523
|
+
if (operationSignal.aborted) {
|
|
524
|
+
return operationSignal.reason as Error;
|
|
525
|
+
}
|
|
526
|
+
return s3OperationError(operation, target, cause);
|
|
527
|
+
},
|
|
528
|
+
[Symbol.asyncDispose]: async () => {
|
|
529
|
+
deadline.cancel();
|
|
530
|
+
release();
|
|
531
|
+
}
|
|
307
532
|
};
|
|
308
533
|
}
|
|
309
534
|
}
|
|
310
535
|
|
|
536
|
+
/**
|
|
537
|
+
* An abort signal that fires after the given timeout, using a timer that does not hold the process
|
|
538
|
+
* open.
|
|
539
|
+
*
|
|
540
|
+
* The reason is what callers see when the timeout fires, so it is the error to report - not a
|
|
541
|
+
* marker to translate later.
|
|
542
|
+
*/
|
|
543
|
+
function timeoutSignal(timeoutMs: number, createReason: () => unknown): { signal: AbortSignal; cancel: () => void } {
|
|
544
|
+
const controller = new AbortController();
|
|
545
|
+
const timer = setTimeout(() => controller.abort(createReason()), timeoutMs);
|
|
546
|
+
timer.unref();
|
|
547
|
+
return { signal: controller.signal, cancel: () => clearTimeout(timer) };
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* A timeout that the compactor may retry, matching how the AWS SDK classifies its own request
|
|
552
|
+
* timeouts.
|
|
553
|
+
*/
|
|
554
|
+
function s3TimeoutError(operation: string, target: string, message: string): ObjectStorageError {
|
|
555
|
+
return new ObjectStorageError(`S3 ${operation} for ${target} ${message}`, {
|
|
556
|
+
cause: new DOMException(message, 'TimeoutError'),
|
|
557
|
+
retryable: true
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
|
|
311
561
|
function s3OperationError(operation: string, target: string, error: unknown): Error {
|
|
312
562
|
if (error instanceof ObjectStorageError) {
|
|
313
563
|
return error;
|