tero 0.0.8 → 0.0.10

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/dist/backup.js CHANGED
@@ -1,17 +1,58 @@
1
- import { createReadStream, existsSync, statSync } from "fs";
2
- import { join, basename } from "path";
3
- import tar from "tar";
4
- import { S3Client, PutObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
5
- import { Upload } from "@aws-sdk/lib-storage";
1
+ import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync, unlinkSync } from "fs";
2
+ import { join, basename, relative, dirname, sep } from "path";
3
+ import { create as tarCreate } from "tar";
4
+ import { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
6
5
  import { CronJob } from "cron";
6
+ import { gzipSync, gunzipSync } from "zlib";
7
+ import { randomUUID } from "crypto";
8
+ import { partitionedPath, walkPartitions } from "./acid-engine.js";
9
+ /**
10
+ * LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort.
11
+ */
12
+ function padLsn(lsn) {
13
+ return lsn.toString().padStart(16, '0');
14
+ }
15
+ /**
16
+ * WAL operations that get shipped in segments. COMMIT/ROLLBACK markers are
17
+ * ESSENTIAL: restore buffers WRITE/DELETE entries per transactionId and only
18
+ * applies them when the transaction's COMMIT arrives (discarding on ROLLBACK).
19
+ * Shipping data entries without commit markers would make every replayed
20
+ * transaction uncommitted — i.e. restore would silently drop ALL WAL-shipped
21
+ * writes. Only BEGIN and CHECKPOINT (pure metadata) are excluded.
22
+ */
23
+ const WAL_SHIPPED_OPS = new Set(['WRITE', 'DELETE', 'COMMIT', 'ROLLBACK']);
24
+ /**
25
+ * Bounded-concurrency mapper. Runs `fn` over `items` with at most `limit`
26
+ * promises in flight. Errors reject the whole promise (first failure wins) —
27
+ * callers that want per-item resilience wrap fn in their own try/catch.
28
+ */
29
+ async function pooledMap(items, limit, fn) {
30
+ const results = new Array(items.length);
31
+ let next = 0;
32
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
33
+ while (true) {
34
+ const i = next++;
35
+ if (i >= items.length)
36
+ return;
37
+ results[i] = await fn(items[i]);
38
+ }
39
+ });
40
+ await Promise.all(workers);
41
+ return results;
42
+ }
7
43
  export class BackupManager {
8
44
  s3Client;
9
45
  scheduledBackups = new Map();
10
46
  config;
11
47
  dbPath;
48
+ /** Injected or default logger (see BackupConfig.logger). */
49
+ log;
12
50
  constructor(dbPath, config) {
13
51
  this.dbPath = dbPath;
14
52
  this.config = config;
53
+ this.log = config.logger === 'silent'
54
+ ? { info: () => { }, warn: () => { }, error: () => { } }
55
+ : (config.logger ?? console);
15
56
  if (config.cloudStorage) {
16
57
  this.initializeCloudStorage(config.cloudStorage);
17
58
  }
@@ -33,7 +74,7 @@ export class BackupManager {
33
74
  this.s3Client = new S3Client(clientConfig);
34
75
  }
35
76
  catch (error) {
36
- throw new Error(`Failed to initialize cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`);
77
+ throw new Error(`Failed to initialize cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
37
78
  }
38
79
  }
39
80
  parseInterval(interval) {
@@ -138,7 +179,7 @@ export class BackupManager {
138
179
  return files;
139
180
  }
140
181
  catch (error) {
141
- throw new Error(`Failed to get JSON files: ${error instanceof Error ? error.message : 'Unknown error'}`);
182
+ throw new Error(`Failed to get JSON files: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
142
183
  }
143
184
  }
144
185
  async createArchiveBackup() {
@@ -161,7 +202,7 @@ export class BackupManager {
161
202
  // 2-level hash-prefix partition dirs are preserved in the archive.
162
203
  // (was: jsonFiles.map(f => f.name) — broke when files moved to XX/YY/key.json)
163
204
  const fileList = jsonFiles.map(f => f.path.slice(this.dbPath.length + 1));
164
- await tar.create({
205
+ await tarCreate({
165
206
  file: backupPath,
166
207
  cwd: this.dbPath,
167
208
  gzip: true,
@@ -180,7 +221,7 @@ export class BackupManager {
180
221
  return { filePath: backupPath, metadata };
181
222
  }
182
223
  catch (error) {
183
- throw new Error(`Failed to create archive backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
224
+ throw new Error(`Failed to create archive backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
184
225
  }
185
226
  }
186
227
  async createIndividualBackup() {
@@ -250,7 +291,7 @@ export class BackupManager {
250
291
  return { files: backedUpFiles, metadata };
251
292
  }
252
293
  catch (error) {
253
- throw new Error(`Failed to create individual backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
294
+ throw new Error(`Failed to create individual backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
254
295
  }
255
296
  }
256
297
  async uploadToCloud(localPath, cloudKey) {
@@ -258,26 +299,25 @@ export class BackupManager {
258
299
  throw new Error('Cloud storage not configured');
259
300
  }
260
301
  try {
261
- const fileStream = createReadStream(localPath);
262
- const stats = statSync(localPath);
263
- const upload = new Upload({
264
- client: this.s3Client,
265
- params: {
266
- Bucket: this.config.cloudStorage.bucket,
267
- Key: cloudKey,
268
- Body: fileStream,
269
- ContentLength: stats.size,
270
- Metadata: {
271
- 'backup-timestamp': new Date().toISOString(),
272
- 'source-db': basename(this.dbPath),
273
- 'backup-format': this.config.format
274
- }
302
+ if (!existsSync(localPath))
303
+ return;
304
+ const fs = await import('fs/promises');
305
+ const body = await fs.readFile(localPath);
306
+ const cmd = new PutObjectCommand({
307
+ Bucket: this.config.cloudStorage.bucket,
308
+ Key: cloudKey,
309
+ Body: body,
310
+ ContentType: cloudKey.endsWith('.json') ? 'application/json' : 'application/octet-stream',
311
+ Metadata: {
312
+ 'backup-timestamp': new Date().toISOString(),
313
+ 'source-db': basename(this.dbPath),
314
+ 'backup-format': this.config.format
275
315
  }
276
316
  });
277
- await upload.done();
317
+ await this.s3Client.send(cmd);
278
318
  }
279
319
  catch (error) {
280
- throw new Error(`Failed to upload to cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`);
320
+ throw new Error(`Failed to upload to cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
281
321
  }
282
322
  }
283
323
  async uploadDirectoryToCloud(localDir, cloudPrefix) {
@@ -287,15 +327,16 @@ export class BackupManager {
287
327
  try {
288
328
  const fs = await import('fs/promises');
289
329
  const files = await fs.readdir(localDir);
290
- const uploadPromises = files.map(async (file) => {
330
+ // Bounded concurrency — unbounded Promise.all would open files.length
331
+ // simultaneous S3 streams and exhaust file descriptors at 20k+ docs.
332
+ await pooledMap(files, 16, async (file) => {
291
333
  const localFilePath = join(localDir, file);
292
334
  const cloudKey = `${cloudPrefix}/${file}`;
293
335
  await this.uploadToCloud(localFilePath, cloudKey);
294
336
  });
295
- await Promise.all(uploadPromises);
296
337
  }
297
338
  catch (error) {
298
- throw new Error(`Failed to upload directory to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`);
339
+ throw new Error(`Failed to upload directory to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
299
340
  }
300
341
  }
301
342
  async uploadIndividualFilesToCloud(localDir) {
@@ -305,18 +346,17 @@ export class BackupManager {
305
346
  try {
306
347
  const fs = await import('fs/promises');
307
348
  const files = await fs.readdir(localDir);
308
- const uploadPromises = files
309
- .filter(file => file.endsWith('.json')) // Only upload JSON files, skip metadata
310
- .map(async (file) => {
349
+ const jsonFiles = files.filter(file => file.endsWith('.json'));
350
+ // Bounded concurrency — same reason as uploadDirectoryToCloud.
351
+ await pooledMap(jsonFiles, 16, async (file) => {
311
352
  const localFilePath = join(localDir, file);
312
353
  // Use direct key-based cloud storage: each JSON file is stored with its key as the cloud key
313
354
  const cloudKey = this.getCloudKey(file);
314
355
  await this.uploadToCloud(localFilePath, cloudKey);
315
356
  });
316
- await Promise.all(uploadPromises);
317
357
  }
318
358
  catch (error) {
319
- throw new Error(`Failed to upload individual files to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`);
359
+ throw new Error(`Failed to upload individual files to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
320
360
  }
321
361
  }
322
362
  getCloudKey(filename) {
@@ -326,7 +366,7 @@ export class BackupManager {
326
366
  }
327
367
  async performBackup() {
328
368
  try {
329
- console.log(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
369
+ this.log.info(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
330
370
  let metadata;
331
371
  let cloudUploaded = false;
332
372
  if (this.config.format === 'archive') {
@@ -337,20 +377,28 @@ export class BackupManager {
337
377
  const cloudKey = this.getCloudKey(basename(filePath));
338
378
  await this.uploadToCloud(filePath, cloudKey);
339
379
  cloudUploaded = true;
340
- console.log(`☁️ Uploaded archive backup to cloud: ${cloudKey}`);
380
+ this.log.info(`☁️ Uploaded archive backup to cloud: ${cloudKey}`);
341
381
  }
342
- console.log(`✅ Archive backup completed: ${filePath}`);
382
+ this.log.info(`✅ Archive backup completed: ${filePath}`);
343
383
  }
344
384
  else {
345
385
  const { files, metadata: backupMetadata } = await this.createIndividualBackup();
346
386
  metadata = backupMetadata;
347
387
  // Upload to cloud if configured - use key-based storage for direct recovery
348
388
  if (this.config.cloudStorage && this.s3Client) {
349
- await this.uploadIndividualFilesToCloud(files[0].split('/').slice(0, -1).join('/'));
389
+ // Derive the backup directory via path.dirname — the previous
390
+ // files[0].split('/') was POSIX-only and threw if files was empty.
391
+ const backupDir = files.length > 0 ? dirname(files[0]) : (this.config.localPath || join(this.dbPath, '.backup'));
392
+ if (files.length === 0) {
393
+ this.log.warn('⚠️ No files to upload to cloud — backup produced no data files');
394
+ }
395
+ else {
396
+ await this.uploadIndividualFilesToCloud(backupDir);
397
+ }
350
398
  cloudUploaded = true;
351
- console.log(`☁️ Uploaded individual backup to cloud using key-based storage`);
399
+ this.log.info(`☁️ Uploaded individual backup to cloud using key-based storage`);
352
400
  }
353
- console.log(`✅ Individual backup completed: ${files.length} files`);
401
+ this.log.info(`✅ Individual backup completed: ${files.length} files`);
354
402
  }
355
403
  // Clean up old backups based on retention policy
356
404
  if (this.config.retention) {
@@ -359,7 +407,7 @@ export class BackupManager {
359
407
  return { success: true, metadata, cloudUploaded };
360
408
  }
361
409
  catch (error) {
362
- console.error(`❌ Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
410
+ this.log.error(`❌ Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
363
411
  return {
364
412
  success: false,
365
413
  metadata: {
@@ -381,13 +429,26 @@ export class BackupManager {
381
429
  const retentionMs = this.parseRetention(this.config.retention);
382
430
  const cutoffDate = new Date(Date.now() - retentionMs);
383
431
  const prefix = this.getCloudKey('');
384
- const listCommand = new ListObjectsV2Command({
385
- Bucket: this.config.cloudStorage.bucket,
386
- Prefix: prefix
387
- });
388
- const response = await this.s3Client.send(listCommand);
389
- if (response.Contents) {
390
- const oldObjects = response.Contents.filter((obj) => obj.LastModified && obj.LastModified < cutoffDate);
432
+ // Paginate ALL pages — a single ListObjectsV2 returns at most 1000 keys,
433
+ // so with more objects than that, retention silently stopped deleting
434
+ // everything past the first page (unbounded bucket growth + cost).
435
+ const oldObjects = [];
436
+ let token;
437
+ do {
438
+ const response = await this.s3Client.send(new ListObjectsV2Command({
439
+ Bucket: this.config.cloudStorage.bucket,
440
+ Prefix: prefix,
441
+ ContinuationToken: token,
442
+ }));
443
+ if (response.Contents) {
444
+ for (const obj of response.Contents) {
445
+ if (obj.Key && obj.LastModified && obj.LastModified < cutoffDate)
446
+ oldObjects.push(obj);
447
+ }
448
+ }
449
+ token = response.IsTruncated ? response.NextContinuationToken : undefined;
450
+ } while (token);
451
+ if (oldObjects.length > 0) {
391
452
  const deletePromises = oldObjects.map((obj) => {
392
453
  if (obj.Key) {
393
454
  return this.s3Client.send(new DeleteObjectCommand({
@@ -399,12 +460,12 @@ export class BackupManager {
399
460
  }).filter(Boolean);
400
461
  await Promise.all(deletePromises);
401
462
  if (oldObjects.length > 0) {
402
- console.log(`🗑️ Cleaned up ${oldObjects.length} old backup(s) from cloud storage`);
463
+ this.log.info(`🗑️ Cleaned up ${oldObjects.length} old backup(s) from cloud storage`);
403
464
  }
404
465
  }
405
466
  }
406
467
  catch (error) {
407
- console.warn(`⚠️ Failed to cleanup old backups: ${error instanceof Error ? error.message : 'Unknown error'}`);
468
+ this.log.warn(`⚠️ Failed to cleanup old backups: ${error instanceof Error ? error.message : 'Unknown error'}`);
408
469
  }
409
470
  }
410
471
  scheduleBackup(config) {
@@ -417,7 +478,7 @@ export class BackupManager {
417
478
  this.config.retention = config.retention;
418
479
  }
419
480
  const performScheduledBackup = async () => {
420
- console.log(`⏰ Scheduled backup triggered (${config.interval} interval)`);
481
+ this.log.info(`⏰ Scheduled backup triggered (${config.interval} interval)`);
421
482
  await this.performBackup();
422
483
  };
423
484
  // Create cron job for recurring backups
@@ -426,11 +487,11 @@ export class BackupManager {
426
487
  'UTC' // timezone
427
488
  );
428
489
  this.scheduledBackups.set(scheduleId, cronJob);
429
- console.log(`📅 Backup scheduled with cron: ${cronExpression} (${config.interval} interval), ${config.retention || this.config.retention} retention`);
490
+ this.log.info(`📅 Backup scheduled with cron: ${cronExpression} (${config.interval} interval), ${config.retention || this.config.retention} retention`);
430
491
  return scheduleId;
431
492
  }
432
493
  catch (error) {
433
- throw new Error(`Failed to schedule backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
494
+ throw new Error(`Failed to schedule backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
434
495
  }
435
496
  }
436
497
  cancelScheduledBackup(scheduleId) {
@@ -438,7 +499,7 @@ export class BackupManager {
438
499
  if (cronJob) {
439
500
  cronJob.stop();
440
501
  this.scheduledBackups.delete(scheduleId);
441
- console.log(`❌ Cancelled scheduled backup: ${scheduleId}`);
502
+ this.log.info(`❌ Cancelled scheduled backup: ${scheduleId}`);
442
503
  return true;
443
504
  }
444
505
  return false;
@@ -493,9 +554,12 @@ export class BackupManager {
493
554
  };
494
555
  }
495
556
  try {
496
- // 1) Snapshot all data JSON files to bucket.
557
+ // 1) Snapshot all data JSON files to bucket. POOLED — the old sequential
558
+ // await-per-file loop made a 50k-doc backup take ~12 minutes at ~15ms
559
+ // per PUT; 16 in flight brings it under a minute. Per-item errors are
560
+ // collected (not fatal), matching the previous best-effort semantics.
497
561
  const jsonFiles = await this.getJsonFiles();
498
- for (const file of jsonFiles) {
562
+ await pooledMap(jsonFiles, 16, async (file) => {
499
563
  try {
500
564
  const cloudKey = this.getCloudKey(file.name);
501
565
  await this.uploadToCloud(file.path, cloudKey);
@@ -504,12 +568,12 @@ export class BackupManager {
504
568
  catch (error) {
505
569
  errors.push(`data:${file.name}:${error instanceof Error ? error.message : 'Unknown error'}`);
506
570
  }
507
- }
571
+ });
508
572
  // 2) Stream WAL archive segments the caller wants persisted.
509
573
  const walPaths = options?.walArchivePaths ?? [];
510
- for (const archivePath of walPaths) {
574
+ await pooledMap(walPaths, 16, async (archivePath) => {
511
575
  if (!existsSync(archivePath))
512
- continue;
576
+ return;
513
577
  try {
514
578
  const segName = basename(archivePath);
515
579
  const prefix = this.config.cloudStorage.pathPrefix || 'tero-backups';
@@ -521,7 +585,7 @@ export class BackupManager {
521
585
  catch (error) {
522
586
  errors.push(`wal:${basename(archivePath)}:${error instanceof Error ? error.message : 'Unknown error'}`);
523
587
  }
524
- }
588
+ });
525
589
  // 3) Emit a backup manifest so hydrate-on-startup can discover the latest snapshot.
526
590
  try {
527
591
  const manifest = {
@@ -575,12 +639,508 @@ export class BackupManager {
575
639
  });
576
640
  await this.s3Client.send(cmd);
577
641
  }
642
+ // ===== Live backup (per-second WAL shipping) — fields =====
643
+ liveShipper;
644
+ liveNodeId;
645
+ liveEngine;
646
+ livePrefix;
647
+ liveCheckpoints = 0;
648
+ /** In-flight checkpoint (shared promise: concurrent callers await the same run). */
649
+ liveCheckpointPromise;
650
+ lastCheckpointError;
578
651
  destroy() {
579
- // Cancel all scheduled backups
580
- for (const [id, cronJob] of this.scheduledBackups) {
652
+ for (const [id, cronJob] of this.scheduledBackups)
581
653
  cronJob.stop();
582
- }
583
654
  this.scheduledBackups.clear();
584
- console.log('🛑 BackupManager destroyed, all scheduled backups cancelled');
655
+ // Clear the reference too — the automatic initial-checkpoint retry loop
656
+ // checks it and must stop retrying after destroy.
657
+ if (this.liveShipper) {
658
+ this.liveShipper.stop();
659
+ this.liveShipper = undefined;
660
+ }
661
+ this.log.info('🛑 BackupManager destroyed, all scheduled backups cancelled');
662
+ }
663
+ liveCloudPrefix(nodeId) {
664
+ const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
665
+ return `${base}/${basename(this.dbPath)}/nodes/${nodeId}/`;
666
+ }
667
+ async uploadBytes(key, body, contentType = 'application/octet-stream') {
668
+ if (!this.s3Client || !this.config.cloudStorage)
669
+ throw new Error('Cloud storage not configured');
670
+ await this.s3Client.send(new PutObjectCommand({
671
+ Bucket: this.config.cloudStorage.bucket, Key: key, Body: body, ContentType: contentType,
672
+ Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': basename(this.dbPath) },
673
+ }));
674
+ }
675
+ async downloadBytes(key) {
676
+ if (!this.s3Client || !this.config.cloudStorage)
677
+ throw new Error('Cloud storage not configured');
678
+ const resp = await this.s3Client.send(new GetObjectCommand({ Bucket: this.config.cloudStorage.bucket, Key: key }));
679
+ if (!resp.Body)
680
+ throw new Error(`Empty body for ${key}`);
681
+ const chunks = [];
682
+ for await (const c of resp.Body)
683
+ chunks.push(typeof c === 'string' ? Buffer.from(c) : c);
684
+ return Buffer.concat(chunks);
685
+ }
686
+ async readJsonOrDefault(key) {
687
+ try {
688
+ return JSON.parse((await this.downloadBytes(key)).toString('utf8'));
689
+ }
690
+ catch (e) {
691
+ if (e instanceof Error && (e.name === 'NoSuchKey' || /NoSuchKey|404|not found|does not exist/i.test(e.message)))
692
+ return null;
693
+ throw e;
694
+ }
695
+ }
696
+ async listPrefix(prefix) {
697
+ if (!this.s3Client || !this.config.cloudStorage)
698
+ throw new Error('Cloud storage not configured');
699
+ const keys = [];
700
+ let token;
701
+ do {
702
+ const resp = await this.s3Client.send(new ListObjectsV2Command({ Bucket: this.config.cloudStorage.bucket, Prefix: prefix, ContinuationToken: token }));
703
+ if (resp.Contents)
704
+ for (const o of resp.Contents)
705
+ if (o.Key)
706
+ keys.push(o.Key);
707
+ token = resp.IsTruncated ? resp.NextContinuationToken : undefined;
708
+ } while (token);
709
+ return keys;
710
+ }
711
+ enableLiveBackup(engine, opts) {
712
+ if (opts.consistency !== 'per-second')
713
+ throw new Error("Tero live backup only supports consistency: 'per-second' (RPO ≤ 1s). Other levels are not offered.");
714
+ if (this.liveShipper)
715
+ return;
716
+ if (!this.s3Client || !this.config.cloudStorage)
717
+ throw new Error('Cloud storage not configured — call configureBackup() with cloudStorage first.');
718
+ const intervalMs = Math.max(250, opts.intervalMs ?? 1000);
719
+ if (intervalMs > 1000)
720
+ throw new Error(`intervalMs=${intervalMs} violates the per-second consistency contract (RPO ≤ 1s). Use intervalMs ≤ 1000.`);
721
+ // Resolve nodeId: explicit > persisted file > fresh id. Sanitize hard — this
722
+ // becomes an S3 key path component; garbage must never produce nested paths.
723
+ let nodeId = opts.nodeId;
724
+ const idFile = join(this.dbPath, '.tero-node-id');
725
+ if (!nodeId) {
726
+ try {
727
+ nodeId = readFileSync(idFile, 'utf8').trim();
728
+ }
729
+ catch {
730
+ nodeId = '';
731
+ }
732
+ }
733
+ if (nodeId)
734
+ nodeId = nodeId.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64);
735
+ if (!nodeId)
736
+ nodeId = randomUUID().replace(/-/g, '').slice(0, 16);
737
+ try {
738
+ writeFileSync(idFile, nodeId, 'utf8');
739
+ }
740
+ catch { }
741
+ const prefix = this.liveCloudPrefix(nodeId);
742
+ this.liveNodeId = nodeId;
743
+ this.liveEngine = engine;
744
+ this.livePrefix = prefix;
745
+ this.lastCheckpointError = undefined;
746
+ this.liveShipper = new WalShipper({ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs });
747
+ this.liveShipper.start();
748
+ this.log.info(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
749
+ // CRITICAL: take the initial FULL checkpoint automatically. Without it, every
750
+ // document written BEFORE enableLiveBackup() is unrestorable until the first
751
+ // manual liveCheckpointToBucket() — a crash in that window loses all prior data.
752
+ // Retry with backoff (bucket may be temporarily unreachable); surface failures
753
+ // in getLiveBackupStatus().lastCheckpointError.
754
+ void this.runInitialCheckpoint(prefix);
755
+ }
756
+ /** Initial full checkpoint with bounded retry. Stops on success or disable. */
757
+ async runInitialCheckpoint(prefix) {
758
+ for (let attempt = 1;; attempt++) {
759
+ if (this.liveShipper === undefined || this.livePrefix !== prefix)
760
+ return; // disabled/re-enabled under us
761
+ try {
762
+ await this.liveCheckpointToBucket();
763
+ return;
764
+ }
765
+ catch (e) {
766
+ this.lastCheckpointError = `initial-checkpoint attempt ${attempt}: ${e instanceof Error ? e.message : String(e)}`;
767
+ if (attempt >= 60)
768
+ return; // give up after ~5 min; error stays visible in status
769
+ // unref'd so a failing bucket can never keep the process alive.
770
+ await new Promise(r => { const t = setTimeout(r, Math.min(5000 * attempt, 30000)); t.unref?.(); });
771
+ }
772
+ }
773
+ }
774
+ disableLiveBackup() {
775
+ if (!this.liveShipper)
776
+ return;
777
+ this.liveShipper.stop();
778
+ this.liveShipper = undefined;
779
+ this.log.info('🛑 Tero live backup disabled');
780
+ }
781
+ getLiveBackupStatus() {
782
+ const s = this.liveShipper?.status;
783
+ return {
784
+ state: s?.state ?? 'stopped', nodeId: this.liveNodeId ?? 'unknown', intervalMs: this.liveShipper?.intervalMs ?? 0,
785
+ lastShippedLsn: s?.lastShippedLsn ?? 0, lastShipAt: s?.lastShipAt ?? 0,
786
+ secondsSinceLastShip: s?.lastShipAt ? Math.round((Date.now() - s.lastShipAt) / 1000) : 0,
787
+ segmentsShipped: s?.segmentsShipped ?? 0, checkpointsTaken: this.liveCheckpoints,
788
+ errorCount: s?.errorCount ?? 0, lastError: s?.lastError,
789
+ lastCheckpointError: this.lastCheckpointError,
790
+ };
791
+ }
792
+ // __TERO_LIVE_PART2__
793
+ async liveCheckpointToBucket(_opts) {
794
+ if (!this.liveEngine || !this.liveNodeId || !this.livePrefix)
795
+ throw new Error('Live backup not enabled — call enableLiveBackup() first.');
796
+ // Share the in-flight run: concurrent callers (e.g. the automatic initial
797
+ // checkpoint racing a manual call) must never interleave uploads — a second
798
+ // run could publish latest.json before the first run's data is durable.
799
+ if (this.liveCheckpointPromise)
800
+ return this.liveCheckpointPromise;
801
+ this.liveCheckpointPromise = this.doLiveCheckpoint();
802
+ try {
803
+ const r = await this.liveCheckpointPromise;
804
+ this.lastCheckpointError = undefined;
805
+ return r;
806
+ }
807
+ catch (e) {
808
+ this.lastCheckpointError = e instanceof Error ? e.message : String(e);
809
+ throw e;
810
+ }
811
+ finally {
812
+ this.liveCheckpointPromise = undefined;
813
+ }
814
+ }
815
+ async doLiveCheckpoint() {
816
+ const engine = this.liveEngine;
817
+ const start = Date.now();
818
+ const ckptPrefix = `${this.livePrefix}checkpoint/`;
819
+ const latestKey = `${ckptPrefix}latest.json`;
820
+ // (1) CONSERVATIVE baseLsn — capture BEFORE flushing/uploading. commitTransaction
821
+ // is synchronous (LSN assignment + committedBuffer set are atomic in one event-
822
+ // loop turn), so every entry with lsn ≤ ckptLsn is in committedBuffer right now
823
+ // and lands in the data files after the flush below. Everything > ckptLsn is
824
+ // guaranteed to be WAL-replayed on restore. Capturing the LSN AFTER the uploads
825
+ // instead would let mid-checkpoint writes be skipped by BOTH the checkpoint
826
+ // content AND the replay filter — silent stale-data loss.
827
+ const ckptLsn = engine.getWAL().getCurrentLSN();
828
+ // (2) Flush committed data so the files we read reflect all commits ≤ ckptLsn.
829
+ engine.flushCommittedBuffer();
830
+ const posixRel = (p) => relative(this.dbPath, p).split(sep).join('/');
831
+ const latest = await this.readJsonOrDefault(latestKey);
832
+ if (!latest) {
833
+ // FULL checkpoint (first call after enable — captures ALL documents, including
834
+ // everything written before enableLiveBackup()).
835
+ const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
836
+ const dataPrefix = `${ckptPrefix}${baseTs}/data/`;
837
+ const filePaths = [];
838
+ await walkPartitions(this.dbPath, async (filePath) => { filePaths.push(filePath); });
839
+ // Pool uploads: sequential PUTs at ~15ms/object would make a 50k-doc initial
840
+ // checkpoint take ~12 minutes; 16 in flight brings it under a minute.
841
+ await pooledMap(filePaths, 16, async (filePath) => {
842
+ await this.uploadBytes(`${dataPrefix}${posixRel(filePath)}`, readFileSync(filePath), 'application/json');
843
+ });
844
+ const count = filePaths.length;
845
+ // Drain the dirty set: the full upload supersedes any pending incremental
846
+ // changes — otherwise the next incremental checkpoint would re-upload them.
847
+ engine.takeDirtyKeys();
848
+ await this.uploadBytes(`${ckptPrefix}${baseTs}/index.json`, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, createdAt: new Date().toISOString(), docCount: count }, null, 2)), 'application/json');
849
+ // latest.json is published LAST — it is the visibility marker for restore.
850
+ // Publishing it before the data objects are durable would let a concurrent
851
+ // restore read a checkpoint whose data is missing.
852
+ await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
853
+ this.liveCheckpoints++;
854
+ return { uploadedDocs: count, tombstonedDocs: 0, fullUpload: true, duration: Date.now() - start };
855
+ }
856
+ // INCREMENTAL checkpoint — upload ONLY dirty docs, tombstone deleted ones.
857
+ // Tombstones are required: the full checkpoint data still contains the deleted
858
+ // document, and its WAL DELETE entry (lsn ≤ baseLsn) is deliberately skipped by
859
+ // the restore replay filter — without a marker, deleted docs would resurrect.
860
+ const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
861
+ const dirty = engine.takeDirtyKeys();
862
+ let uploaded = 0, tombstoned = 0;
863
+ for (const key of dirty) {
864
+ const filePath = partitionedPath(this.dbPath, key);
865
+ const rel = posixRel(filePath);
866
+ if (existsSync(filePath)) {
867
+ await this.uploadBytes(`${dataPrefix}${rel}`, readFileSync(filePath), 'application/json');
868
+ uploaded++;
869
+ }
870
+ else {
871
+ await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream');
872
+ tombstoned++;
873
+ }
874
+ }
875
+ await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs: latest.baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString(), dirtyUploaded: uploaded, tombstoned }, null, 2)), 'application/json');
876
+ await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify({ nodeId: this.liveNodeId, updatedAt: new Date().toISOString(), lastShippedLsn: this.liveShipper?.status.lastShippedLsn ?? 0, lastCheckpointAt: new Date().toISOString() }, null, 2)), 'application/json');
877
+ this.liveCheckpoints++;
878
+ return { uploadedDocs: uploaded, tombstonedDocs: tombstoned, fullUpload: false, duration: Date.now() - start };
879
+ }
880
+ // __TERO_LIVE_PART3__
881
+ async restoreLiveToDirectory(targetDir, opts = {}) {
882
+ if (!this.s3Client || !this.config.cloudStorage)
883
+ throw new Error('Cloud storage not configured');
884
+ if (existsSync(targetDir) && readdirSync(targetDir).some(f => !f.startsWith('.'))) {
885
+ this.log.warn(`⚠️ restoreLiveToDirectory: target '${targetDir}' is not empty — restored state will be merged over existing files.`);
886
+ }
887
+ mkdirSync(targetDir, { recursive: true });
888
+ const pit = opts.pointInTime ?? Infinity;
889
+ let nodeId = opts.nodeId;
890
+ if (!nodeId) {
891
+ // Exact prefix slicing — NOT a regex on '/nodes/'. A regex would also match a
892
+ // user pathPrefix or database name containing "nodes" and restore from the
893
+ // wrong node (e.g. pathPrefix 'my/nodes/stuff' would capture 'stuff').
894
+ const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
895
+ const nodesPrefix = `${base}/${basename(this.dbPath)}/nodes/`;
896
+ const all = await this.listPrefix(nodesPrefix);
897
+ const ids = new Set();
898
+ for (const k of all) {
899
+ const id = k.slice(nodesPrefix.length).split('/')[0];
900
+ if (id)
901
+ ids.add(id);
902
+ }
903
+ if (ids.size === 0)
904
+ throw new Error('No live-backup nodes found in bucket.');
905
+ if (ids.size > 1)
906
+ throw new Error(`Multiple nodes found: ${[...ids].join(', ')}. Specify nodeId.`);
907
+ nodeId = [...ids][0];
908
+ }
909
+ const prefix = this.liveCloudPrefix(nodeId);
910
+ const latest = await this.readJsonOrDefault(`${prefix}checkpoint/latest.json`);
911
+ let docsRestored = 0;
912
+ let baseLsn = null;
913
+ if (latest) {
914
+ baseLsn = latest.baseLsn ?? null;
915
+ const dataKeys = await this.listPrefix(`${prefix}checkpoint/${latest.baseTs}/data/`);
916
+ const tombstoneKeyNames = new Set();
917
+ const activeDataKeys = [];
918
+ for (const dk of dataKeys) {
919
+ if (dk.endsWith('.deleted')) {
920
+ const keyName = basename(dk).replace(/\.json\.deleted$/, '');
921
+ tombstoneKeyNames.add(keyName);
922
+ }
923
+ else if (dk.endsWith('.json')) {
924
+ activeDataKeys.push(dk);
925
+ }
926
+ }
927
+ // Filter out any active key that has a tombstone so it is never downloaded or resurrected
928
+ const keysToDownload = activeDataKeys.filter(dk => {
929
+ const keyName = basename(dk).replace(/\.json$/, '');
930
+ return !tombstoneKeyNames.has(keyName);
931
+ });
932
+ // Pool downloads — sequential GETs make a 50k-doc restore take ~12 minutes.
933
+ await pooledMap(keysToDownload, 16, async (dk) => {
934
+ const key = basename(dk).replace(/\.json$/, '');
935
+ const dest = partitionedPath(targetDir, key);
936
+ const body = await this.downloadBytes(dk);
937
+ mkdirSync(dirname(dest), { recursive: true });
938
+ const tmp = `${dest}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
939
+ writeFileSync(tmp, body);
940
+ renameSync(tmp, dest);
941
+ docsRestored++;
942
+ });
943
+ // Ensure any existing local file matching a tombstone is deleted
944
+ for (const keyName of tombstoneKeyNames) {
945
+ const dest = partitionedPath(targetDir, keyName);
946
+ try {
947
+ if (existsSync(dest))
948
+ unlinkSync(dest);
949
+ }
950
+ catch { }
951
+ }
952
+ }
953
+ const walKeys = (await this.listPrefix(`${prefix}wal/`))
954
+ .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) > (baseLsn ?? 0) : false; }).sort();
955
+ // Detect LSN gaps between consecutive segments. Local WAL archives are pruned
956
+ // (keep-last-3) even while the bucket is unreachable, so an outage spanning
957
+ // >3MB of writes loses segments permanently. Small gaps are normal (filtered
958
+ // BEGIN/COMMIT/CHECKPOINT entries); gaps >50 LSNs mean real writes may be missing.
959
+ let prevEnd = -1;
960
+ for (const wk of walKeys) {
961
+ const m = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
962
+ const s = parseInt(m[1]), e = parseInt(m[2]);
963
+ if (prevEnd >= 0 && s - prevEnd - 1 > 50) {
964
+ this.log.warn(`⚠️ Live-backup WAL gap: ${s - prevEnd - 1} LSNs missing between shipped segments (bucket outage longer than local WAL retention?). Writes in the gap may be unrecoverable.`);
965
+ }
966
+ prevEnd = Math.max(prevEnd, e);
967
+ }
968
+ let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
969
+ const pending = new Map();
970
+ const apply = (e) => {
971
+ if (!e.key)
972
+ return;
973
+ const dest = partitionedPath(targetDir, e.key);
974
+ if (e.operation === 'WRITE') {
975
+ mkdirSync(dirname(dest), { recursive: true });
976
+ const tmp = `${dest}.tmp.${process.pid}`;
977
+ // Match the engine's data-file format exactly (atomicWriteFile uses
978
+ // JSON.stringify(data, null, 2)) so restored files are byte-identical
979
+ // to engine-written ones.
980
+ writeFileSync(tmp, JSON.stringify(e.afterImage ?? null, null, 2));
981
+ renameSync(tmp, dest);
982
+ }
983
+ else if (e.operation === 'DELETE') {
984
+ try {
985
+ unlinkSync(dest);
986
+ }
987
+ catch { }
988
+ }
989
+ lastLsn = Math.max(lastLsn, e.lsn);
990
+ };
991
+ for (const wk of walKeys) {
992
+ try {
993
+ const entries = JSON.parse(gunzipSync(await this.downloadBytes(wk)).toString('utf8'));
994
+ for (const e of entries) {
995
+ if (e.timestamp > pit)
996
+ continue;
997
+ if (e.lsn <= (baseLsn ?? 0))
998
+ continue; // already captured in checkpoint
999
+ if (e.operation === 'WRITE' || e.operation === 'DELETE') {
1000
+ if (!e.transactionId) {
1001
+ apply(e);
1002
+ continue;
1003
+ }
1004
+ if (!pending.has(e.transactionId))
1005
+ pending.set(e.transactionId, []);
1006
+ pending.get(e.transactionId).push(e);
1007
+ }
1008
+ else if (e.operation === 'COMMIT') {
1009
+ for (const w of pending.get(e.transactionId) ?? [])
1010
+ apply(w);
1011
+ pending.delete(e.transactionId);
1012
+ }
1013
+ else if (e.operation === 'ROLLBACK') {
1014
+ pending.delete(e.transactionId);
1015
+ }
1016
+ }
1017
+ segmentsReplayed++;
1018
+ }
1019
+ catch (e) {
1020
+ this.log.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
1021
+ }
1022
+ }
1023
+ return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn };
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Per-second WAL shipper. Reads new WRITE/DELETE entries from the WAL (current log
1028
+ * + any rotated archives) since the last shipped LSN, gzips them, and PUTs one
1029
+ * segment per active second-with-writes. Idle seconds produce zero PUTs.
1030
+ * In-flight guard: overlapping ticks are skipped. Status flips to 'degraded' on
1031
+ * any upload failure and auto-recovers on the next successful tick.
1032
+ */
1033
+ class WalShipper {
1034
+ deps;
1035
+ timer = null;
1036
+ shipping = false;
1037
+ lastLsn = 0;
1038
+ initialized = false;
1039
+ shippedArchives = new Set();
1040
+ /** Tick counter + per-archive retry schedule (throttles re-reads during outages). */
1041
+ tickCount = 0;
1042
+ archiveRetryAt = new Map();
1043
+ status;
1044
+ intervalMs;
1045
+ constructor(deps) {
1046
+ this.deps = deps;
1047
+ this.intervalMs = deps.intervalMs;
1048
+ this.status = { state: 'stopped', lastShippedLsn: 0, lastShipAt: 0, segmentsShipped: 0, totalBytesShipped: 0, errorCount: 0 };
1049
+ }
1050
+ start() {
1051
+ if (this.timer)
1052
+ return;
1053
+ if (!this.initialized) {
1054
+ this.lastLsn = this.deps.wal.getCurrentLSN();
1055
+ this.initialized = true;
1056
+ }
1057
+ this.status.state = 'healthy';
1058
+ this.timer = setInterval(() => { void this.tick(); }, this.deps.intervalMs);
1059
+ this.timer.unref?.();
1060
+ }
1061
+ stop() {
1062
+ if (this.timer) {
1063
+ clearInterval(this.timer);
1064
+ this.timer = null;
1065
+ }
1066
+ this.status.state = 'stopped';
1067
+ }
1068
+ async tick() {
1069
+ if (this.shipping)
1070
+ return;
1071
+ this.shipping = true;
1072
+ this.tickCount++;
1073
+ try {
1074
+ await this.shipArchives();
1075
+ // getLogEntries(fromLSN) filters lsn >= fromLSN (INCLUSIVE) — pass lastLsn + 1
1076
+ // or every tick would re-ship the final entry of the previous segment.
1077
+ // COMMIT/ROLLBACK markers must ship too (see WAL_SHIPPED_OPS) or restore
1078
+ // can never commit its buffered transactions.
1079
+ const entries = this.deps.wal.getLogEntries(this.lastLsn + 1).filter(e => WAL_SHIPPED_OPS.has(e.operation));
1080
+ if (entries.length === 0) {
1081
+ this.status.state = 'healthy';
1082
+ return;
1083
+ }
1084
+ const start = entries[0].lsn, end = entries[entries.length - 1].lsn;
1085
+ const body = gzipSync(Buffer.from(JSON.stringify(entries)), { level: 1 });
1086
+ await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(start)}-${padLsn(end)}.json.gz`, body);
1087
+ this.lastLsn = end;
1088
+ this.status.lastShippedLsn = end;
1089
+ this.status.lastShipAt = Date.now();
1090
+ this.status.segmentsShipped++;
1091
+ this.status.totalBytesShipped += body.length;
1092
+ this.status.state = 'healthy';
1093
+ this.status.lastError = undefined;
1094
+ }
1095
+ catch (e) {
1096
+ this.status.state = 'degraded';
1097
+ this.status.errorCount++;
1098
+ this.status.lastError = e instanceof Error ? e.message : String(e);
1099
+ }
1100
+ finally {
1101
+ this.shipping = false;
1102
+ }
1103
+ }
1104
+ async shipArchives() {
1105
+ const archives = this.deps.wal.listArchives();
1106
+ for (const p of archives) {
1107
+ if (this.shippedArchives.has(p))
1108
+ continue;
1109
+ // Throttle failing archives: without this, a bucket outage means every tick
1110
+ // re-reads and re-parses up to 3MB of archive JSON per second (wasted CPU
1111
+ // on a busy server). Retry each failing archive only every 5 ticks.
1112
+ const retryAt = this.archiveRetryAt.get(p);
1113
+ if (retryAt !== undefined && this.tickCount < retryAt)
1114
+ continue;
1115
+ try {
1116
+ const lines = readFileSync(p, 'utf8').trim().split('\n');
1117
+ const entries = [];
1118
+ for (const line of lines) {
1119
+ try {
1120
+ entries.push(JSON.parse(line));
1121
+ }
1122
+ catch { }
1123
+ }
1124
+ const fresh = entries.filter(e => WAL_SHIPPED_OPS.has(e.operation) && e.lsn > this.lastLsn);
1125
+ if (fresh.length > 0) {
1126
+ const s = fresh[0].lsn, en = fresh[fresh.length - 1].lsn;
1127
+ const body = gzipSync(Buffer.from(JSON.stringify(fresh)), { level: 1 });
1128
+ await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(s)}-${padLsn(en)}.json.gz`, body);
1129
+ this.lastLsn = en;
1130
+ this.status.lastShippedLsn = en;
1131
+ this.status.lastShipAt = Date.now();
1132
+ this.status.segmentsShipped++;
1133
+ this.status.totalBytesShipped += body.length;
1134
+ }
1135
+ this.shippedArchives.add(p);
1136
+ this.archiveRetryAt.delete(p);
1137
+ }
1138
+ catch (e) {
1139
+ this.archiveRetryAt.set(p, this.tickCount + 5);
1140
+ this.status.state = 'degraded';
1141
+ this.status.errorCount++;
1142
+ this.status.lastError = `archive:${e instanceof Error ? e.message : e}`;
1143
+ }
1144
+ }
585
1145
  }
586
1146
  }