tero 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/backup.js CHANGED
@@ -1,7 +1,8 @@
1
- import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync, unlinkSync } from "fs";
1
+ import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync, unlinkSync, openSync, fsyncSync, closeSync } from "fs";
2
2
  import { join, basename, relative, dirname, sep } from "path";
3
3
  import { create as tarCreate } from "tar";
4
4
  import { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
5
+ import { Upload } from "@aws-sdk/lib-storage";
5
6
  import { CronJob } from "cron";
6
7
  import { gzipSync, gunzipSync } from "zlib";
7
8
  import { randomUUID } from "crypto";
@@ -50,9 +51,9 @@ export class BackupManager {
50
51
  constructor(dbPath, config) {
51
52
  this.dbPath = dbPath;
52
53
  this.config = config;
53
- this.log = config.logger === 'silent'
54
- ? { info: () => { }, warn: () => { }, error: () => { } }
55
- : (config.logger ?? console);
54
+ this.log = config.logger && config.logger !== 'silent'
55
+ ? config.logger
56
+ : { info: () => { }, warn: () => { }, error: () => { } };
56
57
  if (config.cloudStorage) {
57
58
  this.initializeCloudStorage(config.cloudStorage);
58
59
  }
@@ -301,6 +302,30 @@ export class BackupManager {
301
302
  try {
302
303
  if (!existsSync(localPath))
303
304
  return;
305
+ const stat = statSync(localPath);
306
+ // Stream large files (>5MB) via multipart Upload to avoid loading entire file into heap (OOM on tar.gz)
307
+ const isLarge = stat.size > 5 * 1024 * 1024;
308
+ if (isLarge) {
309
+ const stream = createReadStream(localPath);
310
+ const upload = new Upload({
311
+ client: this.s3Client,
312
+ params: {
313
+ Bucket: this.config.cloudStorage.bucket,
314
+ Key: cloudKey,
315
+ Body: stream,
316
+ ContentType: cloudKey.endsWith('.json') ? 'application/json' : 'application/octet-stream',
317
+ Metadata: {
318
+ 'backup-timestamp': new Date().toISOString(),
319
+ 'source-db': this.getDbName(),
320
+ 'backup-format': this.config.format
321
+ }
322
+ },
323
+ queueSize: 4,
324
+ partSize: 5 * 1024 * 1024,
325
+ });
326
+ await upload.done();
327
+ return;
328
+ }
304
329
  const fs = await import('fs/promises');
305
330
  const body = await fs.readFile(localPath);
306
331
  const cmd = new PutObjectCommand({
@@ -310,7 +335,7 @@ export class BackupManager {
310
335
  ContentType: cloudKey.endsWith('.json') ? 'application/json' : 'application/octet-stream',
311
336
  Metadata: {
312
337
  'backup-timestamp': new Date().toISOString(),
313
- 'source-db': basename(this.dbPath),
338
+ 'source-db': this.getDbName(),
314
339
  'backup-format': this.config.format
315
340
  }
316
341
  });
@@ -359,10 +384,40 @@ export class BackupManager {
359
384
  throw new Error(`Failed to upload individual files to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
360
385
  }
361
386
  }
387
+ /**
388
+ * Derive a collision-free bucket key prefix for this DB instance.
389
+ * The old `basename(dbPath)` implementation made `/tmp/a/TeroDB` and
390
+ * `/tmp/b/TeroDB` collide on the same prefix (cross-tenant overwrite).
391
+ * We now use `pathPrefix/<safeDbName>` where `safeDbName` is derived from
392
+ * the FULL resolved path when a custom `dbName` isn't supplied.
393
+ * Explicit `cloudStorage.dbName` or `BackupConfig.bucketPrefix` takes
394
+ * precedence for callers who want stable, human-readable prefixes.
395
+ */
396
+ getDbName() {
397
+ // Allow caller to override — useful for stable bucket layouts
398
+ const override = this.config.cloudStorage?.dbName || this.config?.bucketPrefix;
399
+ if (typeof override === 'string' && override.trim()) {
400
+ return override.trim().replace(/^\/+|\/+$/g, '').replace(/[^a-zA-Z0-9_\-]/g, '_').slice(0, 128);
401
+ }
402
+ // Default: hash the full resolved path to avoid collisions, keeping basename for readability
403
+ const base = basename(this.dbPath) || 'tero';
404
+ // Use a short hash of the full path so different directories with same basename diverge
405
+ const full = this.dbPath;
406
+ let h = 0x811c9dc5;
407
+ for (let i = 0; i < full.length; i++) {
408
+ h ^= full.charCodeAt(i);
409
+ h = Math.imul(h, 0x01000193) >>> 0;
410
+ }
411
+ const suffix = h.toString(16).padStart(8, '0').slice(0, 6);
412
+ return `${base}-${suffix}`;
413
+ }
362
414
  getCloudKey(filename) {
363
415
  const prefix = this.config.cloudStorage?.pathPrefix || 'tero-backups';
364
- const dbName = basename(this.dbPath);
365
- return `${prefix}/${dbName}/${filename}`;
416
+ const dbName = this.getDbName();
417
+ // filename is already sanitized (key + ".json" or archive name); avoid double slashes
418
+ if (!filename)
419
+ return `${prefix}/${dbName}/`;
420
+ return `${prefix}/${dbName}/${filename.replace(/^\/+/, '')}`;
366
421
  }
367
422
  async performBackup() {
368
423
  try {
@@ -576,10 +631,10 @@ export class BackupManager {
576
631
  return;
577
632
  try {
578
633
  const segName = basename(archivePath);
579
- const prefix = this.config.cloudStorage.pathPrefix || 'tero-backups';
580
- const dbName = basename(this.dbPath);
581
- const cloudKey = `${prefix}/${dbName}/wal/${segName}`;
582
- await this.uploadToCloud(archivePath, cloudKey);
634
+ const cloudKey = `${this.getDbName()}/wal/${segName}`;
635
+ // getCloudKey already prefixes, but for WAL we need wal/ subprefix
636
+ const walKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${cloudKey}`;
637
+ await this.uploadToCloud(archivePath, walKey);
583
638
  uploadedWALSegments++;
584
639
  }
585
640
  catch (error) {
@@ -593,9 +648,9 @@ export class BackupManager {
593
648
  tag: options?.tag ?? 'manual',
594
649
  dataFiles: jsonFiles.map(f => f.name),
595
650
  walSegments: walPaths.map(p => basename(p)),
596
- dbPath: basename(this.dbPath),
651
+ dbPath: this.getDbName(),
597
652
  };
598
- const manifestKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${basename(this.dbPath)}/MANIFEST.json`;
653
+ const manifestKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${this.getDbName()}/MANIFEST.json`;
599
654
  await this.uploadBuffer(JSON.stringify(manifest, null, 2), manifestKey, 'application/json');
600
655
  }
601
656
  catch (error) {
@@ -634,7 +689,7 @@ export class BackupManager {
634
689
  ContentType: contentType,
635
690
  Metadata: {
636
691
  'backup-timestamp': new Date().toISOString(),
637
- 'source-db': basename(this.dbPath),
692
+ 'source-db': this.getDbName(),
638
693
  },
639
694
  });
640
695
  await this.s3Client.send(cmd);
@@ -648,6 +703,18 @@ export class BackupManager {
648
703
  /** In-flight checkpoint (shared promise: concurrent callers await the same run). */
649
704
  liveCheckpointPromise;
650
705
  lastCheckpointError;
706
+ async drainInFlight() {
707
+ if (this.liveShipper) {
708
+ this.liveShipper.stop();
709
+ this.liveShipper = undefined;
710
+ }
711
+ if (this.liveCheckpointPromise) {
712
+ try {
713
+ await this.liveCheckpointPromise;
714
+ }
715
+ catch { }
716
+ }
717
+ }
651
718
  destroy() {
652
719
  for (const [id, cronJob] of this.scheduledBackups)
653
720
  cronJob.stop();
@@ -662,14 +729,14 @@ export class BackupManager {
662
729
  }
663
730
  liveCloudPrefix(nodeId) {
664
731
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
665
- return `${base}/${basename(this.dbPath)}/nodes/${nodeId}/`;
732
+ return `${base}/${this.getDbName()}/nodes/${nodeId}/`;
666
733
  }
667
734
  async uploadBytes(key, body, contentType = 'application/octet-stream') {
668
735
  if (!this.s3Client || !this.config.cloudStorage)
669
736
  throw new Error('Cloud storage not configured');
670
737
  await this.s3Client.send(new PutObjectCommand({
671
738
  Bucket: this.config.cloudStorage.bucket, Key: key, Body: body, ContentType: contentType,
672
- Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': basename(this.dbPath) },
739
+ Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': this.getDbName() },
673
740
  }));
674
741
  }
675
742
  async downloadBytes(key) {
@@ -708,6 +775,33 @@ export class BackupManager {
708
775
  } while (token);
709
776
  return keys;
710
777
  }
778
+ async listPrefixWithMeta(prefix) {
779
+ if (!this.s3Client || !this.config.cloudStorage)
780
+ throw new Error('Cloud storage not configured');
781
+ const out = [];
782
+ let token;
783
+ do {
784
+ const resp = await this.s3Client.send(new ListObjectsV2Command({ Bucket: this.config.cloudStorage.bucket, Prefix: prefix, ContinuationToken: token }));
785
+ if (resp.Contents)
786
+ for (const o of resp.Contents)
787
+ if (o.Key)
788
+ out.push({ key: o.Key, lastModified: o.LastModified ?? new Date(0) });
789
+ token = resp.IsTruncated ? resp.NextContinuationToken : undefined;
790
+ } while (token);
791
+ return out;
792
+ }
793
+ async deleteObject(key) {
794
+ if (!this.s3Client || !this.config.cloudStorage)
795
+ throw new Error('Cloud storage not configured');
796
+ try {
797
+ await this.s3Client.send(new DeleteObjectCommand({ Bucket: this.config.cloudStorage.bucket, Key: key }));
798
+ }
799
+ catch (e) {
800
+ if (e?.name === 'NoSuchKey' || e?.Code === 'NoSuchKey' || e?.$metadata?.httpStatusCode === 404)
801
+ return;
802
+ throw e;
803
+ }
804
+ }
711
805
  enableLiveBackup(engine, opts) {
712
806
  if (opts.consistency !== 'per-second')
713
807
  throw new Error("Tero live backup only supports consistency: 'per-second' (RPO ≤ 1s). Other levels are not offered.");
@@ -736,6 +830,13 @@ export class BackupManager {
736
830
  nodeId = randomUUID().replace(/-/g, '').slice(0, 16);
737
831
  try {
738
832
  writeFileSync(idFile, nodeId, 'utf8');
833
+ const fd = openSync(idFile, 'r');
834
+ try {
835
+ fsyncSync(fd);
836
+ }
837
+ finally {
838
+ closeSync(fd);
839
+ }
739
840
  }
740
841
  catch { }
741
842
  const prefix = this.liveCloudPrefix(nodeId);
@@ -860,18 +961,26 @@ export class BackupManager {
860
961
  const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
861
962
  const dirty = engine.takeDirtyKeys();
862
963
  let uploaded = 0, tombstoned = 0;
863
- for (const key of dirty) {
964
+ const dirtyList = Array.from(dirty);
965
+ await pooledMap(dirtyList, 16, async (key) => {
864
966
  const filePath = partitionedPath(this.dbPath, key);
865
967
  const rel = posixRel(filePath);
866
968
  if (existsSync(filePath)) {
867
969
  await this.uploadBytes(`${dataPrefix}${rel}`, readFileSync(filePath), 'application/json');
868
970
  uploaded++;
971
+ // Delete stale tombstone if this key was previously deleted then recreated
972
+ // under the same baseTs. Without this, bucket holds both data and
973
+ // .deleted and the old restore filter would drop the recreated doc.
974
+ try {
975
+ await this.deleteObject(`${dataPrefix}${rel}.deleted`);
976
+ }
977
+ catch { }
869
978
  }
870
979
  else {
871
980
  await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream');
872
981
  tombstoned++;
873
982
  }
874
- }
983
+ });
875
984
  await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs: latest.baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString(), dirtyUploaded: uploaded, tombstoned }, null, 2)), 'application/json');
876
985
  await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify({ nodeId: this.liveNodeId, updatedAt: new Date().toISOString(), lastShippedLsn: this.liveShipper?.status.lastShippedLsn ?? 0, lastCheckpointAt: new Date().toISOString() }, null, 2)), 'application/json');
877
986
  this.liveCheckpoints++;
@@ -892,7 +1001,7 @@ export class BackupManager {
892
1001
  // user pathPrefix or database name containing "nodes" and restore from the
893
1002
  // wrong node (e.g. pathPrefix 'my/nodes/stuff' would capture 'stuff').
894
1003
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
895
- const nodesPrefix = `${base}/${basename(this.dbPath)}/nodes/`;
1004
+ const nodesPrefix = `${base}/${this.getDbName()}/nodes/`;
896
1005
  const all = await this.listPrefix(nodesPrefix);
897
1006
  const ids = new Set();
898
1007
  for (const k of all) {
@@ -912,23 +1021,49 @@ export class BackupManager {
912
1021
  let baseLsn = null;
913
1022
  if (latest) {
914
1023
  baseLsn = latest.baseLsn ?? null;
915
- const dataKeys = await this.listPrefix(`${prefix}checkpoint/${latest.baseTs}/data/`);
916
- const tombstoneKeyNames = new Set();
917
- const activeDataKeys = [];
918
- for (const dk of dataKeys) {
919
- if (dk.endsWith('.deleted')) {
920
- const keyName = basename(dk).replace(/\.json\.deleted$/, '');
921
- tombstoneKeyNames.add(keyName);
1024
+ const dataWithMeta = await this.listPrefixWithMeta(`${prefix}checkpoint/${latest.baseTs}/data/`);
1025
+ const tombstoneMeta = new Map();
1026
+ const activeMeta = new Map();
1027
+ for (const { key, lastModified } of dataWithMeta) {
1028
+ if (key.endsWith('.deleted')) {
1029
+ const keyName = basename(key).replace(/\.json\.deleted$/, '');
1030
+ const prev = tombstoneMeta.get(keyName);
1031
+ if (!prev || lastModified > prev)
1032
+ tombstoneMeta.set(keyName, lastModified);
922
1033
  }
923
- else if (dk.endsWith('.json')) {
924
- activeDataKeys.push(dk);
1034
+ else if (key.endsWith('.json')) {
1035
+ const keyName = basename(key).replace(/\.json$/, '');
1036
+ const prev = activeMeta.get(keyName);
1037
+ if (!prev || lastModified > prev.lastModified)
1038
+ activeMeta.set(keyName, { key, lastModified });
925
1039
  }
926
1040
  }
927
- // Filter out any active key that has a tombstone so it is never downloaded or resurrected
928
- const keysToDownload = activeDataKeys.filter(dk => {
929
- const keyName = basename(dk).replace(/\.json$/, '');
930
- return !tombstoneKeyNames.has(keyName);
931
- });
1041
+ // Resolve tombstone vs data by recency: newer wins. This handles
1042
+ // delete→recreate under same baseTs (data newer) vs legit delete
1043
+ // (tombstone newer than the full-checkpoint data), and also heals
1044
+ // legacy buckets that contain both due to the pre-fix bug.
1045
+ const keysToDownload = [];
1046
+ const finalTombstones = new Set();
1047
+ for (const [keyName, active] of activeMeta) {
1048
+ const tombTime = tombstoneMeta.get(keyName);
1049
+ if (tombTime) {
1050
+ if (active.lastModified > tombTime) {
1051
+ keysToDownload.push(active.key);
1052
+ }
1053
+ else {
1054
+ finalTombstones.add(keyName);
1055
+ }
1056
+ }
1057
+ else {
1058
+ keysToDownload.push(active.key);
1059
+ }
1060
+ }
1061
+ for (const [keyName] of tombstoneMeta) {
1062
+ if (!activeMeta.has(keyName))
1063
+ finalTombstones.add(keyName);
1064
+ }
1065
+ // Keep compat names for later local-delete loop
1066
+ const tombstoneKeyNames = finalTombstones;
932
1067
  // Pool downloads — sequential GETs make a 50k-doc restore take ~12 minutes.
933
1068
  await pooledMap(keysToDownload, 16, async (dk) => {
934
1069
  const key = basename(dk).replace(/\.json$/, '');
package/dist/index.d.ts CHANGED
@@ -65,16 +65,32 @@ export declare class Transaction {
65
65
  * including deletes. One array push per op: O(1), off the engine hot path. */
66
66
  private operationsLog;
67
67
  private destroyed;
68
+ private committed;
69
+ private rolledBack;
68
70
  private timeoutTimer?;
69
71
  constructor(id: string, db: Tero, options?: TransactionOptions);
70
72
  getId(): string;
71
73
  isActive(): boolean;
72
74
  isRolledBack(): boolean;
75
+ isCommitted(): boolean;
73
76
  private _checkActive;
74
77
  create(key: string, initialData?: any): Promise<void>;
75
78
  update(key: string, data: any): Promise<void>;
76
79
  delete(key: string): Promise<void>;
77
- get(key: string): Promise<any>;
80
+ /**
81
+ * Read document within this transaction.
82
+ * @param options.lock - 'shared' (default) or 'exclusive' (SELECT FOR UPDATE)
83
+ */
84
+ get(key: string, options?: {
85
+ lock?: 'shared' | 'exclusive';
86
+ }): Promise<any>;
87
+ /**
88
+ * Alias for get() with explicit locking semantics.
89
+ * @param options.lock - 'shared' (default) or 'exclusive' (SELECT FOR UPDATE)
90
+ */
91
+ read(key: string, options?: {
92
+ lock?: 'shared' | 'exclusive';
93
+ }): Promise<any>;
78
94
  getState(): {
79
95
  status: string;
80
96
  operations: Array<{
@@ -84,7 +100,9 @@ export declare class Transaction {
84
100
  startTime: number;
85
101
  };
86
102
  getOperationCount(): number;
87
- getDuration(): number;
103
+ commit(): Promise<void>;
104
+ abort(): Promise<void>;
105
+ rollback(): Promise<void>;
88
106
  destroy(): void;
89
107
  }
90
108
  export declare class Tero {
@@ -135,6 +153,7 @@ export declare class Tero {
135
153
  timeout?: number;
136
154
  }): Promise<RecoveryResult>;
137
155
  private initializeDirectories;
156
+ private static readonly MAX_KEY_LENGTH;
138
157
  private validateKey;
139
158
  /**
140
159
  * Tracks which keys each active transaction has touched (cache entries tagged
@@ -152,7 +171,9 @@ export declare class Tero {
152
171
  schemaName?: string;
153
172
  strict?: boolean;
154
173
  }): Promise<ValidationResult | void>;
155
- read(transactionId: string | Transaction, key: string): Promise<any>;
174
+ read(transactionId: string | Transaction, key: string, options?: {
175
+ lock?: 'shared' | 'exclusive';
176
+ }): Promise<any>;
156
177
  commit(transactionId: string | Transaction): Promise<void>;
157
178
  rollback(transactionId: string | Transaction): Promise<void>;
158
179
  commitTransaction(transactionId: string | Transaction): Promise<void>;
@@ -174,8 +195,10 @@ export declare class Tero {
174
195
  strict?: boolean;
175
196
  }): Promise<ValidationResult | void>;
176
197
  /**
177
- * Read a document. Returns the document data on success, or `false` if the
178
- * document is absent. Throws for genuine errors.
198
+ * Read a document. Returns the document data on success, or `null` if the
199
+ * document is absent (use `=== null` to check). For backwards-compat, `false`
200
+ * is still treated as "not found" by callers, but new code should check for null.
201
+ * Throws for genuine errors (invalid key, corrupt file).
179
202
  *
180
203
  * Fast path (3 tiers, zero-syscall on hit):
181
204
  * 1. LRU cache (committed entries) — pure memory, 900k+ ops/s
@@ -185,7 +208,7 @@ export declare class Tero {
185
208
  *
186
209
  * NO transaction is created, NO WAL I/O, NO lock acquired.
187
210
  */
188
- get(key: string): Promise<any>;
211
+ get(key: string): Promise<any | null>;
189
212
  /**
190
213
  * Map a document key to its partitioned path on disk (2-level hash-prefix).
191
214
  * Delegates to the ENGINE'S partitionedPath() — the single authoritative
@@ -328,9 +351,9 @@ export declare class Tero {
328
351
  recoverFromArchive(archiveName?: string): Promise<RecoveryResult>;
329
352
  /**
330
353
  * Read a key locally; if absent locally, transparently recover it from the client's
331
- * bucket and cache the result. Returns the data, or `false` if the key genuinely
332
- * doesn't exist on either side. Throws for real (auth/network) errors so callers
333
- * don't silently mistake them for "not in cloud".
354
+ * bucket and cache the result. Returns the data, or `null` if the key genuinely
355
+ * doesn't exist on either side (returns `false` for backwards compat — both mean "not found").
356
+ * Throws for real (auth/network) errors so callers don't silently mistake them for "not in cloud".
334
357
  *
335
358
  * Options:
336
359
  * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
@@ -339,7 +362,7 @@ export declare class Tero {
339
362
  getWithRecovery(key: string, options?: {
340
363
  fallbackToCloud?: boolean;
341
364
  mode?: 'missing' | 'all';
342
- }): Promise<any>;
365
+ }): Promise<any | null>;
343
366
  /**
344
367
  * Probe local + cloud availability for a key without modifying local state.
345
368
  * Returns { local, cloud, canRecover }:
@@ -375,6 +398,8 @@ export declare class Tero {
375
398
  */
376
399
  private acquireFileLock;
377
400
  private releaseFileLock;
401
+ destroyAsync(): Promise<void>;
402
+ close(): Promise<void>;
378
403
  destroy(): void;
379
404
  /**
380
405
  * Generates a unique identifier with a custom prefix.