tero 0.0.9 → 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,24 +1,58 @@
1
- import { createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, renameSync, unlinkSync } from "fs";
2
- import { join, basename, relative, dirname } from "path";
3
- import tar from "tar";
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
4
  import { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
5
- import { Upload } from "@aws-sdk/lib-storage";
6
5
  import { CronJob } from "cron";
7
6
  import { gzipSync, gunzipSync } from "zlib";
8
7
  import { randomUUID } from "crypto";
9
8
  import { partitionedPath, walkPartitions } from "./acid-engine.js";
10
- /** LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort. */
9
+ /**
10
+ * LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort.
11
+ */
11
12
  function padLsn(lsn) {
12
13
  return lsn.toString().padStart(16, '0');
13
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
+ }
14
43
  export class BackupManager {
15
44
  s3Client;
16
45
  scheduledBackups = new Map();
17
46
  config;
18
47
  dbPath;
48
+ /** Injected or default logger (see BackupConfig.logger). */
49
+ log;
19
50
  constructor(dbPath, config) {
20
51
  this.dbPath = dbPath;
21
52
  this.config = config;
53
+ this.log = config.logger === 'silent'
54
+ ? { info: () => { }, warn: () => { }, error: () => { } }
55
+ : (config.logger ?? console);
22
56
  if (config.cloudStorage) {
23
57
  this.initializeCloudStorage(config.cloudStorage);
24
58
  }
@@ -40,7 +74,7 @@ export class BackupManager {
40
74
  this.s3Client = new S3Client(clientConfig);
41
75
  }
42
76
  catch (error) {
43
- 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 });
44
78
  }
45
79
  }
46
80
  parseInterval(interval) {
@@ -145,7 +179,7 @@ export class BackupManager {
145
179
  return files;
146
180
  }
147
181
  catch (error) {
148
- 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 });
149
183
  }
150
184
  }
151
185
  async createArchiveBackup() {
@@ -168,7 +202,7 @@ export class BackupManager {
168
202
  // 2-level hash-prefix partition dirs are preserved in the archive.
169
203
  // (was: jsonFiles.map(f => f.name) — broke when files moved to XX/YY/key.json)
170
204
  const fileList = jsonFiles.map(f => f.path.slice(this.dbPath.length + 1));
171
- await tar.create({
205
+ await tarCreate({
172
206
  file: backupPath,
173
207
  cwd: this.dbPath,
174
208
  gzip: true,
@@ -187,7 +221,7 @@ export class BackupManager {
187
221
  return { filePath: backupPath, metadata };
188
222
  }
189
223
  catch (error) {
190
- 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 });
191
225
  }
192
226
  }
193
227
  async createIndividualBackup() {
@@ -257,7 +291,7 @@ export class BackupManager {
257
291
  return { files: backedUpFiles, metadata };
258
292
  }
259
293
  catch (error) {
260
- 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 });
261
295
  }
262
296
  }
263
297
  async uploadToCloud(localPath, cloudKey) {
@@ -265,26 +299,25 @@ export class BackupManager {
265
299
  throw new Error('Cloud storage not configured');
266
300
  }
267
301
  try {
268
- const fileStream = createReadStream(localPath);
269
- const stats = statSync(localPath);
270
- const upload = new Upload({
271
- client: this.s3Client,
272
- params: {
273
- Bucket: this.config.cloudStorage.bucket,
274
- Key: cloudKey,
275
- Body: fileStream,
276
- ContentLength: stats.size,
277
- Metadata: {
278
- 'backup-timestamp': new Date().toISOString(),
279
- 'source-db': basename(this.dbPath),
280
- 'backup-format': this.config.format
281
- }
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
282
315
  }
283
316
  });
284
- await upload.done();
317
+ await this.s3Client.send(cmd);
285
318
  }
286
319
  catch (error) {
287
- 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 });
288
321
  }
289
322
  }
290
323
  async uploadDirectoryToCloud(localDir, cloudPrefix) {
@@ -294,15 +327,16 @@ export class BackupManager {
294
327
  try {
295
328
  const fs = await import('fs/promises');
296
329
  const files = await fs.readdir(localDir);
297
- 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) => {
298
333
  const localFilePath = join(localDir, file);
299
334
  const cloudKey = `${cloudPrefix}/${file}`;
300
335
  await this.uploadToCloud(localFilePath, cloudKey);
301
336
  });
302
- await Promise.all(uploadPromises);
303
337
  }
304
338
  catch (error) {
305
- 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 });
306
340
  }
307
341
  }
308
342
  async uploadIndividualFilesToCloud(localDir) {
@@ -312,18 +346,17 @@ export class BackupManager {
312
346
  try {
313
347
  const fs = await import('fs/promises');
314
348
  const files = await fs.readdir(localDir);
315
- const uploadPromises = files
316
- .filter(file => file.endsWith('.json')) // Only upload JSON files, skip metadata
317
- .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) => {
318
352
  const localFilePath = join(localDir, file);
319
353
  // Use direct key-based cloud storage: each JSON file is stored with its key as the cloud key
320
354
  const cloudKey = this.getCloudKey(file);
321
355
  await this.uploadToCloud(localFilePath, cloudKey);
322
356
  });
323
- await Promise.all(uploadPromises);
324
357
  }
325
358
  catch (error) {
326
- 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 });
327
360
  }
328
361
  }
329
362
  getCloudKey(filename) {
@@ -333,7 +366,7 @@ export class BackupManager {
333
366
  }
334
367
  async performBackup() {
335
368
  try {
336
- console.log(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
369
+ this.log.info(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
337
370
  let metadata;
338
371
  let cloudUploaded = false;
339
372
  if (this.config.format === 'archive') {
@@ -344,20 +377,28 @@ export class BackupManager {
344
377
  const cloudKey = this.getCloudKey(basename(filePath));
345
378
  await this.uploadToCloud(filePath, cloudKey);
346
379
  cloudUploaded = true;
347
- console.log(`☁️ Uploaded archive backup to cloud: ${cloudKey}`);
380
+ this.log.info(`☁️ Uploaded archive backup to cloud: ${cloudKey}`);
348
381
  }
349
- console.log(`✅ Archive backup completed: ${filePath}`);
382
+ this.log.info(`✅ Archive backup completed: ${filePath}`);
350
383
  }
351
384
  else {
352
385
  const { files, metadata: backupMetadata } = await this.createIndividualBackup();
353
386
  metadata = backupMetadata;
354
387
  // Upload to cloud if configured - use key-based storage for direct recovery
355
388
  if (this.config.cloudStorage && this.s3Client) {
356
- 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
+ }
357
398
  cloudUploaded = true;
358
- console.log(`☁️ Uploaded individual backup to cloud using key-based storage`);
399
+ this.log.info(`☁️ Uploaded individual backup to cloud using key-based storage`);
359
400
  }
360
- console.log(`✅ Individual backup completed: ${files.length} files`);
401
+ this.log.info(`✅ Individual backup completed: ${files.length} files`);
361
402
  }
362
403
  // Clean up old backups based on retention policy
363
404
  if (this.config.retention) {
@@ -366,7 +407,7 @@ export class BackupManager {
366
407
  return { success: true, metadata, cloudUploaded };
367
408
  }
368
409
  catch (error) {
369
- console.error(`❌ Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
410
+ this.log.error(`❌ Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
370
411
  return {
371
412
  success: false,
372
413
  metadata: {
@@ -388,13 +429,26 @@ export class BackupManager {
388
429
  const retentionMs = this.parseRetention(this.config.retention);
389
430
  const cutoffDate = new Date(Date.now() - retentionMs);
390
431
  const prefix = this.getCloudKey('');
391
- const listCommand = new ListObjectsV2Command({
392
- Bucket: this.config.cloudStorage.bucket,
393
- Prefix: prefix
394
- });
395
- const response = await this.s3Client.send(listCommand);
396
- if (response.Contents) {
397
- 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) {
398
452
  const deletePromises = oldObjects.map((obj) => {
399
453
  if (obj.Key) {
400
454
  return this.s3Client.send(new DeleteObjectCommand({
@@ -406,12 +460,12 @@ export class BackupManager {
406
460
  }).filter(Boolean);
407
461
  await Promise.all(deletePromises);
408
462
  if (oldObjects.length > 0) {
409
- 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`);
410
464
  }
411
465
  }
412
466
  }
413
467
  catch (error) {
414
- 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'}`);
415
469
  }
416
470
  }
417
471
  scheduleBackup(config) {
@@ -424,7 +478,7 @@ export class BackupManager {
424
478
  this.config.retention = config.retention;
425
479
  }
426
480
  const performScheduledBackup = async () => {
427
- console.log(`⏰ Scheduled backup triggered (${config.interval} interval)`);
481
+ this.log.info(`⏰ Scheduled backup triggered (${config.interval} interval)`);
428
482
  await this.performBackup();
429
483
  };
430
484
  // Create cron job for recurring backups
@@ -433,11 +487,11 @@ export class BackupManager {
433
487
  'UTC' // timezone
434
488
  );
435
489
  this.scheduledBackups.set(scheduleId, cronJob);
436
- 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`);
437
491
  return scheduleId;
438
492
  }
439
493
  catch (error) {
440
- 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 });
441
495
  }
442
496
  }
443
497
  cancelScheduledBackup(scheduleId) {
@@ -445,7 +499,7 @@ export class BackupManager {
445
499
  if (cronJob) {
446
500
  cronJob.stop();
447
501
  this.scheduledBackups.delete(scheduleId);
448
- console.log(`❌ Cancelled scheduled backup: ${scheduleId}`);
502
+ this.log.info(`❌ Cancelled scheduled backup: ${scheduleId}`);
449
503
  return true;
450
504
  }
451
505
  return false;
@@ -500,9 +554,12 @@ export class BackupManager {
500
554
  };
501
555
  }
502
556
  try {
503
- // 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.
504
561
  const jsonFiles = await this.getJsonFiles();
505
- for (const file of jsonFiles) {
562
+ await pooledMap(jsonFiles, 16, async (file) => {
506
563
  try {
507
564
  const cloudKey = this.getCloudKey(file.name);
508
565
  await this.uploadToCloud(file.path, cloudKey);
@@ -511,12 +568,12 @@ export class BackupManager {
511
568
  catch (error) {
512
569
  errors.push(`data:${file.name}:${error instanceof Error ? error.message : 'Unknown error'}`);
513
570
  }
514
- }
571
+ });
515
572
  // 2) Stream WAL archive segments the caller wants persisted.
516
573
  const walPaths = options?.walArchivePaths ?? [];
517
- for (const archivePath of walPaths) {
574
+ await pooledMap(walPaths, 16, async (archivePath) => {
518
575
  if (!existsSync(archivePath))
519
- continue;
576
+ return;
520
577
  try {
521
578
  const segName = basename(archivePath);
522
579
  const prefix = this.config.cloudStorage.pathPrefix || 'tero-backups';
@@ -528,7 +585,7 @@ export class BackupManager {
528
585
  catch (error) {
529
586
  errors.push(`wal:${basename(archivePath)}:${error instanceof Error ? error.message : 'Unknown error'}`);
530
587
  }
531
- }
588
+ });
532
589
  // 3) Emit a backup manifest so hydrate-on-startup can discover the latest snapshot.
533
590
  try {
534
591
  const manifest = {
@@ -588,13 +645,20 @@ export class BackupManager {
588
645
  liveEngine;
589
646
  livePrefix;
590
647
  liveCheckpoints = 0;
648
+ /** In-flight checkpoint (shared promise: concurrent callers await the same run). */
649
+ liveCheckpointPromise;
650
+ lastCheckpointError;
591
651
  destroy() {
592
652
  for (const [id, cronJob] of this.scheduledBackups)
593
653
  cronJob.stop();
594
654
  this.scheduledBackups.clear();
595
- if (this.liveShipper)
655
+ // Clear the reference too — the automatic initial-checkpoint retry loop
656
+ // checks it and must stop retrying after destroy.
657
+ if (this.liveShipper) {
596
658
  this.liveShipper.stop();
597
- console.log('🛑 BackupManager destroyed, all scheduled backups cancelled');
659
+ this.liveShipper = undefined;
660
+ }
661
+ this.log.info('🛑 BackupManager destroyed, all scheduled backups cancelled');
598
662
  }
599
663
  liveCloudPrefix(nodeId) {
600
664
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
@@ -652,6 +716,10 @@ export class BackupManager {
652
716
  if (!this.s3Client || !this.config.cloudStorage)
653
717
  throw new Error('Cloud storage not configured — call configureBackup() with cloudStorage first.');
654
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.
655
723
  let nodeId = opts.nodeId;
656
724
  const idFile = join(this.dbPath, '.tero-node-id');
657
725
  if (!nodeId) {
@@ -659,9 +727,13 @@ export class BackupManager {
659
727
  nodeId = readFileSync(idFile, 'utf8').trim();
660
728
  }
661
729
  catch {
662
- nodeId = randomUUID().replace(/-/g, '').slice(0, 16);
730
+ nodeId = '';
663
731
  }
664
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);
665
737
  try {
666
738
  writeFileSync(idFile, nodeId, 'utf8');
667
739
  }
@@ -670,16 +742,41 @@ export class BackupManager {
670
742
  this.liveNodeId = nodeId;
671
743
  this.liveEngine = engine;
672
744
  this.livePrefix = prefix;
745
+ this.lastCheckpointError = undefined;
673
746
  this.liveShipper = new WalShipper({ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs });
674
747
  this.liveShipper.start();
675
- console.log(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
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
+ }
676
773
  }
677
774
  disableLiveBackup() {
678
775
  if (!this.liveShipper)
679
776
  return;
680
777
  this.liveShipper.stop();
681
778
  this.liveShipper = undefined;
682
- console.log('🛑 Tero live backup disabled');
779
+ this.log.info('🛑 Tero live backup disabled');
683
780
  }
684
781
  getLiveBackupStatus() {
685
782
  const s = this.liveShipper?.status;
@@ -689,60 +786,119 @@ export class BackupManager {
689
786
  secondsSinceLastShip: s?.lastShipAt ? Math.round((Date.now() - s.lastShipAt) / 1000) : 0,
690
787
  segmentsShipped: s?.segmentsShipped ?? 0, checkpointsTaken: this.liveCheckpoints,
691
788
  errorCount: s?.errorCount ?? 0, lastError: s?.lastError,
789
+ lastCheckpointError: this.lastCheckpointError,
692
790
  };
693
791
  }
694
792
  // __TERO_LIVE_PART2__
695
793
  async liveCheckpointToBucket(_opts) {
696
794
  if (!this.liveEngine || !this.liveNodeId || !this.livePrefix)
697
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;
698
817
  const start = Date.now();
699
818
  const ckptPrefix = `${this.livePrefix}checkpoint/`;
700
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('/');
701
831
  const latest = await this.readJsonOrDefault(latestKey);
702
- const wal = this.liveEngine.getWAL();
703
- const dirty = this.liveEngine.takeDirtyKeys();
704
832
  if (!latest) {
833
+ // FULL checkpoint (first call after enable — captures ALL documents, including
834
+ // everything written before enableLiveBackup()).
705
835
  const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
706
836
  const dataPrefix = `${ckptPrefix}${baseTs}/data/`;
707
- let count = 0;
708
- await walkPartitions(this.dbPath, async (filePath) => {
709
- await this.uploadBytes(`${dataPrefix}${relative(this.dbPath, filePath)}`, readFileSync(filePath), 'application/json');
710
- count++;
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');
711
843
  });
712
- await this.uploadBytes(`${ckptPrefix}${baseTs}/index.json`, Buffer.from(JSON.stringify({ baseTs, baseLsn: wal.getCurrentLSN(), createdAt: new Date().toISOString(), docCount: count }, null, 2)), 'application/json');
713
- await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: wal.getCurrentLSN(), updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
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');
714
853
  this.liveCheckpoints++;
715
- return { uploadedDocs: count, fullUpload: true, duration: Date.now() - start };
854
+ return { uploadedDocs: count, tombstonedDocs: 0, fullUpload: true, duration: Date.now() - start };
716
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.
717
860
  const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
718
- let uploaded = 0;
861
+ const dirty = engine.takeDirtyKeys();
862
+ let uploaded = 0, tombstoned = 0;
719
863
  for (const key of dirty) {
720
864
  const filePath = partitionedPath(this.dbPath, key);
865
+ const rel = posixRel(filePath);
721
866
  if (existsSync(filePath)) {
722
- await this.uploadBytes(`${dataPrefix}${relative(this.dbPath, filePath)}`, readFileSync(filePath), 'application/json');
867
+ await this.uploadBytes(`${dataPrefix}${rel}`, readFileSync(filePath), 'application/json');
723
868
  uploaded++;
724
869
  }
870
+ else {
871
+ await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream');
872
+ tombstoned++;
873
+ }
725
874
  }
726
- await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs: latest.baseTs, baseLsn: wal.getCurrentLSN(), updatedAt: new Date().toISOString(), dirtyUploaded: uploaded }, null, 2)), 'application/json');
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');
727
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');
728
877
  this.liveCheckpoints++;
729
- return { uploadedDocs: uploaded, fullUpload: false, duration: Date.now() - start };
878
+ return { uploadedDocs: uploaded, tombstonedDocs: tombstoned, fullUpload: false, duration: Date.now() - start };
730
879
  }
731
880
  // __TERO_LIVE_PART3__
732
881
  async restoreLiveToDirectory(targetDir, opts = {}) {
733
882
  if (!this.s3Client || !this.config.cloudStorage)
734
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
+ }
735
887
  mkdirSync(targetDir, { recursive: true });
736
888
  const pit = opts.pointInTime ?? Infinity;
737
889
  let nodeId = opts.nodeId;
738
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').
739
894
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
740
- const all = await this.listPrefix(`${base}/${basename(this.dbPath)}/nodes/`);
895
+ const nodesPrefix = `${base}/${basename(this.dbPath)}/nodes/`;
896
+ const all = await this.listPrefix(nodesPrefix);
741
897
  const ids = new Set();
742
898
  for (const k of all) {
743
- const m = k.match(/\/nodes\/([^/]+)\//);
744
- if (m)
745
- ids.add(m[1]);
899
+ const id = k.slice(nodesPrefix.length).split('/')[0];
900
+ if (id)
901
+ ids.add(id);
746
902
  }
747
903
  if (ids.size === 0)
748
904
  throw new Error('No live-backup nodes found in bucket.');
@@ -757,21 +913,58 @@ export class BackupManager {
757
913
  if (latest) {
758
914
  baseLsn = latest.baseLsn ?? null;
759
915
  const dataKeys = await this.listPrefix(`${prefix}checkpoint/${latest.baseTs}/data/`);
916
+ const tombstoneKeyNames = new Set();
917
+ const activeDataKeys = [];
760
918
  for (const dk of dataKeys) {
761
- if (dk.endsWith('.deleted'))
762
- continue;
763
- const body = await this.downloadBytes(dk);
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) => {
764
934
  const key = basename(dk).replace(/\.json$/, '');
765
935
  const dest = partitionedPath(targetDir, key);
936
+ const body = await this.downloadBytes(dk);
766
937
  mkdirSync(dirname(dest), { recursive: true });
767
- const tmp = `${dest}.tmp.${process.pid}`;
938
+ const tmp = `${dest}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
768
939
  writeFileSync(tmp, body);
769
940
  renameSync(tmp, dest);
770
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 { }
771
951
  }
772
952
  }
773
953
  const walKeys = (await this.listPrefix(`${prefix}wal/`))
774
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
+ }
775
968
  let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
776
969
  const pending = new Map();
777
970
  const apply = (e) => {
@@ -781,7 +974,10 @@ export class BackupManager {
781
974
  if (e.operation === 'WRITE') {
782
975
  mkdirSync(dirname(dest), { recursive: true });
783
976
  const tmp = `${dest}.tmp.${process.pid}`;
784
- writeFileSync(tmp, JSON.stringify(e.afterImage ?? null));
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));
785
981
  renameSync(tmp, dest);
786
982
  }
787
983
  else if (e.operation === 'DELETE') {
@@ -821,7 +1017,7 @@ export class BackupManager {
821
1017
  segmentsReplayed++;
822
1018
  }
823
1019
  catch (e) {
824
- console.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
1020
+ this.log.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
825
1021
  }
826
1022
  }
827
1023
  return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn };
@@ -841,6 +1037,9 @@ class WalShipper {
841
1037
  lastLsn = 0;
842
1038
  initialized = false;
843
1039
  shippedArchives = new Set();
1040
+ /** Tick counter + per-archive retry schedule (throttles re-reads during outages). */
1041
+ tickCount = 0;
1042
+ archiveRetryAt = new Map();
844
1043
  status;
845
1044
  intervalMs;
846
1045
  constructor(deps) {
@@ -870,9 +1069,14 @@ class WalShipper {
870
1069
  if (this.shipping)
871
1070
  return;
872
1071
  this.shipping = true;
1072
+ this.tickCount++;
873
1073
  try {
874
1074
  await this.shipArchives();
875
- const entries = this.deps.wal.getLogEntries(this.lastLsn).filter(e => e.operation === 'WRITE' || e.operation === 'DELETE');
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));
876
1080
  if (entries.length === 0) {
877
1081
  this.status.state = 'healthy';
878
1082
  return;
@@ -902,6 +1106,12 @@ class WalShipper {
902
1106
  for (const p of archives) {
903
1107
  if (this.shippedArchives.has(p))
904
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;
905
1115
  try {
906
1116
  const lines = readFileSync(p, 'utf8').trim().split('\n');
907
1117
  const entries = [];
@@ -911,7 +1121,7 @@ class WalShipper {
911
1121
  }
912
1122
  catch { }
913
1123
  }
914
- const fresh = entries.filter(e => (e.operation === 'WRITE' || e.operation === 'DELETE') && e.lsn > this.lastLsn);
1124
+ const fresh = entries.filter(e => WAL_SHIPPED_OPS.has(e.operation) && e.lsn > this.lastLsn);
915
1125
  if (fresh.length > 0) {
916
1126
  const s = fresh[0].lsn, en = fresh[fresh.length - 1].lsn;
917
1127
  const body = gzipSync(Buffer.from(JSON.stringify(fresh)), { level: 1 });
@@ -923,8 +1133,10 @@ class WalShipper {
923
1133
  this.status.totalBytesShipped += body.length;
924
1134
  }
925
1135
  this.shippedArchives.add(p);
1136
+ this.archiveRetryAt.delete(p);
926
1137
  }
927
1138
  catch (e) {
1139
+ this.archiveRetryAt.set(p, this.tickCount + 5);
928
1140
  this.status.state = 'degraded';
929
1141
  this.status.errorCount++;
930
1142
  this.status.lastError = `archive:${e instanceof Error ? e.message : e}`;