tero 0.0.6 → 0.0.8

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.
@@ -4,6 +4,9 @@ export interface RecoveryConfig {
4
4
  localPath: string;
5
5
  autoRecover?: boolean;
6
6
  recoveryTimeout?: number;
7
+ mode?: 'all' | 'missing' | 'none';
8
+ continueOnError?: boolean;
9
+ concurrency?: number;
7
10
  }
8
11
  export interface RecoveryResult {
9
12
  success: boolean;
@@ -25,12 +28,23 @@ export declare class DataRecovery {
25
28
  constructor(config: RecoveryConfig);
26
29
  private initializeCloudStorage;
27
30
  private getCloudKey;
31
+ private isNotFound;
28
32
  checkFileInCloud(key: string): Promise<FileRecoveryInfo>;
29
33
  recoverSingleFile(key: string): Promise<boolean>;
30
34
  recoverFromArchive(archiveName?: string): Promise<RecoveryResult>;
31
35
  recoverIndividualFiles(keys?: string[]): Promise<RecoveryResult>;
32
36
  listAvailableArchives(): Promise<string[]>;
33
37
  listAvailableFiles(): Promise<string[]>;
38
+ /**
39
+ * List files that exist in the cloud bucket but are missing from the local directory.
40
+ * This is the v2 fast path used during hydrate-on-startup with mode='missing'.
41
+ */
42
+ listMissingLocally(): Promise<string[]>;
43
+ /**
44
+ * Recover only files that exist in the cloud but are missing locally.
45
+ * Returns the standard RecoveryResult. Used by v2 hydrate-on-startup (mode='missing').
46
+ */
47
+ recoverMissingFiles(): Promise<RecoveryResult>;
34
48
  private downloadFile;
35
49
  private extractArchive;
36
50
  testCloudConnection(): Promise<{
package/dist/recovery.js CHANGED
@@ -2,6 +2,7 @@ import { S3Client, GetObjectCommand, ListObjectsV2Command, HeadObjectCommand } f
2
2
  import { createWriteStream, existsSync, mkdirSync } from "fs";
3
3
  import { join, dirname } from "path";
4
4
  import { pipeline } from "stream/promises";
5
+ import { partitionedPath } from "./acid-engine.js";
5
6
  export class DataRecovery {
6
7
  s3Client;
7
8
  config;
@@ -34,6 +35,12 @@ export class DataRecovery {
34
35
  const dbName = this.config.localPath.split('/').pop() || 'database';
35
36
  return `${prefix}/${dbName}/${filename}`;
36
37
  }
38
+ isNotFound(error) {
39
+ return (error?.name === 'NotFound' ||
40
+ error?.name === 'NoSuchKey' ||
41
+ error?.$metadata?.httpStatusCode === 404 ||
42
+ (error?.Code && (error.Code === 'NotFound' || error.Code === 'NoSuchKey')));
43
+ }
37
44
  async checkFileInCloud(key) {
38
45
  try {
39
46
  const cloudKey = this.getCloudKey(`${key}.json`);
@@ -50,19 +57,21 @@ export class DataRecovery {
50
57
  };
51
58
  }
52
59
  catch (error) {
53
- if (error.name === 'NotFound' || error.$metadata?.httpStatusCode === 404) {
54
- return {
55
- key,
56
- exists: false
57
- };
60
+ if (this.isNotFound(error)) {
61
+ return { key, exists: false };
58
62
  }
59
- throw new Error(`Failed to check file in cloud: ${error.message}`);
63
+ // Re-surface real errors (auth/network/permission) so callers can distinguish
64
+ // "not in cloud" from "couldn't reach cloud".
65
+ throw new Error(`Failed to check file in cloud: ${error?.message || 'Unknown error'}`);
60
66
  }
61
67
  }
62
68
  async recoverSingleFile(key) {
63
69
  try {
64
70
  const cloudKey = this.getCloudKey(`${key}.json`);
65
- const localFilePath = join(this.config.localPath, `${key}.json`);
71
+ // Write into the 2-level hash-partition location the engine reads from —
72
+ // NOT flat at the db root. The partition is deterministic from the key,
73
+ // so restored files are immediately visible to engine reads.
74
+ const localFilePath = partitionedPath(this.config.localPath, key);
66
75
  // Ensure local directory exists
67
76
  const localDir = dirname(localFilePath);
68
77
  if (!existsSync(localDir)) {
@@ -82,10 +91,11 @@ export class DataRecovery {
82
91
  return true;
83
92
  }
84
93
  catch (error) {
85
- if (error.name === 'NoSuchKey' || error.$metadata?.httpStatusCode === 404) {
94
+ if (this.isNotFound(error)) {
86
95
  return false;
87
96
  }
88
- return false;
97
+ // Re-surface real errors so callers don't mistake them for "not in cloud".
98
+ throw new Error(`Failed to recover file from cloud: ${error?.message || 'Unknown error'}`);
89
99
  }
90
100
  }
91
101
  async recoverFromArchive(archiveName) {
@@ -149,14 +159,37 @@ export class DataRecovery {
149
159
  throw new Error('No backup files found in cloud storage');
150
160
  }
151
161
  }
152
- // Recover each file
153
- for (const key of keys) {
154
- const success = await this.recoverSingleFile(key);
155
- if (success) {
156
- recovered.push(key);
157
- }
158
- else {
159
- failed.push(key);
162
+ // Recover each file. We catch real (non-404) errors here so a single
163
+ // auth/network hiccup doesn't abort the whole batch — they go into `failed`
164
+ // and the caller can decide whether to retry.
165
+ //
166
+ // Parallel S3 GETs in batches of `concurrency` (default 10). A single-key
167
+ // sequential download takes ~30ms HTTP RTT to S3/R2; 50,000 keys sequentially
168
+ // takes 25 minutes (1,500 seconds). Batched parallelism reduces this to
169
+ // ~25ms × (50,000 / 10) ≈ 125 seconds (~2 min) and can be tuned higher.
170
+ const concurrency = this.config.concurrency ?? 10;
171
+ for (let i = 0; i < keys.length; i += concurrency) {
172
+ const batch = keys.slice(i, i + concurrency);
173
+ const results = await Promise.allSettled(batch.map(async (key) => {
174
+ try {
175
+ const success = await this.recoverSingleFile(key);
176
+ return { key, success };
177
+ }
178
+ catch (error) {
179
+ return { key, success: false, error };
180
+ }
181
+ }));
182
+ for (const r of results) {
183
+ if (r.status === 'fulfilled') {
184
+ const { key, success } = r.value;
185
+ if (success)
186
+ recovered.push(key);
187
+ else
188
+ failed.push(key);
189
+ }
190
+ else {
191
+ failed.push(r.reason?.key || 'unknown');
192
+ }
160
193
  }
161
194
  }
162
195
  const duration = Date.now() - startTime;
@@ -233,6 +266,57 @@ export class DataRecovery {
233
266
  return [];
234
267
  }
235
268
  }
269
+ /**
270
+ * List files that exist in the cloud bucket but are missing from the local directory.
271
+ * This is the v2 fast path used during hydrate-on-startup with mode='missing'.
272
+ */
273
+ async listMissingLocally() {
274
+ try {
275
+ const cloudFiles = await this.listAvailableFiles();
276
+ const missing = [];
277
+ for (const key of cloudFiles) {
278
+ const localPath = partitionedPath(this.config.localPath, key);
279
+ if (!existsSync(localPath)) {
280
+ missing.push(key);
281
+ }
282
+ }
283
+ return missing;
284
+ }
285
+ catch (error) {
286
+ return [];
287
+ }
288
+ }
289
+ /**
290
+ * Recover only files that exist in the cloud but are missing locally.
291
+ * Returns the standard RecoveryResult. Used by v2 hydrate-on-startup (mode='missing').
292
+ */
293
+ async recoverMissingFiles() {
294
+ const startTime = Date.now();
295
+ try {
296
+ const missing = await this.listMissingLocally();
297
+ if (missing.length === 0) {
298
+ return {
299
+ success: true,
300
+ recovered: [],
301
+ failed: [],
302
+ totalFiles: 0,
303
+ duration: Date.now() - startTime,
304
+ };
305
+ }
306
+ const result = await this.recoverIndividualFiles(missing);
307
+ result.duration = Date.now() - startTime;
308
+ return result;
309
+ }
310
+ catch (error) {
311
+ return {
312
+ success: false,
313
+ recovered: [],
314
+ failed: [],
315
+ totalFiles: 0,
316
+ duration: Date.now() - startTime,
317
+ };
318
+ }
319
+ }
236
320
  async downloadFile(cloudKey, localPath) {
237
321
  try {
238
322
  const getCommand = new GetObjectCommand({
@@ -253,7 +337,10 @@ export class DataRecovery {
253
337
  return true;
254
338
  }
255
339
  catch (error) {
256
- return false;
340
+ if (this.isNotFound(error)) {
341
+ return false;
342
+ }
343
+ throw new Error(`Failed to download file from cloud: ${error?.message || 'Unknown error'}`);
257
344
  }
258
345
  }
259
346
  async extractArchive(archivePath) {
@@ -290,9 +377,9 @@ export class DataRecovery {
290
377
  try {
291
378
  const cloudFiles = await this.listAvailableFiles();
292
379
  const localFiles = [];
293
- // Check which files exist locally
380
+ // Check which files exist locally (in their hash-partition location)
294
381
  for (const key of cloudFiles) {
295
- const localPath = join(this.config.localPath, `${key}.json`);
382
+ const localPath = partitionedPath(this.config.localPath, key);
296
383
  if (existsSync(localPath)) {
297
384
  localFiles.push(key);
298
385
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tero",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "description": "Tero is a JSON database that provides ACID transactions, schema validation, automated cloud backup, and automatic cloud recovery",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "test:production": "node local_tests/production-test.js",
22
22
  "test:legacy": "node local_tests/test.js",
23
23
  "test:backup": "node local_tests/backup-test.js",
24
+ "test:s3": "node local_tests/s3-live-backup-test.js",
24
25
  "test:schema": "node local_tests/schema-test.js",
25
26
  "test:all": "npm run test",
26
27
  "test:watch": "npm run test",
@@ -29,7 +30,10 @@
29
30
  "pretest": "echo 'Running Tero test suite...'",
30
31
  "posttest": "echo 'Test suite completed!'",
31
32
  "verify": "node verify-build.js && npm run test",
32
- "ci": "npm run verify"
33
+ "ci": "npm run verify",
34
+ "bench": "node bench/run-bench.js --synchronous normal",
35
+ "bench:full": "node bench/run-bench.js --synchronous full",
36
+ "bench:quick": "node bench/run-bench.js --quick --synchronous normal"
33
37
  },
34
38
  "files": [
35
39
  "dist/**/*"