tero 0.0.9 → 0.0.12

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,59 @@
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, openSync, fsyncSync, closeSync } 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
5
  import { Upload } from "@aws-sdk/lib-storage";
6
6
  import { CronJob } from "cron";
7
7
  import { gzipSync, gunzipSync } from "zlib";
8
8
  import { randomUUID } from "crypto";
9
9
  import { partitionedPath, walkPartitions } from "./acid-engine.js";
10
- /** LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort. */
10
+ /**
11
+ * LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort.
12
+ */
11
13
  function padLsn(lsn) {
12
14
  return lsn.toString().padStart(16, '0');
13
15
  }
16
+ /**
17
+ * WAL operations that get shipped in segments. COMMIT/ROLLBACK markers are
18
+ * ESSENTIAL: restore buffers WRITE/DELETE entries per transactionId and only
19
+ * applies them when the transaction's COMMIT arrives (discarding on ROLLBACK).
20
+ * Shipping data entries without commit markers would make every replayed
21
+ * transaction uncommitted — i.e. restore would silently drop ALL WAL-shipped
22
+ * writes. Only BEGIN and CHECKPOINT (pure metadata) are excluded.
23
+ */
24
+ const WAL_SHIPPED_OPS = new Set(['WRITE', 'DELETE', 'COMMIT', 'ROLLBACK']);
25
+ /**
26
+ * Bounded-concurrency mapper. Runs `fn` over `items` with at most `limit`
27
+ * promises in flight. Errors reject the whole promise (first failure wins) —
28
+ * callers that want per-item resilience wrap fn in their own try/catch.
29
+ */
30
+ async function pooledMap(items, limit, fn) {
31
+ const results = new Array(items.length);
32
+ let next = 0;
33
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
34
+ while (true) {
35
+ const i = next++;
36
+ if (i >= items.length)
37
+ return;
38
+ results[i] = await fn(items[i]);
39
+ }
40
+ });
41
+ await Promise.all(workers);
42
+ return results;
43
+ }
14
44
  export class BackupManager {
15
45
  s3Client;
16
46
  scheduledBackups = new Map();
17
47
  config;
18
48
  dbPath;
49
+ /** Injected or default logger (see BackupConfig.logger). */
50
+ log;
19
51
  constructor(dbPath, config) {
20
52
  this.dbPath = dbPath;
21
53
  this.config = config;
54
+ this.log = config.logger && config.logger !== 'silent'
55
+ ? config.logger
56
+ : { info: () => { }, warn: () => { }, error: () => { } };
22
57
  if (config.cloudStorage) {
23
58
  this.initializeCloudStorage(config.cloudStorage);
24
59
  }
@@ -40,7 +75,7 @@ export class BackupManager {
40
75
  this.s3Client = new S3Client(clientConfig);
41
76
  }
42
77
  catch (error) {
43
- throw new Error(`Failed to initialize cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`);
78
+ throw new Error(`Failed to initialize cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
44
79
  }
45
80
  }
46
81
  parseInterval(interval) {
@@ -145,7 +180,7 @@ export class BackupManager {
145
180
  return files;
146
181
  }
147
182
  catch (error) {
148
- throw new Error(`Failed to get JSON files: ${error instanceof Error ? error.message : 'Unknown error'}`);
183
+ throw new Error(`Failed to get JSON files: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
149
184
  }
150
185
  }
151
186
  async createArchiveBackup() {
@@ -168,7 +203,7 @@ export class BackupManager {
168
203
  // 2-level hash-prefix partition dirs are preserved in the archive.
169
204
  // (was: jsonFiles.map(f => f.name) — broke when files moved to XX/YY/key.json)
170
205
  const fileList = jsonFiles.map(f => f.path.slice(this.dbPath.length + 1));
171
- await tar.create({
206
+ await tarCreate({
172
207
  file: backupPath,
173
208
  cwd: this.dbPath,
174
209
  gzip: true,
@@ -187,7 +222,7 @@ export class BackupManager {
187
222
  return { filePath: backupPath, metadata };
188
223
  }
189
224
  catch (error) {
190
- throw new Error(`Failed to create archive backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
225
+ throw new Error(`Failed to create archive backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
191
226
  }
192
227
  }
193
228
  async createIndividualBackup() {
@@ -257,7 +292,7 @@ export class BackupManager {
257
292
  return { files: backedUpFiles, metadata };
258
293
  }
259
294
  catch (error) {
260
- throw new Error(`Failed to create individual backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
295
+ throw new Error(`Failed to create individual backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
261
296
  }
262
297
  }
263
298
  async uploadToCloud(localPath, cloudKey) {
@@ -265,26 +300,49 @@ export class BackupManager {
265
300
  throw new Error('Cloud storage not configured');
266
301
  }
267
302
  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
- }
303
+ if (!existsSync(localPath))
304
+ return;
305
+ const stat = statSync(localPath);
306
+ // Stream large files (>5MB) via multipart Upload to avoid loading entire file into heap (OOM on tar.gz)
307
+ const isLarge = stat.size > 5 * 1024 * 1024;
308
+ if (isLarge) {
309
+ const stream = createReadStream(localPath);
310
+ const upload = new Upload({
311
+ client: this.s3Client,
312
+ params: {
313
+ Bucket: this.config.cloudStorage.bucket,
314
+ Key: cloudKey,
315
+ Body: stream,
316
+ ContentType: cloudKey.endsWith('.json') ? 'application/json' : 'application/octet-stream',
317
+ Metadata: {
318
+ 'backup-timestamp': new Date().toISOString(),
319
+ 'source-db': this.getDbName(),
320
+ 'backup-format': this.config.format
321
+ }
322
+ },
323
+ queueSize: 4,
324
+ partSize: 5 * 1024 * 1024,
325
+ });
326
+ await upload.done();
327
+ return;
328
+ }
329
+ const fs = await import('fs/promises');
330
+ const body = await fs.readFile(localPath);
331
+ const cmd = new PutObjectCommand({
332
+ Bucket: this.config.cloudStorage.bucket,
333
+ Key: cloudKey,
334
+ Body: body,
335
+ ContentType: cloudKey.endsWith('.json') ? 'application/json' : 'application/octet-stream',
336
+ Metadata: {
337
+ 'backup-timestamp': new Date().toISOString(),
338
+ 'source-db': this.getDbName(),
339
+ 'backup-format': this.config.format
282
340
  }
283
341
  });
284
- await upload.done();
342
+ await this.s3Client.send(cmd);
285
343
  }
286
344
  catch (error) {
287
- throw new Error(`Failed to upload to cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`);
345
+ throw new Error(`Failed to upload to cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
288
346
  }
289
347
  }
290
348
  async uploadDirectoryToCloud(localDir, cloudPrefix) {
@@ -294,15 +352,16 @@ export class BackupManager {
294
352
  try {
295
353
  const fs = await import('fs/promises');
296
354
  const files = await fs.readdir(localDir);
297
- const uploadPromises = files.map(async (file) => {
355
+ // Bounded concurrency — unbounded Promise.all would open files.length
356
+ // simultaneous S3 streams and exhaust file descriptors at 20k+ docs.
357
+ await pooledMap(files, 16, async (file) => {
298
358
  const localFilePath = join(localDir, file);
299
359
  const cloudKey = `${cloudPrefix}/${file}`;
300
360
  await this.uploadToCloud(localFilePath, cloudKey);
301
361
  });
302
- await Promise.all(uploadPromises);
303
362
  }
304
363
  catch (error) {
305
- throw new Error(`Failed to upload directory to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`);
364
+ throw new Error(`Failed to upload directory to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
306
365
  }
307
366
  }
308
367
  async uploadIndividualFilesToCloud(localDir) {
@@ -312,28 +371,57 @@ export class BackupManager {
312
371
  try {
313
372
  const fs = await import('fs/promises');
314
373
  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) => {
374
+ const jsonFiles = files.filter(file => file.endsWith('.json'));
375
+ // Bounded concurrency — same reason as uploadDirectoryToCloud.
376
+ await pooledMap(jsonFiles, 16, async (file) => {
318
377
  const localFilePath = join(localDir, file);
319
378
  // Use direct key-based cloud storage: each JSON file is stored with its key as the cloud key
320
379
  const cloudKey = this.getCloudKey(file);
321
380
  await this.uploadToCloud(localFilePath, cloudKey);
322
381
  });
323
- await Promise.all(uploadPromises);
324
382
  }
325
383
  catch (error) {
326
- throw new Error(`Failed to upload individual files to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`);
384
+ throw new Error(`Failed to upload individual files to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
385
+ }
386
+ }
387
+ /**
388
+ * Derive a collision-free bucket key prefix for this DB instance.
389
+ * The old `basename(dbPath)` implementation made `/tmp/a/TeroDB` and
390
+ * `/tmp/b/TeroDB` collide on the same prefix (cross-tenant overwrite).
391
+ * We now use `pathPrefix/<safeDbName>` where `safeDbName` is derived from
392
+ * the FULL resolved path when a custom `dbName` isn't supplied.
393
+ * Explicit `cloudStorage.dbName` or `BackupConfig.bucketPrefix` takes
394
+ * precedence for callers who want stable, human-readable prefixes.
395
+ */
396
+ getDbName() {
397
+ // Allow caller to override — useful for stable bucket layouts
398
+ const override = this.config.cloudStorage?.dbName || this.config?.bucketPrefix;
399
+ if (typeof override === 'string' && override.trim()) {
400
+ return override.trim().replace(/^\/+|\/+$/g, '').replace(/[^a-zA-Z0-9_\-]/g, '_').slice(0, 128);
327
401
  }
402
+ // Default: hash the full resolved path to avoid collisions, keeping basename for readability
403
+ const base = basename(this.dbPath) || 'tero';
404
+ // Use a short hash of the full path so different directories with same basename diverge
405
+ const full = this.dbPath;
406
+ let h = 0x811c9dc5;
407
+ for (let i = 0; i < full.length; i++) {
408
+ h ^= full.charCodeAt(i);
409
+ h = Math.imul(h, 0x01000193) >>> 0;
410
+ }
411
+ const suffix = h.toString(16).padStart(8, '0').slice(0, 6);
412
+ return `${base}-${suffix}`;
328
413
  }
329
414
  getCloudKey(filename) {
330
415
  const prefix = this.config.cloudStorage?.pathPrefix || 'tero-backups';
331
- const dbName = basename(this.dbPath);
332
- return `${prefix}/${dbName}/${filename}`;
416
+ const dbName = this.getDbName();
417
+ // filename is already sanitized (key + ".json" or archive name); avoid double slashes
418
+ if (!filename)
419
+ return `${prefix}/${dbName}/`;
420
+ return `${prefix}/${dbName}/${filename.replace(/^\/+/, '')}`;
333
421
  }
334
422
  async performBackup() {
335
423
  try {
336
- console.log(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
424
+ this.log.info(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
337
425
  let metadata;
338
426
  let cloudUploaded = false;
339
427
  if (this.config.format === 'archive') {
@@ -344,20 +432,28 @@ export class BackupManager {
344
432
  const cloudKey = this.getCloudKey(basename(filePath));
345
433
  await this.uploadToCloud(filePath, cloudKey);
346
434
  cloudUploaded = true;
347
- console.log(`☁️ Uploaded archive backup to cloud: ${cloudKey}`);
435
+ this.log.info(`☁️ Uploaded archive backup to cloud: ${cloudKey}`);
348
436
  }
349
- console.log(`✅ Archive backup completed: ${filePath}`);
437
+ this.log.info(`✅ Archive backup completed: ${filePath}`);
350
438
  }
351
439
  else {
352
440
  const { files, metadata: backupMetadata } = await this.createIndividualBackup();
353
441
  metadata = backupMetadata;
354
442
  // Upload to cloud if configured - use key-based storage for direct recovery
355
443
  if (this.config.cloudStorage && this.s3Client) {
356
- await this.uploadIndividualFilesToCloud(files[0].split('/').slice(0, -1).join('/'));
444
+ // Derive the backup directory via path.dirname — the previous
445
+ // files[0].split('/') was POSIX-only and threw if files was empty.
446
+ const backupDir = files.length > 0 ? dirname(files[0]) : (this.config.localPath || join(this.dbPath, '.backup'));
447
+ if (files.length === 0) {
448
+ this.log.warn('⚠️ No files to upload to cloud — backup produced no data files');
449
+ }
450
+ else {
451
+ await this.uploadIndividualFilesToCloud(backupDir);
452
+ }
357
453
  cloudUploaded = true;
358
- console.log(`☁️ Uploaded individual backup to cloud using key-based storage`);
454
+ this.log.info(`☁️ Uploaded individual backup to cloud using key-based storage`);
359
455
  }
360
- console.log(`✅ Individual backup completed: ${files.length} files`);
456
+ this.log.info(`✅ Individual backup completed: ${files.length} files`);
361
457
  }
362
458
  // Clean up old backups based on retention policy
363
459
  if (this.config.retention) {
@@ -366,7 +462,7 @@ export class BackupManager {
366
462
  return { success: true, metadata, cloudUploaded };
367
463
  }
368
464
  catch (error) {
369
- console.error(`❌ Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
465
+ this.log.error(`❌ Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
370
466
  return {
371
467
  success: false,
372
468
  metadata: {
@@ -388,13 +484,26 @@ export class BackupManager {
388
484
  const retentionMs = this.parseRetention(this.config.retention);
389
485
  const cutoffDate = new Date(Date.now() - retentionMs);
390
486
  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);
487
+ // Paginate ALL pages — a single ListObjectsV2 returns at most 1000 keys,
488
+ // so with more objects than that, retention silently stopped deleting
489
+ // everything past the first page (unbounded bucket growth + cost).
490
+ const oldObjects = [];
491
+ let token;
492
+ do {
493
+ const response = await this.s3Client.send(new ListObjectsV2Command({
494
+ Bucket: this.config.cloudStorage.bucket,
495
+ Prefix: prefix,
496
+ ContinuationToken: token,
497
+ }));
498
+ if (response.Contents) {
499
+ for (const obj of response.Contents) {
500
+ if (obj.Key && obj.LastModified && obj.LastModified < cutoffDate)
501
+ oldObjects.push(obj);
502
+ }
503
+ }
504
+ token = response.IsTruncated ? response.NextContinuationToken : undefined;
505
+ } while (token);
506
+ if (oldObjects.length > 0) {
398
507
  const deletePromises = oldObjects.map((obj) => {
399
508
  if (obj.Key) {
400
509
  return this.s3Client.send(new DeleteObjectCommand({
@@ -406,12 +515,12 @@ export class BackupManager {
406
515
  }).filter(Boolean);
407
516
  await Promise.all(deletePromises);
408
517
  if (oldObjects.length > 0) {
409
- console.log(`🗑️ Cleaned up ${oldObjects.length} old backup(s) from cloud storage`);
518
+ this.log.info(`🗑️ Cleaned up ${oldObjects.length} old backup(s) from cloud storage`);
410
519
  }
411
520
  }
412
521
  }
413
522
  catch (error) {
414
- console.warn(`⚠️ Failed to cleanup old backups: ${error instanceof Error ? error.message : 'Unknown error'}`);
523
+ this.log.warn(`⚠️ Failed to cleanup old backups: ${error instanceof Error ? error.message : 'Unknown error'}`);
415
524
  }
416
525
  }
417
526
  scheduleBackup(config) {
@@ -424,7 +533,7 @@ export class BackupManager {
424
533
  this.config.retention = config.retention;
425
534
  }
426
535
  const performScheduledBackup = async () => {
427
- console.log(`⏰ Scheduled backup triggered (${config.interval} interval)`);
536
+ this.log.info(`⏰ Scheduled backup triggered (${config.interval} interval)`);
428
537
  await this.performBackup();
429
538
  };
430
539
  // Create cron job for recurring backups
@@ -433,11 +542,11 @@ export class BackupManager {
433
542
  'UTC' // timezone
434
543
  );
435
544
  this.scheduledBackups.set(scheduleId, cronJob);
436
- console.log(`📅 Backup scheduled with cron: ${cronExpression} (${config.interval} interval), ${config.retention || this.config.retention} retention`);
545
+ this.log.info(`📅 Backup scheduled with cron: ${cronExpression} (${config.interval} interval), ${config.retention || this.config.retention} retention`);
437
546
  return scheduleId;
438
547
  }
439
548
  catch (error) {
440
- throw new Error(`Failed to schedule backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
549
+ throw new Error(`Failed to schedule backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
441
550
  }
442
551
  }
443
552
  cancelScheduledBackup(scheduleId) {
@@ -445,7 +554,7 @@ export class BackupManager {
445
554
  if (cronJob) {
446
555
  cronJob.stop();
447
556
  this.scheduledBackups.delete(scheduleId);
448
- console.log(`❌ Cancelled scheduled backup: ${scheduleId}`);
557
+ this.log.info(`❌ Cancelled scheduled backup: ${scheduleId}`);
449
558
  return true;
450
559
  }
451
560
  return false;
@@ -500,9 +609,12 @@ export class BackupManager {
500
609
  };
501
610
  }
502
611
  try {
503
- // 1) Snapshot all data JSON files to bucket.
612
+ // 1) Snapshot all data JSON files to bucket. POOLED — the old sequential
613
+ // await-per-file loop made a 50k-doc backup take ~12 minutes at ~15ms
614
+ // per PUT; 16 in flight brings it under a minute. Per-item errors are
615
+ // collected (not fatal), matching the previous best-effort semantics.
504
616
  const jsonFiles = await this.getJsonFiles();
505
- for (const file of jsonFiles) {
617
+ await pooledMap(jsonFiles, 16, async (file) => {
506
618
  try {
507
619
  const cloudKey = this.getCloudKey(file.name);
508
620
  await this.uploadToCloud(file.path, cloudKey);
@@ -511,24 +623,24 @@ export class BackupManager {
511
623
  catch (error) {
512
624
  errors.push(`data:${file.name}:${error instanceof Error ? error.message : 'Unknown error'}`);
513
625
  }
514
- }
626
+ });
515
627
  // 2) Stream WAL archive segments the caller wants persisted.
516
628
  const walPaths = options?.walArchivePaths ?? [];
517
- for (const archivePath of walPaths) {
629
+ await pooledMap(walPaths, 16, async (archivePath) => {
518
630
  if (!existsSync(archivePath))
519
- continue;
631
+ return;
520
632
  try {
521
633
  const segName = basename(archivePath);
522
- const prefix = this.config.cloudStorage.pathPrefix || 'tero-backups';
523
- const dbName = basename(this.dbPath);
524
- const cloudKey = `${prefix}/${dbName}/wal/${segName}`;
525
- await this.uploadToCloud(archivePath, cloudKey);
634
+ const cloudKey = `${this.getDbName()}/wal/${segName}`;
635
+ // getCloudKey already prefixes, but for WAL we need wal/ subprefix
636
+ const walKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${cloudKey}`;
637
+ await this.uploadToCloud(archivePath, walKey);
526
638
  uploadedWALSegments++;
527
639
  }
528
640
  catch (error) {
529
641
  errors.push(`wal:${basename(archivePath)}:${error instanceof Error ? error.message : 'Unknown error'}`);
530
642
  }
531
- }
643
+ });
532
644
  // 3) Emit a backup manifest so hydrate-on-startup can discover the latest snapshot.
533
645
  try {
534
646
  const manifest = {
@@ -536,9 +648,9 @@ export class BackupManager {
536
648
  tag: options?.tag ?? 'manual',
537
649
  dataFiles: jsonFiles.map(f => f.name),
538
650
  walSegments: walPaths.map(p => basename(p)),
539
- dbPath: basename(this.dbPath),
651
+ dbPath: this.getDbName(),
540
652
  };
541
- const manifestKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${basename(this.dbPath)}/MANIFEST.json`;
653
+ const manifestKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${this.getDbName()}/MANIFEST.json`;
542
654
  await this.uploadBuffer(JSON.stringify(manifest, null, 2), manifestKey, 'application/json');
543
655
  }
544
656
  catch (error) {
@@ -577,7 +689,7 @@ export class BackupManager {
577
689
  ContentType: contentType,
578
690
  Metadata: {
579
691
  'backup-timestamp': new Date().toISOString(),
580
- 'source-db': basename(this.dbPath),
692
+ 'source-db': this.getDbName(),
581
693
  },
582
694
  });
583
695
  await this.s3Client.send(cmd);
@@ -588,24 +700,43 @@ export class BackupManager {
588
700
  liveEngine;
589
701
  livePrefix;
590
702
  liveCheckpoints = 0;
703
+ /** In-flight checkpoint (shared promise: concurrent callers await the same run). */
704
+ liveCheckpointPromise;
705
+ lastCheckpointError;
706
+ async drainInFlight() {
707
+ if (this.liveShipper) {
708
+ this.liveShipper.stop();
709
+ this.liveShipper = undefined;
710
+ }
711
+ if (this.liveCheckpointPromise) {
712
+ try {
713
+ await this.liveCheckpointPromise;
714
+ }
715
+ catch { }
716
+ }
717
+ }
591
718
  destroy() {
592
719
  for (const [id, cronJob] of this.scheduledBackups)
593
720
  cronJob.stop();
594
721
  this.scheduledBackups.clear();
595
- if (this.liveShipper)
722
+ // Clear the reference too — the automatic initial-checkpoint retry loop
723
+ // checks it and must stop retrying after destroy.
724
+ if (this.liveShipper) {
596
725
  this.liveShipper.stop();
597
- console.log('🛑 BackupManager destroyed, all scheduled backups cancelled');
726
+ this.liveShipper = undefined;
727
+ }
728
+ this.log.info('🛑 BackupManager destroyed, all scheduled backups cancelled');
598
729
  }
599
730
  liveCloudPrefix(nodeId) {
600
731
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
601
- return `${base}/${basename(this.dbPath)}/nodes/${nodeId}/`;
732
+ return `${base}/${this.getDbName()}/nodes/${nodeId}/`;
602
733
  }
603
734
  async uploadBytes(key, body, contentType = 'application/octet-stream') {
604
735
  if (!this.s3Client || !this.config.cloudStorage)
605
736
  throw new Error('Cloud storage not configured');
606
737
  await this.s3Client.send(new PutObjectCommand({
607
738
  Bucket: this.config.cloudStorage.bucket, Key: key, Body: body, ContentType: contentType,
608
- Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': basename(this.dbPath) },
739
+ Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': this.getDbName() },
609
740
  }));
610
741
  }
611
742
  async downloadBytes(key) {
@@ -644,6 +775,33 @@ export class BackupManager {
644
775
  } while (token);
645
776
  return keys;
646
777
  }
778
+ async listPrefixWithMeta(prefix) {
779
+ if (!this.s3Client || !this.config.cloudStorage)
780
+ throw new Error('Cloud storage not configured');
781
+ const out = [];
782
+ let token;
783
+ do {
784
+ const resp = await this.s3Client.send(new ListObjectsV2Command({ Bucket: this.config.cloudStorage.bucket, Prefix: prefix, ContinuationToken: token }));
785
+ if (resp.Contents)
786
+ for (const o of resp.Contents)
787
+ if (o.Key)
788
+ out.push({ key: o.Key, lastModified: o.LastModified ?? new Date(0) });
789
+ token = resp.IsTruncated ? resp.NextContinuationToken : undefined;
790
+ } while (token);
791
+ return out;
792
+ }
793
+ async deleteObject(key) {
794
+ if (!this.s3Client || !this.config.cloudStorage)
795
+ throw new Error('Cloud storage not configured');
796
+ try {
797
+ await this.s3Client.send(new DeleteObjectCommand({ Bucket: this.config.cloudStorage.bucket, Key: key }));
798
+ }
799
+ catch (e) {
800
+ if (e?.name === 'NoSuchKey' || e?.Code === 'NoSuchKey' || e?.$metadata?.httpStatusCode === 404)
801
+ return;
802
+ throw e;
803
+ }
804
+ }
647
805
  enableLiveBackup(engine, opts) {
648
806
  if (opts.consistency !== 'per-second')
649
807
  throw new Error("Tero live backup only supports consistency: 'per-second' (RPO ≤ 1s). Other levels are not offered.");
@@ -652,6 +810,10 @@ export class BackupManager {
652
810
  if (!this.s3Client || !this.config.cloudStorage)
653
811
  throw new Error('Cloud storage not configured — call configureBackup() with cloudStorage first.');
654
812
  const intervalMs = Math.max(250, opts.intervalMs ?? 1000);
813
+ if (intervalMs > 1000)
814
+ throw new Error(`intervalMs=${intervalMs} violates the per-second consistency contract (RPO ≤ 1s). Use intervalMs ≤ 1000.`);
815
+ // Resolve nodeId: explicit > persisted file > fresh id. Sanitize hard — this
816
+ // becomes an S3 key path component; garbage must never produce nested paths.
655
817
  let nodeId = opts.nodeId;
656
818
  const idFile = join(this.dbPath, '.tero-node-id');
657
819
  if (!nodeId) {
@@ -659,27 +821,63 @@ export class BackupManager {
659
821
  nodeId = readFileSync(idFile, 'utf8').trim();
660
822
  }
661
823
  catch {
662
- nodeId = randomUUID().replace(/-/g, '').slice(0, 16);
824
+ nodeId = '';
663
825
  }
664
826
  }
827
+ if (nodeId)
828
+ nodeId = nodeId.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64);
829
+ if (!nodeId)
830
+ nodeId = randomUUID().replace(/-/g, '').slice(0, 16);
665
831
  try {
666
832
  writeFileSync(idFile, nodeId, 'utf8');
833
+ const fd = openSync(idFile, 'r');
834
+ try {
835
+ fsyncSync(fd);
836
+ }
837
+ finally {
838
+ closeSync(fd);
839
+ }
667
840
  }
668
841
  catch { }
669
842
  const prefix = this.liveCloudPrefix(nodeId);
670
843
  this.liveNodeId = nodeId;
671
844
  this.liveEngine = engine;
672
845
  this.livePrefix = prefix;
846
+ this.lastCheckpointError = undefined;
673
847
  this.liveShipper = new WalShipper({ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs });
674
848
  this.liveShipper.start();
675
- console.log(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
849
+ this.log.info(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
850
+ // CRITICAL: take the initial FULL checkpoint automatically. Without it, every
851
+ // document written BEFORE enableLiveBackup() is unrestorable until the first
852
+ // manual liveCheckpointToBucket() — a crash in that window loses all prior data.
853
+ // Retry with backoff (bucket may be temporarily unreachable); surface failures
854
+ // in getLiveBackupStatus().lastCheckpointError.
855
+ void this.runInitialCheckpoint(prefix);
856
+ }
857
+ /** Initial full checkpoint with bounded retry. Stops on success or disable. */
858
+ async runInitialCheckpoint(prefix) {
859
+ for (let attempt = 1;; attempt++) {
860
+ if (this.liveShipper === undefined || this.livePrefix !== prefix)
861
+ return; // disabled/re-enabled under us
862
+ try {
863
+ await this.liveCheckpointToBucket();
864
+ return;
865
+ }
866
+ catch (e) {
867
+ this.lastCheckpointError = `initial-checkpoint attempt ${attempt}: ${e instanceof Error ? e.message : String(e)}`;
868
+ if (attempt >= 60)
869
+ return; // give up after ~5 min; error stays visible in status
870
+ // unref'd so a failing bucket can never keep the process alive.
871
+ await new Promise(r => { const t = setTimeout(r, Math.min(5000 * attempt, 30000)); t.unref?.(); });
872
+ }
873
+ }
676
874
  }
677
875
  disableLiveBackup() {
678
876
  if (!this.liveShipper)
679
877
  return;
680
878
  this.liveShipper.stop();
681
879
  this.liveShipper = undefined;
682
- console.log('🛑 Tero live backup disabled');
880
+ this.log.info('🛑 Tero live backup disabled');
683
881
  }
684
882
  getLiveBackupStatus() {
685
883
  const s = this.liveShipper?.status;
@@ -689,60 +887,127 @@ export class BackupManager {
689
887
  secondsSinceLastShip: s?.lastShipAt ? Math.round((Date.now() - s.lastShipAt) / 1000) : 0,
690
888
  segmentsShipped: s?.segmentsShipped ?? 0, checkpointsTaken: this.liveCheckpoints,
691
889
  errorCount: s?.errorCount ?? 0, lastError: s?.lastError,
890
+ lastCheckpointError: this.lastCheckpointError,
692
891
  };
693
892
  }
694
893
  // __TERO_LIVE_PART2__
695
894
  async liveCheckpointToBucket(_opts) {
696
895
  if (!this.liveEngine || !this.liveNodeId || !this.livePrefix)
697
896
  throw new Error('Live backup not enabled — call enableLiveBackup() first.');
897
+ // Share the in-flight run: concurrent callers (e.g. the automatic initial
898
+ // checkpoint racing a manual call) must never interleave uploads — a second
899
+ // run could publish latest.json before the first run's data is durable.
900
+ if (this.liveCheckpointPromise)
901
+ return this.liveCheckpointPromise;
902
+ this.liveCheckpointPromise = this.doLiveCheckpoint();
903
+ try {
904
+ const r = await this.liveCheckpointPromise;
905
+ this.lastCheckpointError = undefined;
906
+ return r;
907
+ }
908
+ catch (e) {
909
+ this.lastCheckpointError = e instanceof Error ? e.message : String(e);
910
+ throw e;
911
+ }
912
+ finally {
913
+ this.liveCheckpointPromise = undefined;
914
+ }
915
+ }
916
+ async doLiveCheckpoint() {
917
+ const engine = this.liveEngine;
698
918
  const start = Date.now();
699
919
  const ckptPrefix = `${this.livePrefix}checkpoint/`;
700
920
  const latestKey = `${ckptPrefix}latest.json`;
921
+ // (1) CONSERVATIVE baseLsn — capture BEFORE flushing/uploading. commitTransaction
922
+ // is synchronous (LSN assignment + committedBuffer set are atomic in one event-
923
+ // loop turn), so every entry with lsn ≤ ckptLsn is in committedBuffer right now
924
+ // and lands in the data files after the flush below. Everything > ckptLsn is
925
+ // guaranteed to be WAL-replayed on restore. Capturing the LSN AFTER the uploads
926
+ // instead would let mid-checkpoint writes be skipped by BOTH the checkpoint
927
+ // content AND the replay filter — silent stale-data loss.
928
+ const ckptLsn = engine.getWAL().getCurrentLSN();
929
+ // (2) Flush committed data so the files we read reflect all commits ≤ ckptLsn.
930
+ engine.flushCommittedBuffer();
931
+ const posixRel = (p) => relative(this.dbPath, p).split(sep).join('/');
701
932
  const latest = await this.readJsonOrDefault(latestKey);
702
- const wal = this.liveEngine.getWAL();
703
- const dirty = this.liveEngine.takeDirtyKeys();
704
933
  if (!latest) {
934
+ // FULL checkpoint (first call after enable — captures ALL documents, including
935
+ // everything written before enableLiveBackup()).
705
936
  const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
706
937
  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++;
938
+ const filePaths = [];
939
+ await walkPartitions(this.dbPath, async (filePath) => { filePaths.push(filePath); });
940
+ // Pool uploads: sequential PUTs at ~15ms/object would make a 50k-doc initial
941
+ // checkpoint take ~12 minutes; 16 in flight brings it under a minute.
942
+ await pooledMap(filePaths, 16, async (filePath) => {
943
+ await this.uploadBytes(`${dataPrefix}${posixRel(filePath)}`, readFileSync(filePath), 'application/json');
711
944
  });
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');
945
+ const count = filePaths.length;
946
+ // Drain the dirty set: the full upload supersedes any pending incremental
947
+ // changes — otherwise the next incremental checkpoint would re-upload them.
948
+ engine.takeDirtyKeys();
949
+ await this.uploadBytes(`${ckptPrefix}${baseTs}/index.json`, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, createdAt: new Date().toISOString(), docCount: count }, null, 2)), 'application/json');
950
+ // latest.json is published LAST — it is the visibility marker for restore.
951
+ // Publishing it before the data objects are durable would let a concurrent
952
+ // restore read a checkpoint whose data is missing.
953
+ await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
714
954
  this.liveCheckpoints++;
715
- return { uploadedDocs: count, fullUpload: true, duration: Date.now() - start };
955
+ return { uploadedDocs: count, tombstonedDocs: 0, fullUpload: true, duration: Date.now() - start };
716
956
  }
957
+ // INCREMENTAL checkpoint — upload ONLY dirty docs, tombstone deleted ones.
958
+ // Tombstones are required: the full checkpoint data still contains the deleted
959
+ // document, and its WAL DELETE entry (lsn ≤ baseLsn) is deliberately skipped by
960
+ // the restore replay filter — without a marker, deleted docs would resurrect.
717
961
  const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
718
- let uploaded = 0;
719
- for (const key of dirty) {
962
+ const dirty = engine.takeDirtyKeys();
963
+ let uploaded = 0, tombstoned = 0;
964
+ const dirtyList = Array.from(dirty);
965
+ await pooledMap(dirtyList, 16, async (key) => {
720
966
  const filePath = partitionedPath(this.dbPath, key);
967
+ const rel = posixRel(filePath);
721
968
  if (existsSync(filePath)) {
722
- await this.uploadBytes(`${dataPrefix}${relative(this.dbPath, filePath)}`, readFileSync(filePath), 'application/json');
969
+ await this.uploadBytes(`${dataPrefix}${rel}`, readFileSync(filePath), 'application/json');
723
970
  uploaded++;
971
+ // Delete stale tombstone if this key was previously deleted then recreated
972
+ // under the same baseTs. Without this, bucket holds both data and
973
+ // .deleted and the old restore filter would drop the recreated doc.
974
+ try {
975
+ await this.deleteObject(`${dataPrefix}${rel}.deleted`);
976
+ }
977
+ catch { }
724
978
  }
725
- }
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');
979
+ else {
980
+ await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream');
981
+ tombstoned++;
982
+ }
983
+ });
984
+ 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
985
  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
986
  this.liveCheckpoints++;
729
- return { uploadedDocs: uploaded, fullUpload: false, duration: Date.now() - start };
987
+ return { uploadedDocs: uploaded, tombstonedDocs: tombstoned, fullUpload: false, duration: Date.now() - start };
730
988
  }
731
989
  // __TERO_LIVE_PART3__
732
990
  async restoreLiveToDirectory(targetDir, opts = {}) {
733
991
  if (!this.s3Client || !this.config.cloudStorage)
734
992
  throw new Error('Cloud storage not configured');
993
+ if (existsSync(targetDir) && readdirSync(targetDir).some(f => !f.startsWith('.'))) {
994
+ this.log.warn(`⚠️ restoreLiveToDirectory: target '${targetDir}' is not empty — restored state will be merged over existing files.`);
995
+ }
735
996
  mkdirSync(targetDir, { recursive: true });
736
997
  const pit = opts.pointInTime ?? Infinity;
737
998
  let nodeId = opts.nodeId;
738
999
  if (!nodeId) {
1000
+ // Exact prefix slicing — NOT a regex on '/nodes/'. A regex would also match a
1001
+ // user pathPrefix or database name containing "nodes" and restore from the
1002
+ // wrong node (e.g. pathPrefix 'my/nodes/stuff' would capture 'stuff').
739
1003
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
740
- const all = await this.listPrefix(`${base}/${basename(this.dbPath)}/nodes/`);
1004
+ const nodesPrefix = `${base}/${this.getDbName()}/nodes/`;
1005
+ const all = await this.listPrefix(nodesPrefix);
741
1006
  const ids = new Set();
742
1007
  for (const k of all) {
743
- const m = k.match(/\/nodes\/([^/]+)\//);
744
- if (m)
745
- ids.add(m[1]);
1008
+ const id = k.slice(nodesPrefix.length).split('/')[0];
1009
+ if (id)
1010
+ ids.add(id);
746
1011
  }
747
1012
  if (ids.size === 0)
748
1013
  throw new Error('No live-backup nodes found in bucket.');
@@ -756,22 +1021,85 @@ export class BackupManager {
756
1021
  let baseLsn = null;
757
1022
  if (latest) {
758
1023
  baseLsn = latest.baseLsn ?? null;
759
- const dataKeys = await this.listPrefix(`${prefix}checkpoint/${latest.baseTs}/data/`);
760
- for (const dk of dataKeys) {
761
- if (dk.endsWith('.deleted'))
762
- continue;
763
- const body = await this.downloadBytes(dk);
1024
+ const dataWithMeta = await this.listPrefixWithMeta(`${prefix}checkpoint/${latest.baseTs}/data/`);
1025
+ const tombstoneMeta = new Map();
1026
+ const activeMeta = new Map();
1027
+ for (const { key, lastModified } of dataWithMeta) {
1028
+ if (key.endsWith('.deleted')) {
1029
+ const keyName = basename(key).replace(/\.json\.deleted$/, '');
1030
+ const prev = tombstoneMeta.get(keyName);
1031
+ if (!prev || lastModified > prev)
1032
+ tombstoneMeta.set(keyName, lastModified);
1033
+ }
1034
+ else if (key.endsWith('.json')) {
1035
+ const keyName = basename(key).replace(/\.json$/, '');
1036
+ const prev = activeMeta.get(keyName);
1037
+ if (!prev || lastModified > prev.lastModified)
1038
+ activeMeta.set(keyName, { key, lastModified });
1039
+ }
1040
+ }
1041
+ // Resolve tombstone vs data by recency: newer wins. This handles
1042
+ // delete→recreate under same baseTs (data newer) vs legit delete
1043
+ // (tombstone newer than the full-checkpoint data), and also heals
1044
+ // legacy buckets that contain both due to the pre-fix bug.
1045
+ const keysToDownload = [];
1046
+ const finalTombstones = new Set();
1047
+ for (const [keyName, active] of activeMeta) {
1048
+ const tombTime = tombstoneMeta.get(keyName);
1049
+ if (tombTime) {
1050
+ if (active.lastModified > tombTime) {
1051
+ keysToDownload.push(active.key);
1052
+ }
1053
+ else {
1054
+ finalTombstones.add(keyName);
1055
+ }
1056
+ }
1057
+ else {
1058
+ keysToDownload.push(active.key);
1059
+ }
1060
+ }
1061
+ for (const [keyName] of tombstoneMeta) {
1062
+ if (!activeMeta.has(keyName))
1063
+ finalTombstones.add(keyName);
1064
+ }
1065
+ // Keep compat names for later local-delete loop
1066
+ const tombstoneKeyNames = finalTombstones;
1067
+ // Pool downloads — sequential GETs make a 50k-doc restore take ~12 minutes.
1068
+ await pooledMap(keysToDownload, 16, async (dk) => {
764
1069
  const key = basename(dk).replace(/\.json$/, '');
765
1070
  const dest = partitionedPath(targetDir, key);
1071
+ const body = await this.downloadBytes(dk);
766
1072
  mkdirSync(dirname(dest), { recursive: true });
767
- const tmp = `${dest}.tmp.${process.pid}`;
1073
+ const tmp = `${dest}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
768
1074
  writeFileSync(tmp, body);
769
1075
  renameSync(tmp, dest);
770
1076
  docsRestored++;
1077
+ });
1078
+ // Ensure any existing local file matching a tombstone is deleted
1079
+ for (const keyName of tombstoneKeyNames) {
1080
+ const dest = partitionedPath(targetDir, keyName);
1081
+ try {
1082
+ if (existsSync(dest))
1083
+ unlinkSync(dest);
1084
+ }
1085
+ catch { }
771
1086
  }
772
1087
  }
773
1088
  const walKeys = (await this.listPrefix(`${prefix}wal/`))
774
1089
  .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) > (baseLsn ?? 0) : false; }).sort();
1090
+ // Detect LSN gaps between consecutive segments. Local WAL archives are pruned
1091
+ // (keep-last-3) even while the bucket is unreachable, so an outage spanning
1092
+ // >3MB of writes loses segments permanently. Small gaps are normal (filtered
1093
+ // BEGIN/COMMIT/CHECKPOINT entries); gaps >50 LSNs mean real writes may be missing.
1094
+ let prevEnd = -1;
1095
+ for (const wk of walKeys) {
1096
+ const m = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1097
+ const s = parseInt(m[1]), e = parseInt(m[2]);
1098
+ if (prevEnd >= 0 && s - prevEnd - 1 > 50) {
1099
+ 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.`);
1100
+ }
1101
+ prevEnd = Math.max(prevEnd, e);
1102
+ }
775
1103
  let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
776
1104
  const pending = new Map();
777
1105
  const apply = (e) => {
@@ -781,7 +1109,10 @@ export class BackupManager {
781
1109
  if (e.operation === 'WRITE') {
782
1110
  mkdirSync(dirname(dest), { recursive: true });
783
1111
  const tmp = `${dest}.tmp.${process.pid}`;
784
- writeFileSync(tmp, JSON.stringify(e.afterImage ?? null));
1112
+ // Match the engine's data-file format exactly (atomicWriteFile uses
1113
+ // JSON.stringify(data, null, 2)) so restored files are byte-identical
1114
+ // to engine-written ones.
1115
+ writeFileSync(tmp, JSON.stringify(e.afterImage ?? null, null, 2));
785
1116
  renameSync(tmp, dest);
786
1117
  }
787
1118
  else if (e.operation === 'DELETE') {
@@ -821,7 +1152,7 @@ export class BackupManager {
821
1152
  segmentsReplayed++;
822
1153
  }
823
1154
  catch (e) {
824
- console.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
1155
+ this.log.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
825
1156
  }
826
1157
  }
827
1158
  return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn };
@@ -841,6 +1172,9 @@ class WalShipper {
841
1172
  lastLsn = 0;
842
1173
  initialized = false;
843
1174
  shippedArchives = new Set();
1175
+ /** Tick counter + per-archive retry schedule (throttles re-reads during outages). */
1176
+ tickCount = 0;
1177
+ archiveRetryAt = new Map();
844
1178
  status;
845
1179
  intervalMs;
846
1180
  constructor(deps) {
@@ -870,9 +1204,14 @@ class WalShipper {
870
1204
  if (this.shipping)
871
1205
  return;
872
1206
  this.shipping = true;
1207
+ this.tickCount++;
873
1208
  try {
874
1209
  await this.shipArchives();
875
- const entries = this.deps.wal.getLogEntries(this.lastLsn).filter(e => e.operation === 'WRITE' || e.operation === 'DELETE');
1210
+ // getLogEntries(fromLSN) filters lsn >= fromLSN (INCLUSIVE) — pass lastLsn + 1
1211
+ // or every tick would re-ship the final entry of the previous segment.
1212
+ // COMMIT/ROLLBACK markers must ship too (see WAL_SHIPPED_OPS) or restore
1213
+ // can never commit its buffered transactions.
1214
+ const entries = this.deps.wal.getLogEntries(this.lastLsn + 1).filter(e => WAL_SHIPPED_OPS.has(e.operation));
876
1215
  if (entries.length === 0) {
877
1216
  this.status.state = 'healthy';
878
1217
  return;
@@ -902,6 +1241,12 @@ class WalShipper {
902
1241
  for (const p of archives) {
903
1242
  if (this.shippedArchives.has(p))
904
1243
  continue;
1244
+ // Throttle failing archives: without this, a bucket outage means every tick
1245
+ // re-reads and re-parses up to 3MB of archive JSON per second (wasted CPU
1246
+ // on a busy server). Retry each failing archive only every 5 ticks.
1247
+ const retryAt = this.archiveRetryAt.get(p);
1248
+ if (retryAt !== undefined && this.tickCount < retryAt)
1249
+ continue;
905
1250
  try {
906
1251
  const lines = readFileSync(p, 'utf8').trim().split('\n');
907
1252
  const entries = [];
@@ -911,7 +1256,7 @@ class WalShipper {
911
1256
  }
912
1257
  catch { }
913
1258
  }
914
- const fresh = entries.filter(e => (e.operation === 'WRITE' || e.operation === 'DELETE') && e.lsn > this.lastLsn);
1259
+ const fresh = entries.filter(e => WAL_SHIPPED_OPS.has(e.operation) && e.lsn > this.lastLsn);
915
1260
  if (fresh.length > 0) {
916
1261
  const s = fresh[0].lsn, en = fresh[fresh.length - 1].lsn;
917
1262
  const body = gzipSync(Buffer.from(JSON.stringify(fresh)), { level: 1 });
@@ -923,8 +1268,10 @@ class WalShipper {
923
1268
  this.status.totalBytesShipped += body.length;
924
1269
  }
925
1270
  this.shippedArchives.add(p);
1271
+ this.archiveRetryAt.delete(p);
926
1272
  }
927
1273
  catch (e) {
1274
+ this.archiveRetryAt.set(p, this.tickCount + 5);
928
1275
  this.status.state = 'degraded';
929
1276
  this.status.errorCount++;
930
1277
  this.status.lastError = `archive:${e instanceof Error ? e.message : e}`;