tero 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -131,6 +131,8 @@ db.cancelScheduledBackup(scheduleId);
131
131
 
132
132
  Tero interacts directly with object storage from each instance, keeping credentials local and isolated.
133
133
 
134
+ 📊 **Cost comparison:** see [BUCKET_COST_DATA.md](./BUCKET_COST_DATA.md) for AWS S3 vs Cloudflare R2 pricing (verified 2026-08-28), how backup operations map to billed requests, and monthly cost scenarios.
135
+
134
136
  ## Cloud recovery
135
137
 
136
138
  ```javascript
@@ -267,6 +269,48 @@ npm run test:legacy # legacy suite
267
269
  node local_tests/v2-test.js # v2: hydrate + bucket backup surface
268
270
  ```
269
271
 
272
+ ### Testing S3 live backup locally (MinIO)
273
+
274
+ `npm run test:s3` round-trips the live backup API against a real S3-compatible
275
+ endpoint: live writes → `backupToBucket()` → `checkpointAndBackupToBucket()` →
276
+ raw bucket verification → hydrate-on-startup into a fresh node. Without
277
+ credentials it skips, so plain `npm test` stays green.
278
+
279
+ The cheapest way to exercise it is MinIO in Docker:
280
+
281
+ ```bash
282
+ # 1. Start a local S3-compatible server
283
+ docker run -d --name tero-minio-test -p 9000:9000 -p 9001:9001 \
284
+ -v /tmp/tero-minio-data:/data \
285
+ minio/minio server /data --console-address ":9001"
286
+
287
+ # 2. Run the round-trip test (bucket is created if missing)
288
+ S3_ENDPOINT=http://127.0.0.1:9000 \
289
+ S3_BUCKET=tero-live-backup-test \
290
+ AWS_ACCESS_KEY_ID=minioadmin \
291
+ AWS_SECRET_ACCESS_KEY=minioadmin \
292
+ npm run test:s3
293
+
294
+ # 3. Inspect what Tero wrote (console at http://localhost:9001)
295
+ # s3://tero-live-backup-test/tero-backups/<dbName>/
296
+ # ├── <key>.json # data snapshots
297
+ # ├── wal/.wal.<ts> # archived WAL segments
298
+ # └── MANIFEST.json # hydration entry point
299
+
300
+ # 4. Clean up
301
+ docker rm -f tero-minio-test && rm -rf /tmp/tero-minio-data
302
+ ```
303
+
304
+ Against real AWS, omit `S3_ENDPOINT` and pass an IAM user with
305
+ `s3:PutObject/GetObject/ListBucket/CreateBucket` on the test bucket:
306
+
307
+ ```bash
308
+ S3_BUCKET=my-test-bucket \
309
+ AWS_ACCESS_KEY_ID=... \
310
+ AWS_SECRET_ACCESS_KEY=... \
311
+ npm run test:s3
312
+ ```
313
+
270
314
  ## Performance characteristics
271
315
 
272
316
  ```
@@ -126,6 +126,22 @@ export declare class LockManager {
126
126
  releaseAllLocks(transactionId: string): void;
127
127
  detectDeadlock(): string[];
128
128
  }
129
+ /**
130
+ * Map a document key to a 2-level hash-prefix partitioned path:
131
+ * ${dbPath}/${hash[0]}/${hash[2]}/${key}.json
132
+ *
133
+ * This spreads files across 256×256 = 65,536 leaf directories, eliminating
134
+ * the POSIX dentry-lock and readdir() array-allocation problems that flat
135
+ * directories hit at >50k entries (ext4/XFS single-dir lookup degrades
136
+ * super-linearly with file count).
137
+ *
138
+ * The partition is deterministic from the key, so reads/writes for a given
139
+ * key always resolve to the same partition without an in-memory index.
140
+ *
141
+ * Exported so DataRecovery can write cloud-restored files into the exact
142
+ * partition the engine reads from (deterministic from the key).
143
+ */
144
+ export declare function partitionedPath(dbPath: string, key: string): string;
129
145
  /**
130
146
  * Walk partitioned directories under dbPath and call `visitor(filePath)` for
131
147
  * every *.json file found. Uses fs.opendir async iteration so each directory
@@ -173,6 +189,23 @@ export declare class ACIDStorageEngine {
173
189
  private committedBuffer;
174
190
  private dataFlushTimer?;
175
191
  private readonly DATA_FLUSH_INTERVAL_MS;
192
+ /**
193
+ * Dirty-key tracker for incremental cloud checkpoints (roadmap4.md).
194
+ * Every committed write/delete marks its key here at commit time — O(1) per
195
+ * committed op, no I/O, no locks on the hot path. The backup layer drains
196
+ * the set via takeDirtyKeys() to upload ONLY changed documents; the set is
197
+ * cleared atomically on take. Unbounded growth is bounded by checkpoint
198
+ * cadence (drained on every live checkpoint), and even with no checkpoints
199
+ * each entry is just the key string (~50-100 bytes).
200
+ */
201
+ private dirtyKeys;
202
+ /**
203
+ * Atomically drain the dirty-key set: returns the keys changed since the
204
+ * last take and clears the set in one swap. Used by incremental checkpoints.
205
+ */
206
+ takeDirtyKeys(): Set<string>;
207
+ /** Current dirty-key count (diagnostics/status). */
208
+ getDirtyKeyCount(): number;
176
209
  constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number);
177
210
  private initializeStorage;
178
211
  private performCrashRecovery;
@@ -575,10 +575,10 @@ export class LockManager {
575
575
  * The partition is deterministic from the key, so reads/writes for a given
576
576
  * key always resolve to the same partition without an in-memory index.
577
577
  *
578
- * Crash recovery (redoOperation/undoOperation) naturally walks the whole
579
- * tree via fs.opendir recursion — no readdirSync allocation.
578
+ * Exported so DataRecovery can write cloud-restored files into the exact
579
+ * partition the engine reads from (deterministic from the key).
580
580
  */
581
- function partitionedPath(dbPath, key) {
581
+ export function partitionedPath(dbPath, key) {
582
582
  // Fast 32-bit FNV-1a of the key to pick the partition dirs. We only need
583
583
  // ~16 bits of dispersion for partitioning (65k buckets), so 32-bit hash
584
584
  // is more than sufficient (collision here just means two keys share a
@@ -678,6 +678,29 @@ export class ACIDStorageEngine {
678
678
  committedBuffer = new Map();
679
679
  dataFlushTimer;
680
680
  DATA_FLUSH_INTERVAL_MS;
681
+ /**
682
+ * Dirty-key tracker for incremental cloud checkpoints (roadmap4.md).
683
+ * Every committed write/delete marks its key here at commit time — O(1) per
684
+ * committed op, no I/O, no locks on the hot path. The backup layer drains
685
+ * the set via takeDirtyKeys() to upload ONLY changed documents; the set is
686
+ * cleared atomically on take. Unbounded growth is bounded by checkpoint
687
+ * cadence (drained on every live checkpoint), and even with no checkpoints
688
+ * each entry is just the key string (~50-100 bytes).
689
+ */
690
+ dirtyKeys = new Set();
691
+ /**
692
+ * Atomically drain the dirty-key set: returns the keys changed since the
693
+ * last take and clears the set in one swap. Used by incremental checkpoints.
694
+ */
695
+ takeDirtyKeys() {
696
+ const taken = this.dirtyKeys;
697
+ this.dirtyKeys = new Set();
698
+ return taken;
699
+ }
700
+ /** Current dirty-key count (diagnostics/status). */
701
+ getDirtyKeyCount() {
702
+ return this.dirtyKeys.size;
703
+ }
681
704
  constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50) {
682
705
  this.dbPath = dbPath;
683
706
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
@@ -1048,6 +1071,8 @@ export class ACIDStorageEngine {
1048
1071
  else if (op.op === 'delete') {
1049
1072
  this.committedBuffer.set(key, { data: null, op: 'delete' });
1050
1073
  }
1074
+ // Mark dirty for incremental cloud checkpoints (O(1), no I/O)
1075
+ this.dirtyKeys.add(key);
1051
1076
  }
1052
1077
  }
1053
1078
  // Update transaction status
package/dist/backup.d.ts CHANGED
@@ -1,3 +1,31 @@
1
+ import { ACIDStorageEngine } from "./acid-engine.js";
2
+ export interface LiveBackupStatus {
3
+ state: 'healthy' | 'degraded' | 'stopped';
4
+ nodeId: string;
5
+ intervalMs: number;
6
+ lastShippedLsn: number;
7
+ lastShipAt: number;
8
+ secondsSinceLastShip: number;
9
+ segmentsShipped: number;
10
+ checkpointsTaken: number;
11
+ errorCount: number;
12
+ lastError?: string;
13
+ }
14
+ export interface LiveBackupOptions {
15
+ /** The only consistency level live backup offers: RPO ≤ 1 second of committed writes. */
16
+ consistency: 'per-second';
17
+ /** Ship interval in ms. Default 1000. Minimum 250. */
18
+ intervalMs?: number;
19
+ /** Stable identity for this node in the bucket. Persisted to <dbPath>/.tero-node-id. */
20
+ nodeId?: string;
21
+ }
22
+ export interface RestoreLiveResult {
23
+ nodeId: string;
24
+ docsRestored: number;
25
+ segmentsReplayed: number;
26
+ baseLsn: number | null;
27
+ lastLsn: number;
28
+ }
1
29
  export interface CloudStorageConfig {
2
30
  provider: 'aws-s3' | 'cloudflare-r2';
3
31
  region: string;
@@ -93,5 +121,29 @@ export declare class BackupManager {
93
121
  * Upload an arbitrary buffer (used for the bucket manifest and small artifacts).
94
122
  */
95
123
  private uploadBuffer;
124
+ private liveShipper?;
125
+ private liveNodeId?;
126
+ private liveEngine?;
127
+ private livePrefix?;
128
+ private liveCheckpoints;
96
129
  destroy(): void;
130
+ private liveCloudPrefix;
131
+ private uploadBytes;
132
+ private downloadBytes;
133
+ private readJsonOrDefault;
134
+ private listPrefix;
135
+ enableLiveBackup(engine: ACIDStorageEngine, opts: LiveBackupOptions): void;
136
+ disableLiveBackup(): void;
137
+ getLiveBackupStatus(): LiveBackupStatus;
138
+ liveCheckpointToBucket(_opts?: {
139
+ tag?: string;
140
+ }): Promise<{
141
+ uploadedDocs: number;
142
+ fullUpload: boolean;
143
+ duration: number;
144
+ }>;
145
+ restoreLiveToDirectory(targetDir: string, opts?: {
146
+ nodeId?: string;
147
+ pointInTime?: number;
148
+ }): Promise<RestoreLiveResult>;
97
149
  }
package/dist/backup.js CHANGED
@@ -1,9 +1,16 @@
1
- import { createReadStream, existsSync, statSync } from "fs";
2
- import { join, basename } from "path";
1
+ import { createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, renameSync, unlinkSync } from "fs";
2
+ import { join, basename, relative, dirname } from "path";
3
3
  import tar from "tar";
4
- import { S3Client, PutObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
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
+ import { gzipSync, gunzipSync } from "zlib";
8
+ import { randomUUID } from "crypto";
9
+ import { partitionedPath, walkPartitions } from "./acid-engine.js";
10
+ /** LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort. */
11
+ function padLsn(lsn) {
12
+ return lsn.toString().padStart(16, '0');
13
+ }
7
14
  export class BackupManager {
8
15
  s3Client;
9
16
  scheduledBackups = new Map();
@@ -575,12 +582,353 @@ export class BackupManager {
575
582
  });
576
583
  await this.s3Client.send(cmd);
577
584
  }
585
+ // ===== Live backup (per-second WAL shipping) — fields =====
586
+ liveShipper;
587
+ liveNodeId;
588
+ liveEngine;
589
+ livePrefix;
590
+ liveCheckpoints = 0;
578
591
  destroy() {
579
- // Cancel all scheduled backups
580
- for (const [id, cronJob] of this.scheduledBackups) {
592
+ for (const [id, cronJob] of this.scheduledBackups)
581
593
  cronJob.stop();
582
- }
583
594
  this.scheduledBackups.clear();
595
+ if (this.liveShipper)
596
+ this.liveShipper.stop();
584
597
  console.log('🛑 BackupManager destroyed, all scheduled backups cancelled');
585
598
  }
599
+ liveCloudPrefix(nodeId) {
600
+ const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
601
+ return `${base}/${basename(this.dbPath)}/nodes/${nodeId}/`;
602
+ }
603
+ async uploadBytes(key, body, contentType = 'application/octet-stream') {
604
+ if (!this.s3Client || !this.config.cloudStorage)
605
+ throw new Error('Cloud storage not configured');
606
+ await this.s3Client.send(new PutObjectCommand({
607
+ Bucket: this.config.cloudStorage.bucket, Key: key, Body: body, ContentType: contentType,
608
+ Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': basename(this.dbPath) },
609
+ }));
610
+ }
611
+ async downloadBytes(key) {
612
+ if (!this.s3Client || !this.config.cloudStorage)
613
+ throw new Error('Cloud storage not configured');
614
+ const resp = await this.s3Client.send(new GetObjectCommand({ Bucket: this.config.cloudStorage.bucket, Key: key }));
615
+ if (!resp.Body)
616
+ throw new Error(`Empty body for ${key}`);
617
+ const chunks = [];
618
+ for await (const c of resp.Body)
619
+ chunks.push(typeof c === 'string' ? Buffer.from(c) : c);
620
+ return Buffer.concat(chunks);
621
+ }
622
+ async readJsonOrDefault(key) {
623
+ try {
624
+ return JSON.parse((await this.downloadBytes(key)).toString('utf8'));
625
+ }
626
+ catch (e) {
627
+ if (e instanceof Error && (e.name === 'NoSuchKey' || /NoSuchKey|404|not found|does not exist/i.test(e.message)))
628
+ return null;
629
+ throw e;
630
+ }
631
+ }
632
+ async listPrefix(prefix) {
633
+ if (!this.s3Client || !this.config.cloudStorage)
634
+ throw new Error('Cloud storage not configured');
635
+ const keys = [];
636
+ let token;
637
+ do {
638
+ const resp = await this.s3Client.send(new ListObjectsV2Command({ Bucket: this.config.cloudStorage.bucket, Prefix: prefix, ContinuationToken: token }));
639
+ if (resp.Contents)
640
+ for (const o of resp.Contents)
641
+ if (o.Key)
642
+ keys.push(o.Key);
643
+ token = resp.IsTruncated ? resp.NextContinuationToken : undefined;
644
+ } while (token);
645
+ return keys;
646
+ }
647
+ enableLiveBackup(engine, opts) {
648
+ if (opts.consistency !== 'per-second')
649
+ throw new Error("Tero live backup only supports consistency: 'per-second' (RPO ≤ 1s). Other levels are not offered.");
650
+ if (this.liveShipper)
651
+ return;
652
+ if (!this.s3Client || !this.config.cloudStorage)
653
+ throw new Error('Cloud storage not configured — call configureBackup() with cloudStorage first.');
654
+ const intervalMs = Math.max(250, opts.intervalMs ?? 1000);
655
+ let nodeId = opts.nodeId;
656
+ const idFile = join(this.dbPath, '.tero-node-id');
657
+ if (!nodeId) {
658
+ try {
659
+ nodeId = readFileSync(idFile, 'utf8').trim();
660
+ }
661
+ catch {
662
+ nodeId = randomUUID().replace(/-/g, '').slice(0, 16);
663
+ }
664
+ }
665
+ try {
666
+ writeFileSync(idFile, nodeId, 'utf8');
667
+ }
668
+ catch { }
669
+ const prefix = this.liveCloudPrefix(nodeId);
670
+ this.liveNodeId = nodeId;
671
+ this.liveEngine = engine;
672
+ this.livePrefix = prefix;
673
+ this.liveShipper = new WalShipper({ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs });
674
+ this.liveShipper.start();
675
+ console.log(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
676
+ }
677
+ disableLiveBackup() {
678
+ if (!this.liveShipper)
679
+ return;
680
+ this.liveShipper.stop();
681
+ this.liveShipper = undefined;
682
+ console.log('🛑 Tero live backup disabled');
683
+ }
684
+ getLiveBackupStatus() {
685
+ const s = this.liveShipper?.status;
686
+ return {
687
+ state: s?.state ?? 'stopped', nodeId: this.liveNodeId ?? 'unknown', intervalMs: this.liveShipper?.intervalMs ?? 0,
688
+ lastShippedLsn: s?.lastShippedLsn ?? 0, lastShipAt: s?.lastShipAt ?? 0,
689
+ secondsSinceLastShip: s?.lastShipAt ? Math.round((Date.now() - s.lastShipAt) / 1000) : 0,
690
+ segmentsShipped: s?.segmentsShipped ?? 0, checkpointsTaken: this.liveCheckpoints,
691
+ errorCount: s?.errorCount ?? 0, lastError: s?.lastError,
692
+ };
693
+ }
694
+ // __TERO_LIVE_PART2__
695
+ async liveCheckpointToBucket(_opts) {
696
+ if (!this.liveEngine || !this.liveNodeId || !this.livePrefix)
697
+ throw new Error('Live backup not enabled — call enableLiveBackup() first.');
698
+ const start = Date.now();
699
+ const ckptPrefix = `${this.livePrefix}checkpoint/`;
700
+ const latestKey = `${ckptPrefix}latest.json`;
701
+ const latest = await this.readJsonOrDefault(latestKey);
702
+ const wal = this.liveEngine.getWAL();
703
+ const dirty = this.liveEngine.takeDirtyKeys();
704
+ if (!latest) {
705
+ const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
706
+ 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++;
711
+ });
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');
714
+ this.liveCheckpoints++;
715
+ return { uploadedDocs: count, fullUpload: true, duration: Date.now() - start };
716
+ }
717
+ const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
718
+ let uploaded = 0;
719
+ for (const key of dirty) {
720
+ const filePath = partitionedPath(this.dbPath, key);
721
+ if (existsSync(filePath)) {
722
+ await this.uploadBytes(`${dataPrefix}${relative(this.dbPath, filePath)}`, readFileSync(filePath), 'application/json');
723
+ uploaded++;
724
+ }
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');
727
+ 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
+ this.liveCheckpoints++;
729
+ return { uploadedDocs: uploaded, fullUpload: false, duration: Date.now() - start };
730
+ }
731
+ // __TERO_LIVE_PART3__
732
+ async restoreLiveToDirectory(targetDir, opts = {}) {
733
+ if (!this.s3Client || !this.config.cloudStorage)
734
+ throw new Error('Cloud storage not configured');
735
+ mkdirSync(targetDir, { recursive: true });
736
+ const pit = opts.pointInTime ?? Infinity;
737
+ let nodeId = opts.nodeId;
738
+ if (!nodeId) {
739
+ const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
740
+ const all = await this.listPrefix(`${base}/${basename(this.dbPath)}/nodes/`);
741
+ const ids = new Set();
742
+ for (const k of all) {
743
+ const m = k.match(/\/nodes\/([^/]+)\//);
744
+ if (m)
745
+ ids.add(m[1]);
746
+ }
747
+ if (ids.size === 0)
748
+ throw new Error('No live-backup nodes found in bucket.');
749
+ if (ids.size > 1)
750
+ throw new Error(`Multiple nodes found: ${[...ids].join(', ')}. Specify nodeId.`);
751
+ nodeId = [...ids][0];
752
+ }
753
+ const prefix = this.liveCloudPrefix(nodeId);
754
+ const latest = await this.readJsonOrDefault(`${prefix}checkpoint/latest.json`);
755
+ let docsRestored = 0;
756
+ let baseLsn = null;
757
+ if (latest) {
758
+ 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);
764
+ const key = basename(dk).replace(/\.json$/, '');
765
+ const dest = partitionedPath(targetDir, key);
766
+ mkdirSync(dirname(dest), { recursive: true });
767
+ const tmp = `${dest}.tmp.${process.pid}`;
768
+ writeFileSync(tmp, body);
769
+ renameSync(tmp, dest);
770
+ docsRestored++;
771
+ }
772
+ }
773
+ const walKeys = (await this.listPrefix(`${prefix}wal/`))
774
+ .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) > (baseLsn ?? 0) : false; }).sort();
775
+ let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
776
+ const pending = new Map();
777
+ const apply = (e) => {
778
+ if (!e.key)
779
+ return;
780
+ const dest = partitionedPath(targetDir, e.key);
781
+ if (e.operation === 'WRITE') {
782
+ mkdirSync(dirname(dest), { recursive: true });
783
+ const tmp = `${dest}.tmp.${process.pid}`;
784
+ writeFileSync(tmp, JSON.stringify(e.afterImage ?? null));
785
+ renameSync(tmp, dest);
786
+ }
787
+ else if (e.operation === 'DELETE') {
788
+ try {
789
+ unlinkSync(dest);
790
+ }
791
+ catch { }
792
+ }
793
+ lastLsn = Math.max(lastLsn, e.lsn);
794
+ };
795
+ for (const wk of walKeys) {
796
+ try {
797
+ const entries = JSON.parse(gunzipSync(await this.downloadBytes(wk)).toString('utf8'));
798
+ for (const e of entries) {
799
+ if (e.timestamp > pit)
800
+ continue;
801
+ if (e.lsn <= (baseLsn ?? 0))
802
+ continue; // already captured in checkpoint
803
+ if (e.operation === 'WRITE' || e.operation === 'DELETE') {
804
+ if (!e.transactionId) {
805
+ apply(e);
806
+ continue;
807
+ }
808
+ if (!pending.has(e.transactionId))
809
+ pending.set(e.transactionId, []);
810
+ pending.get(e.transactionId).push(e);
811
+ }
812
+ else if (e.operation === 'COMMIT') {
813
+ for (const w of pending.get(e.transactionId) ?? [])
814
+ apply(w);
815
+ pending.delete(e.transactionId);
816
+ }
817
+ else if (e.operation === 'ROLLBACK') {
818
+ pending.delete(e.transactionId);
819
+ }
820
+ }
821
+ segmentsReplayed++;
822
+ }
823
+ catch (e) {
824
+ console.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
825
+ }
826
+ }
827
+ return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn };
828
+ }
829
+ }
830
+ /**
831
+ * Per-second WAL shipper. Reads new WRITE/DELETE entries from the WAL (current log
832
+ * + any rotated archives) since the last shipped LSN, gzips them, and PUTs one
833
+ * segment per active second-with-writes. Idle seconds produce zero PUTs.
834
+ * In-flight guard: overlapping ticks are skipped. Status flips to 'degraded' on
835
+ * any upload failure and auto-recovers on the next successful tick.
836
+ */
837
+ class WalShipper {
838
+ deps;
839
+ timer = null;
840
+ shipping = false;
841
+ lastLsn = 0;
842
+ initialized = false;
843
+ shippedArchives = new Set();
844
+ status;
845
+ intervalMs;
846
+ constructor(deps) {
847
+ this.deps = deps;
848
+ this.intervalMs = deps.intervalMs;
849
+ this.status = { state: 'stopped', lastShippedLsn: 0, lastShipAt: 0, segmentsShipped: 0, totalBytesShipped: 0, errorCount: 0 };
850
+ }
851
+ start() {
852
+ if (this.timer)
853
+ return;
854
+ if (!this.initialized) {
855
+ this.lastLsn = this.deps.wal.getCurrentLSN();
856
+ this.initialized = true;
857
+ }
858
+ this.status.state = 'healthy';
859
+ this.timer = setInterval(() => { void this.tick(); }, this.deps.intervalMs);
860
+ this.timer.unref?.();
861
+ }
862
+ stop() {
863
+ if (this.timer) {
864
+ clearInterval(this.timer);
865
+ this.timer = null;
866
+ }
867
+ this.status.state = 'stopped';
868
+ }
869
+ async tick() {
870
+ if (this.shipping)
871
+ return;
872
+ this.shipping = true;
873
+ try {
874
+ await this.shipArchives();
875
+ const entries = this.deps.wal.getLogEntries(this.lastLsn).filter(e => e.operation === 'WRITE' || e.operation === 'DELETE');
876
+ if (entries.length === 0) {
877
+ this.status.state = 'healthy';
878
+ return;
879
+ }
880
+ const start = entries[0].lsn, end = entries[entries.length - 1].lsn;
881
+ const body = gzipSync(Buffer.from(JSON.stringify(entries)), { level: 1 });
882
+ await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(start)}-${padLsn(end)}.json.gz`, body);
883
+ this.lastLsn = end;
884
+ this.status.lastShippedLsn = end;
885
+ this.status.lastShipAt = Date.now();
886
+ this.status.segmentsShipped++;
887
+ this.status.totalBytesShipped += body.length;
888
+ this.status.state = 'healthy';
889
+ this.status.lastError = undefined;
890
+ }
891
+ catch (e) {
892
+ this.status.state = 'degraded';
893
+ this.status.errorCount++;
894
+ this.status.lastError = e instanceof Error ? e.message : String(e);
895
+ }
896
+ finally {
897
+ this.shipping = false;
898
+ }
899
+ }
900
+ async shipArchives() {
901
+ const archives = this.deps.wal.listArchives();
902
+ for (const p of archives) {
903
+ if (this.shippedArchives.has(p))
904
+ continue;
905
+ try {
906
+ const lines = readFileSync(p, 'utf8').trim().split('\n');
907
+ const entries = [];
908
+ for (const line of lines) {
909
+ try {
910
+ entries.push(JSON.parse(line));
911
+ }
912
+ catch { }
913
+ }
914
+ const fresh = entries.filter(e => (e.operation === 'WRITE' || e.operation === 'DELETE') && e.lsn > this.lastLsn);
915
+ if (fresh.length > 0) {
916
+ const s = fresh[0].lsn, en = fresh[fresh.length - 1].lsn;
917
+ const body = gzipSync(Buffer.from(JSON.stringify(fresh)), { level: 1 });
918
+ await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(s)}-${padLsn(en)}.json.gz`, body);
919
+ this.lastLsn = en;
920
+ this.status.lastShippedLsn = en;
921
+ this.status.lastShipAt = Date.now();
922
+ this.status.segmentsShipped++;
923
+ this.status.totalBytesShipped += body.length;
924
+ }
925
+ this.shippedArchives.add(p);
926
+ }
927
+ catch (e) {
928
+ this.status.state = 'degraded';
929
+ this.status.errorCount++;
930
+ this.status.lastError = `archive:${e instanceof Error ? e.message : e}`;
931
+ }
932
+ }
933
+ }
586
934
  }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SynchronousMode } from "./acid-engine.js";
2
2
  import { DocumentSchema, ValidationResult } from "./schema.js";
3
- import { BackupConfig, BackupMetadata, CloudStorageConfig, BucketBackupResult } from "./backup.js";
3
+ import { BackupConfig, BackupMetadata, CloudStorageConfig, BucketBackupResult, LiveBackupOptions, LiveBackupStatus } from "./backup.js";
4
4
  import { RecoveryConfig, RecoveryResult, FileRecoveryInfo } from "./recovery.js";
5
5
  interface TeroConfig {
6
6
  directory?: string;
@@ -23,6 +23,8 @@ interface TeroConfig {
23
23
  hydrateOnStartup?: HydrateConfig;
24
24
  /** v2: a default backup config installed at construction time (use configureBackup() at runtime too). */
25
25
  backup?: BackupConfig;
26
+ /** v2: per-second live WAL shipping to the bucket. RPO ≤ 1s of committed writes. */
27
+ liveBackup?: LiveBackupOptions;
26
28
  /**
27
29
  * Acquire an exclusive OS-level file lock (flock) on the data directory to
28
30
  * prevent concurrent process access. Two Node.js processes opening the same
@@ -275,6 +277,27 @@ export declare class Tero {
275
277
  checkpointAndBackupToBucket(options?: {
276
278
  tag?: string;
277
279
  }): Promise<BucketBackupResult>;
280
+ /** Enable per-second live WAL shipping to the bucket. Only consistency: 'per-second'. */
281
+ enableLiveBackup(opts: LiveBackupOptions): void;
282
+ /** Stop live WAL shipping. */
283
+ disableLiveBackup(): void;
284
+ /** Current live-backup health and counters. */
285
+ getLiveBackupStatus(): LiveBackupStatus;
286
+ /** Take an incremental checkpoint (uploads only dirty docs). First call = full upload. */
287
+ liveCheckpointToBucket(opts?: {
288
+ tag?: string;
289
+ }): Promise<{
290
+ uploadedDocs: number;
291
+ fullUpload: boolean;
292
+ duration: number;
293
+ }>;
294
+ /** Restore a fresh Tero instance from a live backup in the bucket. */
295
+ static restoreFromLiveBackup(opts: {
296
+ directory: string;
297
+ cloudStorage: CloudStorageConfig;
298
+ nodeId?: string;
299
+ pointInTime?: number;
300
+ }): Promise<Tero>;
278
301
  configureDataRecovery(config: RecoveryConfig): void;
279
302
  recoverFromCloud(key: string): Promise<boolean>;
280
303
  recoverAllFromCloud(): Promise<RecoveryResult>;
package/dist/index.js CHANGED
@@ -154,6 +154,10 @@ export class Tero {
154
154
  if (config?.backup) {
155
155
  this.configureBackup(config.backup);
156
156
  }
157
+ // v2: enable per-second live WAL shipping if configured.
158
+ if (config?.liveBackup && this.backupManager) {
159
+ this.enableLiveBackup(config.liveBackup);
160
+ }
157
161
  }
158
162
  catch (error) {
159
163
  throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -816,6 +820,44 @@ export class Tero {
816
820
  return await this.backupToBucket(options);
817
821
  }
818
822
  // ---------------------------------------------------------------------------
823
+ // Live Backup (per-second WAL shipping — RPO ≤ 1s)
824
+ // ---------------------------------------------------------------------------
825
+ /** Enable per-second live WAL shipping to the bucket. Only consistency: 'per-second'. */
826
+ enableLiveBackup(opts) {
827
+ if (!this.backupManager)
828
+ throw new Error('Backup not configured. Call configureBackup() first.');
829
+ this.backupManager.enableLiveBackup(this.acidEngine, opts);
830
+ }
831
+ /** Stop live WAL shipping. */
832
+ disableLiveBackup() {
833
+ this.backupManager?.disableLiveBackup();
834
+ }
835
+ /** Current live-backup health and counters. */
836
+ getLiveBackupStatus() {
837
+ if (!this.backupManager)
838
+ return { state: 'stopped', nodeId: 'unknown', intervalMs: 0, lastShippedLsn: 0, lastShipAt: 0, secondsSinceLastShip: 0, segmentsShipped: 0, checkpointsTaken: 0, errorCount: 0 };
839
+ return this.backupManager.getLiveBackupStatus();
840
+ }
841
+ /** Take an incremental checkpoint (uploads only dirty docs). First call = full upload. */
842
+ async liveCheckpointToBucket(opts) {
843
+ if (!this.backupManager)
844
+ throw new Error('Backup not configured. Call configureBackup() first.');
845
+ this.acidEngine.flushCommittedBuffer();
846
+ return await this.backupManager.liveCheckpointToBucket(opts);
847
+ }
848
+ /** Restore a fresh Tero instance from a live backup in the bucket. */
849
+ static async restoreFromLiveBackup(opts) {
850
+ const sanitized = opts.directory.replace(/[^a-zA-Z0-9_\-\/]/g, '') || 'TeroDB';
851
+ const tempMgr = new BackupManager(sanitized, { format: 'individual', cloudStorage: opts.cloudStorage });
852
+ try {
853
+ await tempMgr.restoreLiveToDirectory(sanitized, { nodeId: opts.nodeId, pointInTime: opts.pointInTime });
854
+ }
855
+ finally {
856
+ tempMgr.destroy();
857
+ }
858
+ return new Tero({ directory: opts.directory });
859
+ }
860
+ // ---------------------------------------------------------------------------
819
861
  // Data Recovery
820
862
  // ---------------------------------------------------------------------------
821
863
  configureDataRecovery(config) {
package/dist/recovery.js CHANGED
@@ -2,6 +2,7 @@ import { S3Client, GetObjectCommand, ListObjectsV2Command, HeadObjectCommand } f
2
2
  import { createWriteStream, existsSync, mkdirSync } from "fs";
3
3
  import { join, dirname } from "path";
4
4
  import { pipeline } from "stream/promises";
5
+ import { partitionedPath } from "./acid-engine.js";
5
6
  export class DataRecovery {
6
7
  s3Client;
7
8
  config;
@@ -67,7 +68,10 @@ export class DataRecovery {
67
68
  async recoverSingleFile(key) {
68
69
  try {
69
70
  const cloudKey = this.getCloudKey(`${key}.json`);
70
- const localFilePath = join(this.config.localPath, `${key}.json`);
71
+ // Write into the 2-level hash-partition location the engine reads from —
72
+ // NOT flat at the db root. The partition is deterministic from the key,
73
+ // so restored files are immediately visible to engine reads.
74
+ const localFilePath = partitionedPath(this.config.localPath, key);
71
75
  // Ensure local directory exists
72
76
  const localDir = dirname(localFilePath);
73
77
  if (!existsSync(localDir)) {
@@ -271,7 +275,7 @@ export class DataRecovery {
271
275
  const cloudFiles = await this.listAvailableFiles();
272
276
  const missing = [];
273
277
  for (const key of cloudFiles) {
274
- const localPath = join(this.config.localPath, `${key}.json`);
278
+ const localPath = partitionedPath(this.config.localPath, key);
275
279
  if (!existsSync(localPath)) {
276
280
  missing.push(key);
277
281
  }
@@ -373,9 +377,9 @@ export class DataRecovery {
373
377
  try {
374
378
  const cloudFiles = await this.listAvailableFiles();
375
379
  const localFiles = [];
376
- // Check which files exist locally
380
+ // Check which files exist locally (in their hash-partition location)
377
381
  for (const key of cloudFiles) {
378
- const localPath = join(this.config.localPath, `${key}.json`);
382
+ const localPath = partitionedPath(this.config.localPath, key);
379
383
  if (existsSync(localPath)) {
380
384
  localFiles.push(key);
381
385
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tero",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "description": "Tero is a JSON database that provides ACID transactions, schema validation, automated cloud backup, and automatic cloud recovery",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "test:production": "node local_tests/production-test.js",
22
22
  "test:legacy": "node local_tests/test.js",
23
23
  "test:backup": "node local_tests/backup-test.js",
24
+ "test:s3": "node local_tests/s3-live-backup-test.js",
24
25
  "test:schema": "node local_tests/schema-test.js",
25
26
  "test:all": "npm run test",
26
27
  "test:watch": "npm run test",