tero 0.0.13 → 0.1.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/README.md +2 -27
- package/dist/acid-engine.d.ts +132 -52
- package/dist/acid-engine.js +947 -320
- package/dist/backup.d.ts +27 -0
- package/dist/backup.js +689 -167
- package/dist/index.d.ts +157 -61
- package/dist/index.js +1491 -277
- package/dist/recovery.d.ts +52 -5
- package/dist/recovery.js +398 -117
- package/package.json +20 -16
- package/dist/schema.d.ts +0 -61
- package/dist/schema.js +0 -425
package/dist/recovery.js
CHANGED
|
@@ -1,8 +1,42 @@
|
|
|
1
|
-
import { S3Client, GetObjectCommand, ListObjectsV2Command, HeadObjectCommand } from "@aws-sdk/client-s3";
|
|
2
|
-
import { createWriteStream, existsSync, mkdirSync, openSync, fsyncSync, closeSync } from "fs";
|
|
1
|
+
import { S3Client, GetObjectCommand, ListObjectsV2Command, HeadObjectCommand, DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
|
|
2
|
+
import { createWriteStream, existsSync, mkdirSync, openSync, fsyncSync, closeSync, renameSync, unlinkSync, writeSync } from "fs";
|
|
3
3
|
import { join, dirname, resolve as pathResolve } from "path";
|
|
4
4
|
import { pipeline } from "stream/promises";
|
|
5
|
-
import { partitionedPath } from "./acid-engine.js";
|
|
5
|
+
import { partitionedPath, DataCorruptionError } from "./acid-engine.js";
|
|
6
|
+
export const MAX_DOCUMENT_SIZE = 10 * 1024 * 1024; // 10MB limit
|
|
7
|
+
export function classifyRecoveryError(error) {
|
|
8
|
+
if (error?.name === 'NotFound' ||
|
|
9
|
+
error?.name === 'NoSuchKey' ||
|
|
10
|
+
error?.$metadata?.httpStatusCode === 404 ||
|
|
11
|
+
(error?.Code && (error.Code === 'NotFound' || error.Code === 'NoSuchKey'))) {
|
|
12
|
+
return 'NOT_FOUND';
|
|
13
|
+
}
|
|
14
|
+
if (error?.name === 'AbortError' ||
|
|
15
|
+
error?.name === 'CanceledError' ||
|
|
16
|
+
error?.code === 'ABORT_ERR') {
|
|
17
|
+
return 'CANCELLED';
|
|
18
|
+
}
|
|
19
|
+
const status = error?.$metadata?.httpStatusCode;
|
|
20
|
+
if (status === 403 || status === 401 || error?.name === 'AccessDenied' || error?.name === 'InvalidAccessKeyId') {
|
|
21
|
+
return 'FATAL_AUTH';
|
|
22
|
+
}
|
|
23
|
+
if (error instanceof DataCorruptionError || error?.name === 'DataCorruptionError' || error?.code === 'DATA_CORRUPTION') {
|
|
24
|
+
return 'FATAL_CORRUPTION';
|
|
25
|
+
}
|
|
26
|
+
const code = error?.code;
|
|
27
|
+
if ((typeof status === 'number' && (status === 429 || (status >= 500 && status < 600))) ||
|
|
28
|
+
code === 'ECONNRESET' ||
|
|
29
|
+
code === 'ETIMEDOUT' ||
|
|
30
|
+
code === 'ENOTFOUND' ||
|
|
31
|
+
code === 'EAI_AGAIN' ||
|
|
32
|
+
code === 'UND_ERR_CONNECT_TIMEOUT' ||
|
|
33
|
+
error?.name === 'TimeoutError' ||
|
|
34
|
+
error?.name === 'RequestTimeout' ||
|
|
35
|
+
error?.name === 'ServiceUnavailable') {
|
|
36
|
+
return 'RETRYABLE_NETWORK';
|
|
37
|
+
}
|
|
38
|
+
return 'FATAL_UNKNOWN';
|
|
39
|
+
}
|
|
6
40
|
export class DataRecovery {
|
|
7
41
|
s3Client;
|
|
8
42
|
config;
|
|
@@ -12,6 +46,10 @@ export class DataRecovery {
|
|
|
12
46
|
}
|
|
13
47
|
initializeCloudStorage() {
|
|
14
48
|
try {
|
|
49
|
+
if (this.config.customS3Client) {
|
|
50
|
+
this.s3Client = this.config.customS3Client;
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
15
53
|
const clientConfig = {
|
|
16
54
|
region: this.config.cloudStorage.region,
|
|
17
55
|
credentials: {
|
|
@@ -78,42 +116,224 @@ export class DataRecovery {
|
|
|
78
116
|
return { key, exists: false };
|
|
79
117
|
}
|
|
80
118
|
// Re-surface real errors (auth/network/permission) so callers can distinguish
|
|
81
|
-
// "not in cloud" from "couldn't reach cloud".
|
|
82
|
-
|
|
119
|
+
// "not in cloud" from "couldn't reach cloud", preserving metadata for classifyRecoveryError.
|
|
120
|
+
const err = new Error(`Failed to check file in cloud: ${error?.message || 'Unknown error'}`);
|
|
121
|
+
err.$metadata = error?.$metadata;
|
|
122
|
+
err.name = error?.name;
|
|
123
|
+
err.code = error?.code;
|
|
124
|
+
throw err;
|
|
83
125
|
}
|
|
84
126
|
}
|
|
85
|
-
|
|
127
|
+
/**
|
|
128
|
+
* Efficiently fetches a single file from cloud storage, writes it atomically
|
|
129
|
+
* to the partitioned disk location, and returns the parsed JSON data directly
|
|
130
|
+
* from memory — avoiding redundant disk reads or extra syscalls.
|
|
131
|
+
*/
|
|
132
|
+
async fetchAndPersist(key, options) {
|
|
133
|
+
options?.abortSignal?.throwIfAborted();
|
|
86
134
|
try {
|
|
87
135
|
const cloudKey = this.getCloudKey(`${key}.json`);
|
|
88
|
-
// Write into the 2-level hash-partition location the engine reads from —
|
|
89
|
-
// NOT flat at the db root. The partition is deterministic from the key,
|
|
90
|
-
// so restored files are immediately visible to engine reads.
|
|
91
136
|
const localFilePath = partitionedPath(this.config.localPath, key);
|
|
92
|
-
// Ensure local directory exists
|
|
93
|
-
const localDir = dirname(localFilePath);
|
|
94
|
-
if (!existsSync(localDir)) {
|
|
95
|
-
mkdirSync(localDir, { recursive: true });
|
|
96
|
-
}
|
|
97
137
|
const getCommand = new GetObjectCommand({
|
|
98
138
|
Bucket: this.config.cloudStorage.bucket,
|
|
99
139
|
Key: cloudKey
|
|
100
140
|
});
|
|
101
|
-
const response = await this.s3Client.send(getCommand);
|
|
141
|
+
const response = await this.s3Client.send(getCommand, { abortSignal: options?.abortSignal });
|
|
102
142
|
if (!response.Body) {
|
|
103
|
-
|
|
143
|
+
return null;
|
|
104
144
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
145
|
+
if (response.ContentLength !== undefined && response.ContentLength > MAX_DOCUMENT_SIZE) {
|
|
146
|
+
throw new Error(`Document '${key}' exceeds maximum allowed size of ${MAX_DOCUMENT_SIZE} bytes (got ${response.ContentLength})`);
|
|
147
|
+
}
|
|
148
|
+
let content;
|
|
149
|
+
if (typeof response.Body.transformToString === 'function') {
|
|
150
|
+
content = await response.Body.transformToString('utf-8');
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
const chunks = [];
|
|
154
|
+
let totalBytes = 0;
|
|
155
|
+
for await (const chunk of response.Body) {
|
|
156
|
+
options?.abortSignal?.throwIfAborted();
|
|
157
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
158
|
+
totalBytes += buf.length;
|
|
159
|
+
if (totalBytes > MAX_DOCUMENT_SIZE) {
|
|
160
|
+
throw new Error(`Document '${key}' exceeds maximum allowed size of ${MAX_DOCUMENT_SIZE} bytes`);
|
|
161
|
+
}
|
|
162
|
+
chunks.push(buf);
|
|
163
|
+
}
|
|
164
|
+
content = Buffer.concat(chunks).toString('utf-8');
|
|
165
|
+
}
|
|
166
|
+
options?.abortSignal?.throwIfAborted();
|
|
167
|
+
// Validate JSON in memory before writing to disk
|
|
168
|
+
const trimmed = content.trim();
|
|
169
|
+
let parsed;
|
|
170
|
+
try {
|
|
171
|
+
parsed = trimmed ? JSON.parse(trimmed) : {};
|
|
172
|
+
}
|
|
173
|
+
catch (err) {
|
|
174
|
+
throw new DataCorruptionError(localFilePath, `Downloaded corrupted JSON from cloud for key '${key}': ${err?.message}`);
|
|
175
|
+
}
|
|
176
|
+
const localDir = dirname(localFilePath);
|
|
177
|
+
if (!existsSync(localDir)) {
|
|
178
|
+
mkdirSync(localDir, { recursive: true });
|
|
179
|
+
}
|
|
180
|
+
// Write atomically and durably to avoid partial reads on crash
|
|
181
|
+
const tempFilePath = `${localFilePath}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
182
|
+
try {
|
|
183
|
+
const fd = openSync(tempFilePath, 'w');
|
|
184
|
+
try {
|
|
185
|
+
writeSync(fd, Buffer.from(content, 'utf-8'));
|
|
186
|
+
fsyncSync(fd);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
closeSync(fd);
|
|
190
|
+
}
|
|
191
|
+
renameSync(tempFilePath, localFilePath);
|
|
192
|
+
// Durably persist directory entry
|
|
193
|
+
const dirFd = openSync(localDir, 'r');
|
|
194
|
+
try {
|
|
195
|
+
fsyncSync(dirFd);
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
closeSync(dirFd);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch (writeErr) {
|
|
202
|
+
try {
|
|
203
|
+
if (existsSync(tempFilePath))
|
|
204
|
+
unlinkSync(tempFilePath);
|
|
205
|
+
}
|
|
206
|
+
catch { /* approved: cleanup temp file */ }
|
|
207
|
+
throw writeErr;
|
|
208
|
+
}
|
|
209
|
+
return parsed;
|
|
109
210
|
}
|
|
110
211
|
catch (error) {
|
|
111
212
|
if (this.isNotFound(error)) {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Delete a single document file from cloud storage.
|
|
220
|
+
* Used to propagate deletes in lazy-hydration mode.
|
|
221
|
+
*/
|
|
222
|
+
async deleteFromCloud(key) {
|
|
223
|
+
if (!this.s3Client || !this.config.cloudStorage)
|
|
224
|
+
return;
|
|
225
|
+
try {
|
|
226
|
+
const cloudKey = this.getCloudKey(`${key}.json`);
|
|
227
|
+
await this.s3Client.send(new DeleteObjectCommand({
|
|
228
|
+
Bucket: this.config.cloudStorage.bucket,
|
|
229
|
+
Key: cloudKey
|
|
230
|
+
}));
|
|
231
|
+
}
|
|
232
|
+
catch (e) {
|
|
233
|
+
if (this.isNotFound(e))
|
|
234
|
+
return;
|
|
235
|
+
throw e;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Upload a durable tombstone for a deleted key (P0-2). Tombstone carries
|
|
240
|
+
* a monotonic version (LSN or timestamp) so that a later re-create can
|
|
241
|
+
* invalidate it. Hydration must check tombstone before resurrecting.
|
|
242
|
+
*/
|
|
243
|
+
async putTombstone(key, version) {
|
|
244
|
+
if (!this.s3Client || !this.config.cloudStorage)
|
|
245
|
+
return;
|
|
246
|
+
const cloudKey = this.getCloudKey(`${key}.json.deleted`);
|
|
247
|
+
const ver = version ?? Date.now();
|
|
248
|
+
await this.s3Client.send(new PutObjectCommand({
|
|
249
|
+
Bucket: this.config.cloudStorage.bucket,
|
|
250
|
+
Key: cloudKey,
|
|
251
|
+
Body: Buffer.alloc(0),
|
|
252
|
+
ContentType: 'application/octet-stream',
|
|
253
|
+
Metadata: {
|
|
254
|
+
'tombstone-version': String(ver),
|
|
255
|
+
'deleted-at': new Date().toISOString(),
|
|
256
|
+
}
|
|
257
|
+
}));
|
|
258
|
+
}
|
|
259
|
+
async deleteTombstone(key) {
|
|
260
|
+
if (!this.s3Client || !this.config.cloudStorage)
|
|
261
|
+
return;
|
|
262
|
+
try {
|
|
263
|
+
const cloudKey = this.getCloudKey(`${key}.json.deleted`);
|
|
264
|
+
await this.s3Client.send(new DeleteObjectCommand({
|
|
265
|
+
Bucket: this.config.cloudStorage.bucket,
|
|
266
|
+
Key: cloudKey
|
|
267
|
+
}));
|
|
268
|
+
}
|
|
269
|
+
catch (e) {
|
|
270
|
+
if (this.isNotFound(e))
|
|
271
|
+
return;
|
|
272
|
+
throw e;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Check if a tombstone exists for the key. If both a document and a tombstone
|
|
277
|
+
* exist, the newer LastModified wins (tombstone newer => logically deleted).
|
|
278
|
+
* Returns true if key is tombstoned (deleted) and hydration must not resurrect.
|
|
279
|
+
*/
|
|
280
|
+
async hasTombstone(key) {
|
|
281
|
+
if (!this.s3Client || !this.config.cloudStorage)
|
|
282
|
+
return false;
|
|
283
|
+
const tombKey = this.getCloudKey(`${key}.json.deleted`);
|
|
284
|
+
let tombMeta = null;
|
|
285
|
+
try {
|
|
286
|
+
const resp = await this.s3Client.send(new HeadObjectCommand({
|
|
287
|
+
Bucket: this.config.cloudStorage.bucket,
|
|
288
|
+
Key: tombKey
|
|
289
|
+
}));
|
|
290
|
+
// Defensive: some test mocks return a GetObject-shaped response (Body) for HeadObject.
|
|
291
|
+
// Only treat as tombstone if response looks like HeadObject (has LastModified/ContentLength without Body).
|
|
292
|
+
if (resp && resp.Body !== undefined)
|
|
293
|
+
return false;
|
|
294
|
+
if (!resp || (resp.LastModified === undefined && resp.ContentLength === undefined && resp.ETag === undefined && resp.ContentType === undefined)) {
|
|
295
|
+
// Empty or unexpected mock response — treat as no tombstone
|
|
112
296
|
return false;
|
|
113
297
|
}
|
|
114
|
-
|
|
115
|
-
throw new Error(`Failed to recover file from cloud: ${error?.message || 'Unknown error'}`);
|
|
298
|
+
tombMeta = resp;
|
|
116
299
|
}
|
|
300
|
+
catch (e) {
|
|
301
|
+
if (this.isNotFound(e))
|
|
302
|
+
return false;
|
|
303
|
+
throw e;
|
|
304
|
+
}
|
|
305
|
+
if (!tombMeta)
|
|
306
|
+
return false;
|
|
307
|
+
// Prefer version-lsn metadata (authoritative LSN ordering) over wall-clock LastModified
|
|
308
|
+
const tombVerStr = tombMeta.Metadata?.['tombstone-version'] ?? tombMeta.Metadata?.['version-lsn'] ?? tombMeta.Metadata?.['tombstone_version'];
|
|
309
|
+
const tombVer = tombVerStr !== undefined ? parseInt(String(tombVerStr), 10) : NaN;
|
|
310
|
+
try {
|
|
311
|
+
const docKey = this.getCloudKey(`${key}.json`);
|
|
312
|
+
const docResp = await this.s3Client.send(new HeadObjectCommand({
|
|
313
|
+
Bucket: this.config.cloudStorage.bucket,
|
|
314
|
+
Key: docKey
|
|
315
|
+
}));
|
|
316
|
+
const docVerStr = docResp.Metadata?.['version-lsn'] ?? docResp.Metadata?.['tombstone-version'] ?? docResp.Metadata?.['version_lsn'];
|
|
317
|
+
const docVer = docVerStr !== undefined ? parseInt(String(docVerStr), 10) : NaN;
|
|
318
|
+
if (!isNaN(tombVer) && !isNaN(docVer)) {
|
|
319
|
+
return tombVer >= docVer;
|
|
320
|
+
}
|
|
321
|
+
const docTime = docResp.LastModified?.getTime() ?? 0;
|
|
322
|
+
const tombTime = tombMeta.LastModified?.getTime() ?? 0;
|
|
323
|
+
// If tombstone has version but doc doesn't, prefer tombstone if its version is recent, but fall back to timestamp
|
|
324
|
+
return tombTime >= docTime;
|
|
325
|
+
}
|
|
326
|
+
catch (e) {
|
|
327
|
+
if (this.isNotFound(e)) {
|
|
328
|
+
// No document, only tombstone => deleted
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
throw e;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
async recoverSingleFile(key) {
|
|
335
|
+
const data = await this.fetchAndPersist(key);
|
|
336
|
+
return data !== null;
|
|
117
337
|
}
|
|
118
338
|
async recoverFromArchive(archiveName) {
|
|
119
339
|
const startTime = Date.now();
|
|
@@ -177,13 +397,9 @@ export class DataRecovery {
|
|
|
177
397
|
}
|
|
178
398
|
}
|
|
179
399
|
// Recover each file. We catch real (non-404) errors here so a single
|
|
180
|
-
// auth/network hiccup doesn't abort the whole batch
|
|
181
|
-
// and the caller can decide whether to retry.
|
|
182
|
-
//
|
|
183
|
-
// Parallel S3 GETs in batches of `concurrency` (default 10). A single-key
|
|
184
|
-
// sequential download takes ~30ms HTTP RTT to S3/R2; 50,000 keys sequentially
|
|
185
|
-
// takes 25 minutes (1,500 seconds). Batched parallelism reduces this to
|
|
186
|
-
// ~25ms × (50,000 / 10) ≈ 125 seconds (~2 min) and can be tuned higher.
|
|
400
|
+
// auth/network hiccup doesn't abort the whole batch when continueOnError is true —
|
|
401
|
+
// they go into `failed` and the caller can decide whether to retry.
|
|
402
|
+
// When continueOnError is false, fatal errors (auth, corruption, unknown) throw immediately.
|
|
187
403
|
const concurrency = this.config.concurrency ?? 10;
|
|
188
404
|
for (let i = 0; i < keys.length; i += concurrency) {
|
|
189
405
|
if (isCancelled?.())
|
|
@@ -200,14 +416,28 @@ export class DataRecovery {
|
|
|
200
416
|
}));
|
|
201
417
|
for (const r of results) {
|
|
202
418
|
if (r.status === 'fulfilled') {
|
|
203
|
-
const { key, success } = r.value;
|
|
204
|
-
if (success)
|
|
419
|
+
const { key, success, error } = r.value;
|
|
420
|
+
if (success) {
|
|
205
421
|
recovered.push(key);
|
|
206
|
-
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
207
424
|
failed.push(key);
|
|
425
|
+
if (error && !this.config.continueOnError) {
|
|
426
|
+
const kind = classifyRecoveryError(error);
|
|
427
|
+
if (kind === 'FATAL_AUTH' || kind === 'FATAL_CORRUPTION' || kind === 'FATAL_UNKNOWN') {
|
|
428
|
+
throw error;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
208
432
|
}
|
|
209
433
|
else {
|
|
210
434
|
failed.push(r.reason?.key || 'unknown');
|
|
435
|
+
if (!this.config.continueOnError) {
|
|
436
|
+
const kind = classifyRecoveryError(r.reason);
|
|
437
|
+
if (kind === 'FATAL_AUTH' || kind === 'FATAL_CORRUPTION' || kind === 'FATAL_UNKNOWN') {
|
|
438
|
+
throw r.reason;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
211
441
|
}
|
|
212
442
|
}
|
|
213
443
|
}
|
|
@@ -221,6 +451,10 @@ export class DataRecovery {
|
|
|
221
451
|
};
|
|
222
452
|
}
|
|
223
453
|
catch (error) {
|
|
454
|
+
const kind = classifyRecoveryError(error);
|
|
455
|
+
if (!this.config.continueOnError && (kind === 'FATAL_AUTH' || kind === 'FATAL_CORRUPTION' || kind === 'FATAL_UNKNOWN')) {
|
|
456
|
+
throw error;
|
|
457
|
+
}
|
|
224
458
|
const duration = Date.now() - startTime;
|
|
225
459
|
return {
|
|
226
460
|
success: false,
|
|
@@ -231,111 +465,139 @@ export class DataRecovery {
|
|
|
231
465
|
};
|
|
232
466
|
}
|
|
233
467
|
}
|
|
234
|
-
async
|
|
468
|
+
async *iterateAvailableArchives(options) {
|
|
469
|
+
const prefix = this.getCloudKey('');
|
|
470
|
+
let token;
|
|
235
471
|
try {
|
|
236
|
-
const prefix = this.getCloudKey('');
|
|
237
|
-
// Paginated listing — a bucket with >1000 objects would otherwise
|
|
238
|
-
// silently truncate the archive list (hydrate 'snapshot' mode would
|
|
239
|
-
// miss the newest archive sitting past the first page).
|
|
240
|
-
const objects = [];
|
|
241
|
-
let token;
|
|
242
472
|
do {
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
473
|
+
options?.abortSignal?.throwIfAborted();
|
|
474
|
+
let response;
|
|
475
|
+
try {
|
|
476
|
+
response = await this.s3Client.send(new ListObjectsV2Command({
|
|
477
|
+
Bucket: this.config.cloudStorage.bucket,
|
|
478
|
+
Prefix: prefix,
|
|
479
|
+
MaxKeys: 1000,
|
|
480
|
+
ContinuationToken: token
|
|
481
|
+
}), { abortSignal: options?.abortSignal });
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
if (this.isNotFound(error))
|
|
485
|
+
return;
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
if (response.Contents) {
|
|
489
|
+
for (const obj of response.Contents) {
|
|
490
|
+
options?.abortSignal?.throwIfAborted();
|
|
491
|
+
if (obj.Key && obj.Key.endsWith('.tar.gz')) {
|
|
492
|
+
yield {
|
|
493
|
+
name: obj.Key.split('/').pop(),
|
|
494
|
+
key: obj.Key,
|
|
495
|
+
lastModified: obj.LastModified
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
251
500
|
token = response.IsTruncated ? response.NextContinuationToken : undefined;
|
|
252
501
|
} while (token);
|
|
253
|
-
if (objects.length === 0) {
|
|
254
|
-
return [];
|
|
255
|
-
}
|
|
256
|
-
// Filter for archive files and sort by date (newest first)
|
|
257
|
-
const archives = objects
|
|
258
|
-
.filter((obj) => obj.Key && obj.Key.endsWith('.tar.gz'))
|
|
259
|
-
.sort((a, b) => {
|
|
260
|
-
const dateA = a.LastModified?.getTime() || 0;
|
|
261
|
-
const dateB = b.LastModified?.getTime() || 0;
|
|
262
|
-
return dateB - dateA; // Newest first
|
|
263
|
-
})
|
|
264
|
-
.map((obj) => obj.Key.split('/').pop())
|
|
265
|
-
.filter(Boolean);
|
|
266
|
-
return archives;
|
|
267
502
|
}
|
|
268
503
|
catch (error) {
|
|
269
|
-
|
|
504
|
+
if (this.isNotFound(error))
|
|
505
|
+
return;
|
|
506
|
+
throw error;
|
|
270
507
|
}
|
|
271
508
|
}
|
|
272
|
-
async
|
|
509
|
+
async listAvailableArchives(options) {
|
|
510
|
+
const archives = [];
|
|
511
|
+
for await (const arch of this.iterateAvailableArchives(options)) {
|
|
512
|
+
archives.push(arch);
|
|
513
|
+
}
|
|
514
|
+
return archives
|
|
515
|
+
.sort((a, b) => (b.lastModified?.getTime() || 0) - (a.lastModified?.getTime() || 0))
|
|
516
|
+
.map(a => a.name)
|
|
517
|
+
.filter(Boolean);
|
|
518
|
+
}
|
|
519
|
+
async *iterateAvailableFiles(options) {
|
|
520
|
+
const prefix = this.getCloudKey('');
|
|
521
|
+
let token;
|
|
273
522
|
try {
|
|
274
|
-
const prefix = this.getCloudKey('');
|
|
275
|
-
// Paginated listing — restores from buckets with >1000 objects
|
|
276
|
-
// previously saw a silently truncated file list.
|
|
277
|
-
const objects = [];
|
|
278
|
-
let token;
|
|
279
523
|
do {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
524
|
+
options?.abortSignal?.throwIfAborted();
|
|
525
|
+
let response;
|
|
526
|
+
try {
|
|
527
|
+
response = await this.s3Client.send(new ListObjectsV2Command({
|
|
528
|
+
Bucket: this.config.cloudStorage.bucket,
|
|
529
|
+
Prefix: prefix,
|
|
530
|
+
MaxKeys: 1000,
|
|
531
|
+
ContinuationToken: token
|
|
532
|
+
}), { abortSignal: options?.abortSignal });
|
|
533
|
+
}
|
|
534
|
+
catch (error) {
|
|
535
|
+
if (this.isNotFound(error))
|
|
536
|
+
return;
|
|
537
|
+
throw error;
|
|
538
|
+
}
|
|
539
|
+
if (response.Contents) {
|
|
540
|
+
for (const obj of response.Contents) {
|
|
541
|
+
options?.abortSignal?.throwIfAborted();
|
|
542
|
+
if (!obj.Key || !obj.Key.endsWith('.json') || obj.Key.endsWith('.deleted'))
|
|
543
|
+
continue;
|
|
544
|
+
if (obj.Key.endsWith('MANIFEST.json') ||
|
|
545
|
+
obj.Key.endsWith('latest.json') ||
|
|
546
|
+
obj.Key.endsWith('index.json') ||
|
|
547
|
+
obj.Key.endsWith('backup-metadata.json') ||
|
|
548
|
+
obj.Key.endsWith('-metadata.json') ||
|
|
549
|
+
obj.Key.includes('/wal/') ||
|
|
550
|
+
obj.Key.includes('/nodes/'))
|
|
551
|
+
continue;
|
|
552
|
+
const filename = obj.Key.split('/').pop();
|
|
553
|
+
if (filename.startsWith('.'))
|
|
554
|
+
continue;
|
|
555
|
+
yield filename.replace(/\.json$/, '');
|
|
556
|
+
}
|
|
557
|
+
}
|
|
288
558
|
token = response.IsTruncated ? response.NextContinuationToken : undefined;
|
|
289
559
|
} while (token);
|
|
290
|
-
if (objects.length === 0) {
|
|
291
|
-
return [];
|
|
292
|
-
}
|
|
293
|
-
// Filter for JSON files and extract keys (excluding metadata manifests)
|
|
294
|
-
const files = objects
|
|
295
|
-
.filter((obj) => obj.Key &&
|
|
296
|
-
obj.Key.endsWith('.json') &&
|
|
297
|
-
!obj.Key.endsWith('MANIFEST.json') &&
|
|
298
|
-
!obj.Key.endsWith('latest.json') &&
|
|
299
|
-
!obj.Key.endsWith('index.json'))
|
|
300
|
-
.map((obj) => {
|
|
301
|
-
const filename = obj.Key.split('/').pop();
|
|
302
|
-
return filename.replace('.json', '');
|
|
303
|
-
})
|
|
304
|
-
.filter(Boolean);
|
|
305
|
-
return files;
|
|
306
560
|
}
|
|
307
|
-
catch (
|
|
308
|
-
|
|
561
|
+
catch (err) {
|
|
562
|
+
if (this.isNotFound(err))
|
|
563
|
+
return;
|
|
564
|
+
throw err;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
async listAvailableFiles(options) {
|
|
568
|
+
const files = [];
|
|
569
|
+
for await (const file of this.iterateAvailableFiles(options)) {
|
|
570
|
+
files.push(file);
|
|
309
571
|
}
|
|
572
|
+
return files;
|
|
310
573
|
}
|
|
311
574
|
/**
|
|
312
575
|
* List files that exist in the cloud bucket but are missing from the local directory.
|
|
313
576
|
* This is the v2 fast path used during hydrate-on-startup with mode='missing'.
|
|
314
577
|
*/
|
|
315
|
-
async listMissingLocally() {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
missing.push(key);
|
|
323
|
-
}
|
|
578
|
+
async listMissingLocally(options) {
|
|
579
|
+
const cloudFiles = await this.listAvailableFiles(options);
|
|
580
|
+
const missing = [];
|
|
581
|
+
for (const key of cloudFiles) {
|
|
582
|
+
const localPath = partitionedPath(this.config.localPath, key);
|
|
583
|
+
if (!existsSync(localPath)) {
|
|
584
|
+
missing.push(key);
|
|
324
585
|
}
|
|
325
|
-
return missing;
|
|
326
|
-
}
|
|
327
|
-
catch (error) {
|
|
328
|
-
return [];
|
|
329
586
|
}
|
|
587
|
+
return missing;
|
|
330
588
|
}
|
|
331
589
|
/**
|
|
332
590
|
* Recover only files that exist in the cloud but are missing locally.
|
|
333
591
|
* Returns the standard RecoveryResult. Used by v2 hydrate-on-startup (mode='missing').
|
|
334
592
|
*/
|
|
335
|
-
async recoverMissingFiles(
|
|
593
|
+
async recoverMissingFiles(isCancelledOrOptions) {
|
|
336
594
|
const startTime = Date.now();
|
|
595
|
+
const isCancelled = typeof isCancelledOrOptions === 'function'
|
|
596
|
+
? isCancelledOrOptions
|
|
597
|
+
: () => isCancelledOrOptions?.abortSignal?.aborted ?? false;
|
|
598
|
+
const abortSignal = typeof isCancelledOrOptions === 'object' ? isCancelledOrOptions?.abortSignal : undefined;
|
|
337
599
|
try {
|
|
338
|
-
const missing = await this.listMissingLocally();
|
|
600
|
+
const missing = await this.listMissingLocally({ abortSignal });
|
|
339
601
|
if (missing.length === 0) {
|
|
340
602
|
return {
|
|
341
603
|
success: true,
|
|
@@ -350,6 +612,10 @@ export class DataRecovery {
|
|
|
350
612
|
return result;
|
|
351
613
|
}
|
|
352
614
|
catch (error) {
|
|
615
|
+
const kind = classifyRecoveryError(error);
|
|
616
|
+
if (!this.config.continueOnError && (kind === 'FATAL_AUTH' || kind === 'FATAL_CORRUPTION' || kind === 'FATAL_UNKNOWN')) {
|
|
617
|
+
throw error;
|
|
618
|
+
}
|
|
353
619
|
return {
|
|
354
620
|
success: false,
|
|
355
621
|
recovered: [],
|
|
@@ -374,8 +640,20 @@ export class DataRecovery {
|
|
|
374
640
|
if (!existsSync(localDir)) {
|
|
375
641
|
mkdirSync(localDir, { recursive: true });
|
|
376
642
|
}
|
|
377
|
-
const
|
|
378
|
-
|
|
643
|
+
const tempPath = `${localPath}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
644
|
+
try {
|
|
645
|
+
const writeStream = createWriteStream(tempPath);
|
|
646
|
+
await pipeline(response.Body, writeStream);
|
|
647
|
+
renameSync(tempPath, localPath);
|
|
648
|
+
}
|
|
649
|
+
catch (err) {
|
|
650
|
+
try {
|
|
651
|
+
if (existsSync(tempPath))
|
|
652
|
+
unlinkSync(tempPath);
|
|
653
|
+
}
|
|
654
|
+
catch { }
|
|
655
|
+
throw err;
|
|
656
|
+
}
|
|
379
657
|
return true;
|
|
380
658
|
}
|
|
381
659
|
catch (error) {
|
|
@@ -425,7 +703,7 @@ export class DataRecovery {
|
|
|
425
703
|
closeSync(fd);
|
|
426
704
|
}
|
|
427
705
|
}
|
|
428
|
-
catch { }
|
|
706
|
+
catch { /* approved: directory fsync best-effort */ }
|
|
429
707
|
return true;
|
|
430
708
|
}
|
|
431
709
|
catch (error) {
|
|
@@ -451,18 +729,21 @@ export class DataRecovery {
|
|
|
451
729
|
async getRecoveryInfo() {
|
|
452
730
|
try {
|
|
453
731
|
const cloudFiles = await this.listAvailableFiles();
|
|
454
|
-
|
|
455
|
-
|
|
732
|
+
let localCount = 0;
|
|
733
|
+
const missingLocally = [];
|
|
734
|
+
// Single O(N) pass: check local existence and collect missing keys directly
|
|
456
735
|
for (const key of cloudFiles) {
|
|
457
736
|
const localPath = partitionedPath(this.config.localPath, key);
|
|
458
737
|
if (existsSync(localPath)) {
|
|
459
|
-
|
|
738
|
+
localCount++;
|
|
739
|
+
}
|
|
740
|
+
else {
|
|
741
|
+
missingLocally.push(key);
|
|
460
742
|
}
|
|
461
743
|
}
|
|
462
|
-
const missingLocally = cloudFiles.filter(key => !localFiles.includes(key));
|
|
463
744
|
return {
|
|
464
745
|
cloudFiles: cloudFiles.length,
|
|
465
|
-
localFiles:
|
|
746
|
+
localFiles: localCount,
|
|
466
747
|
missingLocally,
|
|
467
748
|
availableForRecovery: cloudFiles
|
|
468
749
|
};
|