tero 0.1.0 → 0.3.0
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 +64 -1
- package/dist/acid-engine.d.ts +224 -9
- package/dist/acid-engine.js +775 -158
- package/dist/backup.d.ts +38 -3
- package/dist/backup.js +269 -68
- package/dist/index.d.ts +51 -4
- package/dist/index.js +267 -135
- package/dist/recovery.js +2 -13
- package/dist/s3-config.d.ts +3 -0
- package/dist/s3-config.js +21 -0
- package/package.json +1 -1
package/dist/backup.js
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
|
+
import { buildS3ClientConfig } from "./s3-config.js";
|
|
1
2
|
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync, unlinkSync, openSync, fsyncSync, closeSync, writeSync } from "fs";
|
|
2
3
|
import { join, basename, relative, dirname, sep } from "path";
|
|
3
4
|
import { create as tarCreate } from "tar";
|
|
4
5
|
import { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
|
|
5
6
|
import { Upload } from "@aws-sdk/lib-storage";
|
|
6
7
|
import { CronJob } from "cron";
|
|
7
|
-
import {
|
|
8
|
+
import { gzip as gzipCb, gunzipSync } from "zlib";
|
|
9
|
+
/** gzip on the libuv pool: compressing several MB of WAL synchronously every ship tick stalled the event loop for hundreds of ms. */
|
|
10
|
+
function gzipAsync(buf) {
|
|
11
|
+
return new Promise((resolve, reject) => gzipCb(buf, { level: 1 }, (err, out) => (err ? reject(err) : resolve(out))));
|
|
12
|
+
}
|
|
8
13
|
import { createHash, randomUUID } from "crypto";
|
|
9
|
-
import { partitionedPath, RecoveryCorruptionError, verifyLogEntryChecksum,
|
|
14
|
+
import { writeWalSeed, readRawWalLines, partitionedPath, RecoveryCorruptionError, verifyLogEntryChecksum, safeRemoveDirectory } from "./acid-engine.js";
|
|
10
15
|
/**
|
|
11
16
|
* LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort.
|
|
12
17
|
*/
|
|
@@ -129,19 +134,7 @@ export class BackupManager {
|
|
|
129
134
|
this.s3Client = this.config.customS3Client;
|
|
130
135
|
return;
|
|
131
136
|
}
|
|
132
|
-
|
|
133
|
-
region: cloudConfig.region,
|
|
134
|
-
credentials: {
|
|
135
|
-
accessKeyId: cloudConfig.accessKeyId,
|
|
136
|
-
secretAccessKey: cloudConfig.secretAccessKey,
|
|
137
|
-
},
|
|
138
|
-
};
|
|
139
|
-
// Configure for Cloudflare R2 or custom endpoints
|
|
140
|
-
if (cloudConfig.endpoint) {
|
|
141
|
-
clientConfig.endpoint = cloudConfig.endpoint;
|
|
142
|
-
clientConfig.forcePathStyle = true; // Required for R2
|
|
143
|
-
}
|
|
144
|
-
this.s3Client = new S3Client(clientConfig);
|
|
137
|
+
this.s3Client = new S3Client(buildS3ClientConfig(cloudConfig));
|
|
145
138
|
}
|
|
146
139
|
catch (error) {
|
|
147
140
|
throw new Error(`Failed to initialize cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
|
|
@@ -1004,6 +997,10 @@ export class BackupManager {
|
|
|
1004
997
|
this.liveShipper.stop();
|
|
1005
998
|
this.liveShipper = undefined;
|
|
1006
999
|
}
|
|
1000
|
+
if (this.checkpointTimer) {
|
|
1001
|
+
clearInterval(this.checkpointTimer);
|
|
1002
|
+
this.checkpointTimer = undefined;
|
|
1003
|
+
}
|
|
1007
1004
|
this.log.info('🛑 BackupManager destroyed, all scheduled backups cancelled');
|
|
1008
1005
|
}
|
|
1009
1006
|
liveCloudPrefix(nodeId) {
|
|
@@ -1034,6 +1031,10 @@ export class BackupManager {
|
|
|
1034
1031
|
return JSON.parse((await this.downloadBytes(key)).toString('utf8'));
|
|
1035
1032
|
}
|
|
1036
1033
|
catch (e) {
|
|
1034
|
+
// A missing BUCKET is a configuration error, never "no backup yet": treating
|
|
1035
|
+
// it as absent would let a restore silently produce an empty database.
|
|
1036
|
+
if (e instanceof Error && (e.name === 'NoSuchBucket' || /NoSuchBucket|bucket does not exist/i.test(e.message)))
|
|
1037
|
+
throw e;
|
|
1037
1038
|
if (e instanceof Error && (e.name === 'NoSuchKey' || /NoSuchKey|404|not found|does not exist/i.test(e.message)))
|
|
1038
1039
|
return null;
|
|
1039
1040
|
throw e;
|
|
@@ -1090,15 +1091,17 @@ export class BackupManager {
|
|
|
1090
1091
|
}
|
|
1091
1092
|
}
|
|
1092
1093
|
enableLiveBackup(engine, opts) {
|
|
1093
|
-
if (opts.consistency !== 'per-second')
|
|
1094
|
-
throw new Error("Tero live backup
|
|
1094
|
+
if (opts.consistency !== 'per-second' && opts.consistency !== 'interval')
|
|
1095
|
+
throw new Error("Tero live backup consistency must be 'per-second' (RPO ≤ 1s) or 'interval' (RPO = intervalMs).");
|
|
1095
1096
|
if (this.liveShipper)
|
|
1096
1097
|
return;
|
|
1097
1098
|
if (!this.s3Client || !this.config.cloudStorage)
|
|
1098
1099
|
throw new Error('Cloud storage not configured — call configureBackup() with cloudStorage first.');
|
|
1099
1100
|
const intervalMs = Math.max(250, opts.intervalMs ?? 1000);
|
|
1100
|
-
if (intervalMs > 1000)
|
|
1101
|
-
throw new Error(`intervalMs=${intervalMs} violates the per-second consistency contract (RPO ≤ 1s). Use intervalMs ≤ 1000.`);
|
|
1101
|
+
if (opts.consistency === 'per-second' && intervalMs > 1000)
|
|
1102
|
+
throw new Error(`intervalMs=${intervalMs} violates the per-second consistency contract (RPO ≤ 1s). Use intervalMs ≤ 1000, or consistency: 'interval'.`);
|
|
1103
|
+
if (opts.consistency === 'interval' && intervalMs > 300_000)
|
|
1104
|
+
throw new Error(`intervalMs=${intervalMs} is above the 300000ms maximum for consistency: 'interval'.`);
|
|
1102
1105
|
// Resolve nodeId: explicit > persisted file > fresh id. Sanitize hard — this
|
|
1103
1106
|
// becomes an S3 key path component; garbage must never produce nested paths.
|
|
1104
1107
|
let nodeId = opts.nodeId;
|
|
@@ -1130,24 +1133,61 @@ export class BackupManager {
|
|
|
1130
1133
|
this.liveNodeId = nodeId;
|
|
1131
1134
|
this.liveEngine = engine;
|
|
1132
1135
|
this.livePrefix = prefix;
|
|
1136
|
+
// Live checkpoints upload exactly the documents committed since the last one.
|
|
1137
|
+
engine.setDirtyTracking(true);
|
|
1133
1138
|
this.lastCheckpointError = undefined;
|
|
1134
|
-
this.liveShipper = new WalShipper({
|
|
1139
|
+
this.liveShipper = new WalShipper({
|
|
1140
|
+
wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs,
|
|
1141
|
+
// A hole in the shipped WAL makes everything after the last checkpoint
|
|
1142
|
+
// unrestorable. A checkpoint re-bases the bucket on the current state and
|
|
1143
|
+
// closes it, so take one right away instead of waiting for the timer.
|
|
1144
|
+
onGap: () => {
|
|
1145
|
+
if (this.liveCheckpoints === 0 || this.liveCheckpointPromise)
|
|
1146
|
+
return;
|
|
1147
|
+
this.liveCheckpointToBucket().catch(() => { });
|
|
1148
|
+
},
|
|
1149
|
+
});
|
|
1135
1150
|
this.liveShipper.start();
|
|
1151
|
+
// Rotation must never delete a segment the shipper has not uploaded yet.
|
|
1152
|
+
// A 1MB WAL fills in well under a second under load, so the fixed keep count
|
|
1153
|
+
// alone could unlink segments before the next 1s tick ever read them — a
|
|
1154
|
+
// transient S3 error would then truncate the continuous LSN chain in the
|
|
1155
|
+
// bucket permanently. The protector defers pruning of unshipped segments
|
|
1156
|
+
// (bounded by the WAL's protect byte budget, so an outage cannot fill disk).
|
|
1157
|
+
engine.getWAL().setArchiveProtector((segmentEndLsn) => segmentEndLsn > (this.liveShipper?.getShippedLsn() ?? Number.POSITIVE_INFINITY));
|
|
1136
1158
|
this.log.info(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
|
|
1137
1159
|
// CRITICAL: take the initial FULL checkpoint automatically. Without it, every
|
|
1138
1160
|
// document written BEFORE enableLiveBackup() is unrestorable until the first
|
|
1139
1161
|
// manual liveCheckpointToBucket() — a crash in that window loses all prior data.
|
|
1140
1162
|
// Retry with backoff (bucket may be temporarily unreachable); surface failures
|
|
1141
1163
|
// in getLiveBackupStatus().lastCheckpointError.
|
|
1142
|
-
void this.runInitialCheckpoint(prefix);
|
|
1164
|
+
void this.runInitialCheckpoint(prefix, Math.max(0, opts.initialCheckpointDelayMs ?? 0));
|
|
1165
|
+
const ckptEvery = opts.checkpointIntervalMs ?? 15 * 60_000;
|
|
1166
|
+
if (ckptEvery > 0) {
|
|
1167
|
+
this.checkpointTimer = setInterval(() => {
|
|
1168
|
+
// Skip while the initial checkpoint is still being retried.
|
|
1169
|
+
if (this.liveCheckpoints === 0 || this.liveCheckpointPromise)
|
|
1170
|
+
return;
|
|
1171
|
+
this.liveCheckpointToBucket().catch(() => { });
|
|
1172
|
+
}, Math.max(1000, ckptEvery));
|
|
1173
|
+
this.checkpointTimer.unref?.();
|
|
1174
|
+
}
|
|
1143
1175
|
}
|
|
1176
|
+
checkpointTimer;
|
|
1144
1177
|
/** Initial full checkpoint with bounded retry. Stops on success or disable. */
|
|
1145
|
-
async runInitialCheckpoint(prefix) {
|
|
1178
|
+
async runInitialCheckpoint(prefix, delayMs = 0) {
|
|
1179
|
+
if (delayMs > 0) {
|
|
1180
|
+
await new Promise(r => { const t = setTimeout(r, delayMs); t.unref?.(); });
|
|
1181
|
+
}
|
|
1146
1182
|
for (let attempt = 1;; attempt++) {
|
|
1147
1183
|
if (this.liveShipper === undefined || this.livePrefix !== prefix)
|
|
1148
1184
|
return; // disabled/re-enabled under us
|
|
1149
1185
|
try {
|
|
1150
|
-
|
|
1186
|
+
// Always FULL: whatever this process found on disk (a restore, a period with
|
|
1187
|
+
// live backup off, history whose WAL was pruned) is re-based in the bucket.
|
|
1188
|
+
// An incremental here would only upload this session's dirty documents and
|
|
1189
|
+
// then prune the WAL that held everything else.
|
|
1190
|
+
await this.liveCheckpointToBucket({ full: true });
|
|
1151
1191
|
return;
|
|
1152
1192
|
}
|
|
1153
1193
|
catch (e) {
|
|
@@ -1164,6 +1204,15 @@ export class BackupManager {
|
|
|
1164
1204
|
return;
|
|
1165
1205
|
this.liveShipper.stop();
|
|
1166
1206
|
this.liveShipper = undefined;
|
|
1207
|
+
if (this.checkpointTimer) {
|
|
1208
|
+
clearInterval(this.checkpointTimer);
|
|
1209
|
+
this.checkpointTimer = undefined;
|
|
1210
|
+
}
|
|
1211
|
+
// Detach the protector: with no shipper there is no bucket to protect WAL
|
|
1212
|
+
// for, so retention must return to the plain keep-count behaviour — else
|
|
1213
|
+
// "disabled" would silently mean "never prune".
|
|
1214
|
+
this.liveEngine?.getWAL().setArchiveProtector(null);
|
|
1215
|
+
this.liveEngine?.setDirtyTracking(false);
|
|
1167
1216
|
this.log.info('🛑 Tero live backup disabled');
|
|
1168
1217
|
}
|
|
1169
1218
|
getLiveBackupStatus() {
|
|
@@ -1178,7 +1227,7 @@ export class BackupManager {
|
|
|
1178
1227
|
};
|
|
1179
1228
|
}
|
|
1180
1229
|
// __TERO_LIVE_PART2__
|
|
1181
|
-
async liveCheckpointToBucket(
|
|
1230
|
+
async liveCheckpointToBucket(opts) {
|
|
1182
1231
|
if (!this.liveEngine || !this.liveNodeId || !this.livePrefix)
|
|
1183
1232
|
throw new Error('Live backup not enabled — call enableLiveBackup() first.');
|
|
1184
1233
|
// Share the in-flight run: concurrent callers (e.g. the automatic initial
|
|
@@ -1186,7 +1235,7 @@ export class BackupManager {
|
|
|
1186
1235
|
// run could publish latest.json before the first run's data is durable.
|
|
1187
1236
|
if (this.liveCheckpointPromise)
|
|
1188
1237
|
return this.liveCheckpointPromise;
|
|
1189
|
-
this.liveCheckpointPromise = this.doLiveCheckpoint();
|
|
1238
|
+
this.liveCheckpointPromise = this.doLiveCheckpoint(opts?.full === true);
|
|
1190
1239
|
try {
|
|
1191
1240
|
const r = await this.liveCheckpointPromise;
|
|
1192
1241
|
this.lastCheckpointError = undefined;
|
|
@@ -1200,7 +1249,7 @@ export class BackupManager {
|
|
|
1200
1249
|
this.liveCheckpointPromise = undefined;
|
|
1201
1250
|
}
|
|
1202
1251
|
}
|
|
1203
|
-
async doLiveCheckpoint() {
|
|
1252
|
+
async doLiveCheckpoint(forceFull = false) {
|
|
1204
1253
|
const engine = this.liveEngine;
|
|
1205
1254
|
const start = Date.now();
|
|
1206
1255
|
const ckptPrefix = `${this.livePrefix}checkpoint/`;
|
|
@@ -1213,19 +1262,49 @@ export class BackupManager {
|
|
|
1213
1262
|
// instead would let mid-checkpoint writes be skipped by BOTH the checkpoint
|
|
1214
1263
|
// content AND the replay filter — silent stale-data loss.
|
|
1215
1264
|
const ckptLsn = engine.getLastCommittedLSN();
|
|
1216
|
-
//
|
|
1217
|
-
|
|
1265
|
+
// Replay floor: a transaction that BEGAN before this checkpoint but commits
|
|
1266
|
+
// after it has WRITE records below ckptLsn. Restore must replay from here.
|
|
1267
|
+
const replayFromLsn = engine.getReplayFloorLsn();
|
|
1268
|
+
const capturedAt = Date.now();
|
|
1269
|
+
// (2) Write committed data so the files we read reflect all commits ≤ ckptLsn.
|
|
1270
|
+
// No fsync: the backup only reads these files back (from the page cache);
|
|
1271
|
+
// local durability is the WAL's and the durable checkpoint's job. The forced
|
|
1272
|
+
// variant fsynced every pending file synchronously — seconds of blocked loop.
|
|
1273
|
+
engine.flushCommittedBuffer(false, Infinity);
|
|
1274
|
+
// (3) Pin the version-consistent view NOW, in the same tick as the LSN capture.
|
|
1275
|
+
// Opening the snapshot after the first await (as before) let commits that
|
|
1276
|
+
// landed in between leak into a checkpoint labelled with the older LSN —
|
|
1277
|
+
// a point-in-time restore then returned data from after the requested time.
|
|
1278
|
+
// By reference, once: committed images are never mutated and the checkpoint only
|
|
1279
|
+
// serializes them. Deep-cloning every dirty document here (twice — beginSnapshot
|
|
1280
|
+
// peeked again) blocked the event loop for seconds and doubled peak memory.
|
|
1281
|
+
const dirtyAtCapture = engine.peekDirtyKeys(ckptLsn, false);
|
|
1282
|
+
const handle = engine.beginSnapshot(ckptLsn, dirtyAtCapture);
|
|
1283
|
+
// A full checkpoint covers everything below its replay floor, so the shipper
|
|
1284
|
+
// never needs to (re)send older WAL — after a restart it would otherwise
|
|
1285
|
+
// re-upload ranges the bucket already holds.
|
|
1286
|
+
if (forceFull && this.liveShipper && this.liveShipper.getShippedLsn() < replayFromLsn - 1) {
|
|
1287
|
+
this.liveShipper.setInitialLsn(replayFromLsn - 1);
|
|
1288
|
+
}
|
|
1289
|
+
try {
|
|
1290
|
+
return await this.doLiveCheckpointCaptured(engine, start, ckptPrefix, latestKey, ckptLsn, replayFromLsn, capturedAt, dirtyAtCapture, handle, forceFull);
|
|
1291
|
+
}
|
|
1292
|
+
finally {
|
|
1293
|
+
handle.close();
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
async doLiveCheckpointCaptured(engine, start, ckptPrefix, latestKey, ckptLsn, replayFromLsn, capturedAt, dirtyAtCapture, handle, forceFull = false) {
|
|
1218
1297
|
const posixRel = (p) => relative(this.dbPath, p).split(sep).join('/');
|
|
1219
1298
|
const latest = await this.readJsonOrDefault(latestKey);
|
|
1220
|
-
if (!latest) {
|
|
1221
|
-
// FULL checkpoint: consumes
|
|
1299
|
+
if (!latest || forceFull) {
|
|
1300
|
+
// FULL checkpoint: consumes the version-consistent snapshot pinned at capture
|
|
1222
1301
|
const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
|
|
1223
1302
|
const dataPrefix = `${ckptPrefix}${baseTs}/data/`;
|
|
1224
|
-
const dirtySnapshot =
|
|
1303
|
+
const dirtySnapshot = dirtyAtCapture;
|
|
1225
1304
|
let count = 0;
|
|
1226
1305
|
let tombstoned = 0;
|
|
1227
1306
|
const manifestDataItems = [];
|
|
1228
|
-
await pooledConsumeAsyncGen(
|
|
1307
|
+
await pooledConsumeAsyncGen(handle.files(), 16, async (entry) => {
|
|
1229
1308
|
const filePath = partitionedPath(this.dbPath, entry.key);
|
|
1230
1309
|
const rel = posixRel(filePath);
|
|
1231
1310
|
if (entry.state === 'deleted') {
|
|
@@ -1279,16 +1358,24 @@ export class BackupManager {
|
|
|
1279
1358
|
};
|
|
1280
1359
|
await this.uploadBytes(`${ckptPrefix}${baseTs}/index.json`, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, createdAt: new Date().toISOString(), docCount: count }, null, 2)), 'application/json');
|
|
1281
1360
|
await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
|
|
1282
|
-
await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
|
|
1361
|
+
await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, replayFromLsn, capturedAt, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
|
|
1283
1362
|
// CRITICAL P0 ORDERING: Acknowledge ONLY AFTER latest and manifest are published!
|
|
1284
1363
|
// Every acknowledged dirty entry now has a durable representation (present file or .deleted tombstone)
|
|
1285
1364
|
engine.acknowledgeDirtyKeys(dirtySnapshot.values());
|
|
1365
|
+
await this.pruneCoveredWal(walKeys, replayFromLsn);
|
|
1366
|
+
// The previous base is superseded by this one.
|
|
1367
|
+
if (latest && latest.baseTs !== baseTs) {
|
|
1368
|
+
const stale = await this.listPrefix(`${ckptPrefix}${latest.baseTs}/`);
|
|
1369
|
+
await pooledMap(stale, 16, async (k) => { try {
|
|
1370
|
+
await this.deleteObject(k);
|
|
1371
|
+
}
|
|
1372
|
+
catch { /* approved: retried next full checkpoint */ } });
|
|
1373
|
+
}
|
|
1286
1374
|
this.liveCheckpoints++;
|
|
1287
1375
|
return { uploadedDocs: count, tombstonedDocs: tombstoned, fullUpload: true, duration: Date.now() - start };
|
|
1288
1376
|
}
|
|
1289
|
-
// INCREMENTAL checkpoint — upload ONLY dirty docs
|
|
1290
|
-
const
|
|
1291
|
-
const dirtyEntries = [...dirtySnapshot.values()];
|
|
1377
|
+
// INCREMENTAL checkpoint — upload ONLY dirty docs (as of capture), tombstone deleted ones.
|
|
1378
|
+
const dirtyEntries = [...dirtyAtCapture.values()];
|
|
1292
1379
|
const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
|
|
1293
1380
|
let uploaded = 0;
|
|
1294
1381
|
let tombstoned = 0;
|
|
@@ -1353,12 +1440,31 @@ export class BackupManager {
|
|
|
1353
1440
|
lastCheckpointAt: new Date().toISOString()
|
|
1354
1441
|
};
|
|
1355
1442
|
await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
|
|
1356
|
-
await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs: latest.baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString(), dirtyUploaded: uploaded, tombstoned }, null, 2)), 'application/json');
|
|
1443
|
+
await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs: latest.baseTs, baseLsn: ckptLsn, replayFromLsn, capturedAt, updatedAt: new Date().toISOString(), dirtyUploaded: uploaded, tombstoned }, null, 2)), 'application/json');
|
|
1357
1444
|
// CRITICAL P0 ORDERING: Two-phase acknowledgment: ONLY acknowledge successfully uploaded items AFTER manifest and latest are published
|
|
1358
1445
|
engine.acknowledgeDirtyKeys(ackList);
|
|
1446
|
+
await this.pruneCoveredWal(walKeys, replayFromLsn);
|
|
1359
1447
|
this.liveCheckpoints++;
|
|
1360
1448
|
return { uploadedDocs: uploaded, tombstonedDocs: tombstoned, fullUpload: false, duration: Date.now() - start };
|
|
1361
1449
|
}
|
|
1450
|
+
/**
|
|
1451
|
+
* Delete bucket WAL objects the published checkpoint makes redundant: a restore
|
|
1452
|
+
* replays only from replayFromLsn onward, so segments that END before it are
|
|
1453
|
+
* never read again. Without this the WAL prefix grows by one object per ship
|
|
1454
|
+
* forever, and every checkpoint's LIST gets slower and costlier. Best-effort.
|
|
1455
|
+
*/
|
|
1456
|
+
async pruneCoveredWal(walKeys, replayFromLsn) {
|
|
1457
|
+
const stale = walKeys.filter(k => {
|
|
1458
|
+
const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/);
|
|
1459
|
+
return m ? parseInt(m[2], 10) < replayFromLsn : false;
|
|
1460
|
+
});
|
|
1461
|
+
await pooledMap(stale, 16, async (k) => {
|
|
1462
|
+
try {
|
|
1463
|
+
await this.deleteObject(k);
|
|
1464
|
+
}
|
|
1465
|
+
catch { /* approved: retried at the next checkpoint */ }
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1362
1468
|
// __TERO_LIVE_PART3__
|
|
1363
1469
|
/**
|
|
1364
1470
|
* Crash-safe restore: downloads and replays WAL into a fresh temporary staging directory,
|
|
@@ -1472,8 +1578,20 @@ export class BackupManager {
|
|
|
1472
1578
|
const latest = await this.readJsonOrDefault(`${prefix}checkpoint/latest.json`);
|
|
1473
1579
|
let docsRestored = 0;
|
|
1474
1580
|
let baseLsn = null;
|
|
1581
|
+
// First LSN the WAL replay must read. Checkpoints written before replayFromLsn
|
|
1582
|
+
// existed fall back to baseLsn + 1 (their old behaviour).
|
|
1583
|
+
let replayFrom = 0;
|
|
1475
1584
|
if (latest) {
|
|
1476
1585
|
baseLsn = latest.baseLsn ?? null;
|
|
1586
|
+
replayFrom = typeof latest.replayFromLsn === 'number' ? latest.replayFromLsn : (baseLsn ?? -1) + 1;
|
|
1587
|
+
// The checkpoint already contains every commit up to baseLsn, so it cannot
|
|
1588
|
+
// represent an earlier moment. Refuse instead of silently returning newer data.
|
|
1589
|
+
if (targetLsn !== undefined && baseLsn !== null && targetLsn < baseLsn) {
|
|
1590
|
+
throw new Error(`Cannot restore to LSN ${targetLsn}: the oldest restorable point is the latest checkpoint at LSN ${baseLsn}.`);
|
|
1591
|
+
}
|
|
1592
|
+
if (pit !== undefined && typeof latest.capturedAt === 'number' && pit < latest.capturedAt) {
|
|
1593
|
+
throw new Error(`Cannot restore to ${new Date(pit).toISOString()}: the oldest restorable point is the latest checkpoint at ${new Date(latest.capturedAt).toISOString()}.`);
|
|
1594
|
+
}
|
|
1477
1595
|
const dataWithMeta = await this.listPrefixWithMeta(`${prefix}checkpoint/${latest.baseTs}/data/`);
|
|
1478
1596
|
const tombstoneMeta = new Map();
|
|
1479
1597
|
const activeMeta = new Map();
|
|
@@ -1525,13 +1643,21 @@ export class BackupManager {
|
|
|
1525
1643
|
}
|
|
1526
1644
|
}
|
|
1527
1645
|
const walKeys = (await this.listPrefix(`${prefix}wal/`))
|
|
1528
|
-
.filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2])
|
|
1646
|
+
.filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) >= replayFrom : false; })
|
|
1529
1647
|
.sort((a, b) => {
|
|
1530
1648
|
const ma = a.match(/seg-(\d+)-(\d+)\.json\.gz$/);
|
|
1531
1649
|
const mb = b.match(/seg-(\d+)-(\d+)\.json\.gz$/);
|
|
1532
1650
|
return parseInt(ma[1], 10) - parseInt(mb[1], 10);
|
|
1533
1651
|
});
|
|
1652
|
+
// Highest LSN the bucket holds for this node, including anything past a gap:
|
|
1653
|
+
// the restored database must number above all of it.
|
|
1654
|
+
let bucketMaxEnd = -1;
|
|
1655
|
+
for (const wk of walKeys) {
|
|
1656
|
+
const mm = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
|
|
1657
|
+
bucketMaxEnd = Math.max(bucketMaxEnd, parseInt(mm[2], 10));
|
|
1658
|
+
}
|
|
1534
1659
|
let prevEnd = -1;
|
|
1660
|
+
let walGapAtLsn;
|
|
1535
1661
|
for (let i = 0; i < walKeys.length; i++) {
|
|
1536
1662
|
const wk = walKeys[i];
|
|
1537
1663
|
const m = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
|
|
@@ -1539,16 +1665,30 @@ export class BackupManager {
|
|
|
1539
1665
|
if (s > e) {
|
|
1540
1666
|
throw new RecoveryCorruptionError(wk, 0, `Invalid segment range in cloud WAL: startLsn (${s}) > endLsn (${e})`);
|
|
1541
1667
|
}
|
|
1668
|
+
let gap = null;
|
|
1542
1669
|
if (i === 0) {
|
|
1543
|
-
if (baseLsn !== undefined && baseLsn !== null && baseLsn > 0 && s >
|
|
1544
|
-
|
|
1670
|
+
if (baseLsn !== undefined && baseLsn !== null && baseLsn > 0 && s > replayFrom) {
|
|
1671
|
+
gap = `WAL continuity gap between base checkpoint (replay from ${replayFrom}) and first cloud WAL segment (${s})`;
|
|
1545
1672
|
}
|
|
1546
1673
|
}
|
|
1547
1674
|
else if (prevEnd >= 0) {
|
|
1548
|
-
|
|
1549
|
-
|
|
1675
|
+
// Overlap (the same range shipped twice, e.g. around a restart) is harmless:
|
|
1676
|
+
// replay skips LSNs it has already seen. A gap is not.
|
|
1677
|
+
if (s > prevEnd + 1) {
|
|
1678
|
+
gap = `WAL segment gap in cloud restore: expected ${prevEnd + 1}, found ${s}`;
|
|
1550
1679
|
}
|
|
1551
1680
|
}
|
|
1681
|
+
if (gap) {
|
|
1682
|
+
if (!opts.allowWalGap)
|
|
1683
|
+
throw new RecoveryCorruptionError(wk, 0, gap);
|
|
1684
|
+
// Opt-in: restore the checkpoint plus the contiguous WAL before the gap
|
|
1685
|
+
// instead of refusing to restore anything. Replaying past a gap could
|
|
1686
|
+
// apply a later write on top of a missing earlier one, so stop here.
|
|
1687
|
+
walGapAtLsn = i === 0 ? replayFrom : prevEnd + 1;
|
|
1688
|
+
this.log.warn(`⚠️ ${gap} — allowWalGap is set: restoring up to LSN ${walGapAtLsn - 1} and ignoring ${walKeys.length - i} later segment(s).`);
|
|
1689
|
+
walKeys.length = i;
|
|
1690
|
+
break;
|
|
1691
|
+
}
|
|
1552
1692
|
prevEnd = Math.max(prevEnd, e);
|
|
1553
1693
|
}
|
|
1554
1694
|
// PITR: wall-clock PIT is not authoritative — convert to LSN once, then replay by LSN (P1)
|
|
@@ -1580,6 +1720,7 @@ export class BackupManager {
|
|
|
1580
1720
|
effectivePit = undefined;
|
|
1581
1721
|
}
|
|
1582
1722
|
let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
|
|
1723
|
+
let replayedThrough = -1;
|
|
1583
1724
|
const pending = new Map();
|
|
1584
1725
|
const apply = (e) => {
|
|
1585
1726
|
if (!e.key)
|
|
@@ -1623,6 +1764,11 @@ export class BackupManager {
|
|
|
1623
1764
|
}
|
|
1624
1765
|
let prevRecordLsn = -1;
|
|
1625
1766
|
for (const e of entries) {
|
|
1767
|
+
if (e.lsn <= replayedThrough) {
|
|
1768
|
+
prevRecordLsn = e.lsn;
|
|
1769
|
+
continue;
|
|
1770
|
+
} // already seen in an overlapping segment
|
|
1771
|
+
replayedThrough = e.lsn;
|
|
1626
1772
|
if (prevRecordLsn !== -1 && e.lsn <= prevRecordLsn) {
|
|
1627
1773
|
throw new RecoveryCorruptionError(wk, 0, `Non-monotonic record LSN in cloud WAL segment: expected > ${prevRecordLsn}, got ${e.lsn}`, e.lsn);
|
|
1628
1774
|
}
|
|
@@ -1646,11 +1792,12 @@ export class BackupManager {
|
|
|
1646
1792
|
}
|
|
1647
1793
|
if (effectiveTargetLsn !== undefined && e.lsn > effectiveTargetLsn)
|
|
1648
1794
|
continue;
|
|
1649
|
-
if (e.lsn
|
|
1795
|
+
if (e.lsn < replayFrom)
|
|
1650
1796
|
continue;
|
|
1651
1797
|
if (e.operation === 'WRITE' || e.operation === 'DELETE') {
|
|
1652
1798
|
if (!e.transactionId) {
|
|
1653
|
-
|
|
1799
|
+
if (e.lsn > (baseLsn ?? -1))
|
|
1800
|
+
apply(e);
|
|
1654
1801
|
continue;
|
|
1655
1802
|
}
|
|
1656
1803
|
if (!pending.has(e.transactionId))
|
|
@@ -1658,8 +1805,13 @@ export class BackupManager {
|
|
|
1658
1805
|
pending.get(e.transactionId).push(e);
|
|
1659
1806
|
}
|
|
1660
1807
|
else if (e.operation === 'COMMIT') {
|
|
1661
|
-
|
|
1662
|
-
|
|
1808
|
+
// Visibility is decided by the COMMIT position: transactions committed at
|
|
1809
|
+
// or before baseLsn are already in the checkpoint data (re-applying their
|
|
1810
|
+
// older after-images could roll documents back); later ones are replayed
|
|
1811
|
+
// in full, including WRITE records that precede baseLsn.
|
|
1812
|
+
if (e.lsn > (baseLsn ?? -1))
|
|
1813
|
+
for (const w of pending.get(e.transactionId) ?? [])
|
|
1814
|
+
apply(w);
|
|
1663
1815
|
pending.delete(e.transactionId);
|
|
1664
1816
|
}
|
|
1665
1817
|
else if (e.operation === 'ROLLBACK') {
|
|
@@ -1668,7 +1820,10 @@ export class BackupManager {
|
|
|
1668
1820
|
}
|
|
1669
1821
|
segmentsReplayed++;
|
|
1670
1822
|
}
|
|
1671
|
-
|
|
1823
|
+
// Continue LSN numbering above everything the bucket holds for this node.
|
|
1824
|
+
const highestLsn = Math.max(baseLsn ?? 0, prevEnd, lastLsn, bucketMaxEnd);
|
|
1825
|
+
writeWalSeed(targetDir, highestLsn + 1);
|
|
1826
|
+
return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn: highestLsn, ...(walGapAtLsn !== undefined ? { walGapAtLsn } : {}) };
|
|
1672
1827
|
}
|
|
1673
1828
|
}
|
|
1674
1829
|
/**
|
|
@@ -1695,6 +1850,14 @@ class WalShipper {
|
|
|
1695
1850
|
this.intervalMs = deps.intervalMs;
|
|
1696
1851
|
this.status = { state: 'stopped', lastShippedLsn: 0, lastShipAt: 0, segmentsShipped: 0, totalBytesShipped: 0, errorCount: 0 };
|
|
1697
1852
|
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Highest LSN whose entries are durably in the bucket. -1 while nothing has
|
|
1855
|
+
* been shipped (including "not started yet") so the WAL archive protector
|
|
1856
|
+
* keeps every segment on disk until the first successful upload.
|
|
1857
|
+
*/
|
|
1858
|
+
getShippedLsn() {
|
|
1859
|
+
return this.initialized ? this.lastLsn : -1;
|
|
1860
|
+
}
|
|
1698
1861
|
start() {
|
|
1699
1862
|
if (this.timer)
|
|
1700
1863
|
return;
|
|
@@ -1736,15 +1899,35 @@ class WalShipper {
|
|
|
1736
1899
|
this.shipping = true;
|
|
1737
1900
|
this.tickCount++;
|
|
1738
1901
|
try {
|
|
1739
|
-
|
|
1740
|
-
//
|
|
1741
|
-
|
|
1742
|
-
if (entries.length === 0) {
|
|
1743
|
-
this.status.state = 'healthy';
|
|
1902
|
+
// Archives hold older LSNs than the active log. If any of them is still
|
|
1903
|
+
// unshipped, shipping the active log now would jump past it and leave a hole.
|
|
1904
|
+
if (!(await this.shipArchives()))
|
|
1744
1905
|
return;
|
|
1906
|
+
// All operations (including BEGIN and CHECKPOINT) are shipped to guarantee raw LSN continuity.
|
|
1907
|
+
// Raw lines: "[" + lines + "]" is byte-identical to JSON.stringify(entries).
|
|
1908
|
+
let start, end, body;
|
|
1909
|
+
if (this.deps.wal.getLogPath) {
|
|
1910
|
+
const { lines, firstLsn, lastLsn } = readRawWalLines(this.deps.wal.getLogPath(), this.lastLsn);
|
|
1911
|
+
if (lines.length === 0 || firstLsn === null || lastLsn === null) {
|
|
1912
|
+
this.status.state = 'healthy';
|
|
1913
|
+
return;
|
|
1914
|
+
}
|
|
1915
|
+
if (this.lastLsn >= 0 && firstLsn > this.lastLsn + 1)
|
|
1916
|
+
this.deps.onGap?.();
|
|
1917
|
+
start = firstLsn;
|
|
1918
|
+
end = lastLsn;
|
|
1919
|
+
body = await gzipAsync(Buffer.from('[' + lines.join(',') + ']'));
|
|
1920
|
+
}
|
|
1921
|
+
else {
|
|
1922
|
+
const entries = this.deps.wal.getLogEntries(this.lastLsn + 1);
|
|
1923
|
+
if (entries.length === 0) {
|
|
1924
|
+
this.status.state = 'healthy';
|
|
1925
|
+
return;
|
|
1926
|
+
}
|
|
1927
|
+
start = entries[0].lsn;
|
|
1928
|
+
end = entries[entries.length - 1].lsn;
|
|
1929
|
+
body = await gzipAsync(Buffer.from(JSON.stringify(entries)));
|
|
1745
1930
|
}
|
|
1746
|
-
const start = entries[0].lsn, end = entries[entries.length - 1].lsn;
|
|
1747
|
-
const body = gzipSync(Buffer.from(JSON.stringify(entries)), { level: 1 });
|
|
1748
1931
|
await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(start)}-${padLsn(end)}.json.gz`, body);
|
|
1749
1932
|
this.lastLsn = end;
|
|
1750
1933
|
this.status.lastShippedLsn = end;
|
|
@@ -1763,28 +1946,37 @@ class WalShipper {
|
|
|
1763
1946
|
this.shipping = false;
|
|
1764
1947
|
}
|
|
1765
1948
|
}
|
|
1949
|
+
/** Ships rotated segments OLDEST FIRST. Returns false when one could not be shipped (nothing newer may go before it). */
|
|
1766
1950
|
async shipArchives() {
|
|
1767
|
-
|
|
1951
|
+
// listArchives() is newest-first. Shipping in that order advanced lastLsn past
|
|
1952
|
+
// every older segment, which were then marked shipped without being uploaded.
|
|
1953
|
+
const startOf = (p) => { const r = basename(p).match(/^\.wal\.seg-(\d+)-(\d+)$/); return r ? parseInt(r[1], 10) : 0; };
|
|
1954
|
+
const archives = this.deps.wal.listArchives().slice().sort((a, b) => startOf(a) - startOf(b));
|
|
1768
1955
|
for (const p of archives) {
|
|
1769
1956
|
if (this.shippedArchives.has(p))
|
|
1770
1957
|
continue;
|
|
1771
1958
|
// Throttle failing archives: retry each failing archive only every 5 ticks.
|
|
1772
1959
|
const retryAt = this.archiveRetryAt.get(p);
|
|
1773
1960
|
if (retryAt !== undefined && this.tickCount < retryAt)
|
|
1774
|
-
|
|
1961
|
+
return false;
|
|
1775
1962
|
try {
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
this.
|
|
1963
|
+
// Segment names carry their LSN range. Fully shipped already → nothing to
|
|
1964
|
+
// read (after a restart this used to re-parse every retained segment).
|
|
1965
|
+
// Otherwise forward the not-yet-shipped raw lines — no parse/re-serialize.
|
|
1966
|
+
const range = basename(p).match(/^\.wal\.seg-(\d+)-(\d+)$/);
|
|
1967
|
+
if (range && parseInt(range[2], 10) <= this.lastLsn) {
|
|
1968
|
+
this.shippedArchives.add(p);
|
|
1969
|
+
this.archiveRetryAt.delete(p);
|
|
1970
|
+
continue;
|
|
1971
|
+
}
|
|
1972
|
+
const { lines, firstLsn, lastLsn } = readRawWalLines(p, this.lastLsn);
|
|
1973
|
+
if (lines.length > 0 && firstLsn !== null && lastLsn !== null) {
|
|
1974
|
+
if (this.lastLsn >= 0 && firstLsn > this.lastLsn + 1)
|
|
1975
|
+
this.deps.onGap?.();
|
|
1976
|
+
const body = await gzipAsync(Buffer.from('[' + lines.join(',') + ']'));
|
|
1977
|
+
await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(firstLsn)}-${padLsn(lastLsn)}.json.gz`, body);
|
|
1978
|
+
this.lastLsn = lastLsn;
|
|
1979
|
+
this.status.lastShippedLsn = lastLsn;
|
|
1788
1980
|
this.status.lastShipAt = Date.now();
|
|
1789
1981
|
this.status.segmentsShipped++;
|
|
1790
1982
|
this.status.totalBytesShipped += body.length;
|
|
@@ -1797,7 +1989,16 @@ class WalShipper {
|
|
|
1797
1989
|
this.status.state = 'degraded';
|
|
1798
1990
|
this.status.errorCount++;
|
|
1799
1991
|
this.status.lastError = `archive:${e instanceof Error ? e.message : e}`;
|
|
1992
|
+
return false;
|
|
1800
1993
|
}
|
|
1801
1994
|
}
|
|
1995
|
+
// Bound the bookkeeping to segments that still exist.
|
|
1996
|
+
if (this.shippedArchives.size > archives.length + 64) {
|
|
1997
|
+
const live = new Set(archives);
|
|
1998
|
+
for (const p of this.shippedArchives)
|
|
1999
|
+
if (!live.has(p))
|
|
2000
|
+
this.shippedArchives.delete(p);
|
|
2001
|
+
}
|
|
2002
|
+
return true;
|
|
1802
2003
|
}
|
|
1803
2004
|
}
|