tero 0.0.8 → 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/dist/acid-engine.d.ts +17 -0
- package/dist/acid-engine.js +25 -0
- package/dist/backup.d.ts +52 -0
- package/dist/backup.js +354 -6
- package/dist/index.d.ts +24 -1
- package/dist/index.js +42 -0
- package/package.json +1 -1
package/dist/acid-engine.d.ts
CHANGED
|
@@ -189,6 +189,23 @@ export declare class ACIDStorageEngine {
|
|
|
189
189
|
private committedBuffer;
|
|
190
190
|
private dataFlushTimer?;
|
|
191
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;
|
|
192
209
|
constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number);
|
|
193
210
|
private initializeStorage;
|
|
194
211
|
private performCrashRecovery;
|
package/dist/acid-engine.js
CHANGED
|
@@ -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
|
-
|
|
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/package.json
CHANGED