tero 0.0.6 → 0.0.7

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.d.ts CHANGED
@@ -25,6 +25,13 @@ export interface BackupMetadata {
25
25
  checksum: string;
26
26
  retention: string;
27
27
  }
28
+ export interface BucketBackupResult {
29
+ success: boolean;
30
+ uploadedDataFiles: number;
31
+ uploadedWALSegments: number;
32
+ duration: number;
33
+ errors: string[];
34
+ }
28
35
  export declare class BackupManager {
29
36
  private s3Client?;
30
37
  private scheduledBackups;
@@ -36,6 +43,14 @@ export declare class BackupManager {
36
43
  private parseRetention;
37
44
  private intervalToCron;
38
45
  private calculateChecksum;
46
+ /**
47
+ * Enumerate *.json files across the 2-level hash-prefix partition tree using
48
+ * async fs.opendir iteration. Replaces the previous readdirSync() flat scan
49
+ * that allocated a giant array of all filenames in one tick — at 1M keys the
50
+ * old call alone consumed ~80MB and froze the event loop for seconds.
51
+ *
52
+ * Streaming walks each leaf directory one entry at a time.
53
+ */
39
54
  private getJsonFiles;
40
55
  private createArchiveBackup;
41
56
  private createIndividualBackup;
@@ -62,5 +77,21 @@ export declare class BackupManager {
62
77
  success: boolean;
63
78
  message: string;
64
79
  }>;
80
+ /**
81
+ * v2: One-shot bucket backup of all data JSON files + any WAL archive segments
82
+ * the caller passes in. Designed for scheduled "snapshot to bucket" runs that a
83
+ * client triggers with its OWN bucket credentials — the control plane never holds
84
+ * the client's cloud keys, it only observes results via heartbeats.
85
+ *
86
+ * Returns a structured result with per-stream counts and surfaced errors.
87
+ */
88
+ backupToBucket(options?: {
89
+ walArchivePaths?: string[];
90
+ tag?: string;
91
+ }): Promise<BucketBackupResult>;
92
+ /**
93
+ * Upload an arbitrary buffer (used for the bucket manifest and small artifacts).
94
+ */
95
+ private uploadBuffer;
65
96
  destroy(): void;
66
97
  }
package/dist/backup.js CHANGED
@@ -1,7 +1,7 @@
1
- import { createReadStream, existsSync, readdirSync, statSync } from "fs";
1
+ import { createReadStream, existsSync, statSync } from "fs";
2
2
  import { join, basename } from "path";
3
3
  import tar from "tar";
4
- import { S3Client, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
4
+ import { S3Client, PutObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
5
5
  import { Upload } from "@aws-sdk/lib-storage";
6
6
  import { CronJob } from "cron";
7
7
  export class BackupManager {
@@ -105,22 +105,35 @@ export class BackupManager {
105
105
  stream.on('error', reject);
106
106
  });
107
107
  }
108
+ /**
109
+ * Enumerate *.json files across the 2-level hash-prefix partition tree using
110
+ * async fs.opendir iteration. Replaces the previous readdirSync() flat scan
111
+ * that allocated a giant array of all filenames in one tick — at 1M keys the
112
+ * old call alone consumed ~80MB and froze the event loop for seconds.
113
+ *
114
+ * Streaming walks each leaf directory one entry at a time.
115
+ */
108
116
  async getJsonFiles() {
109
117
  try {
110
118
  if (!existsSync(this.dbPath)) {
111
119
  return [];
112
120
  }
113
- const files = readdirSync(this.dbPath)
114
- .filter(file => file.endsWith('.json'))
115
- .map(file => {
116
- const filePath = join(this.dbPath, file);
117
- const stats = statSync(filePath);
118
- return {
119
- path: filePath,
120
- name: file,
121
- size: stats.size,
122
- mtime: stats.mtime
123
- };
121
+ const { walkPartitions } = await import('./acid-engine.js');
122
+ const { basename } = await import('path');
123
+ const files = [];
124
+ await walkPartitions(this.dbPath, async (filePath) => {
125
+ try {
126
+ const stats = statSync(filePath);
127
+ files.push({
128
+ path: filePath,
129
+ name: basename(filePath),
130
+ size: stats.size,
131
+ mtime: stats.mtime
132
+ });
133
+ }
134
+ catch {
135
+ // file may be removed mid-walk — skip
136
+ }
124
137
  });
125
138
  return files;
126
139
  }
@@ -144,13 +157,16 @@ export class BackupManager {
144
157
  const fs = await import('fs/promises');
145
158
  await fs.mkdir(this.config.localPath, { recursive: true });
146
159
  }
147
- // Create tar.gz archive
160
+ // Create tar.gz archive — pass relative paths from dbPath so the
161
+ // 2-level hash-prefix partition dirs are preserved in the archive.
162
+ // (was: jsonFiles.map(f => f.name) — broke when files moved to XX/YY/key.json)
163
+ const fileList = jsonFiles.map(f => f.path.slice(this.dbPath.length + 1));
148
164
  await tar.create({
149
165
  file: backupPath,
150
166
  cwd: this.dbPath,
151
167
  gzip: true,
152
168
  prefix: 'tero-data/'
153
- }, jsonFiles.map(f => f.name));
169
+ }, fileList);
154
170
  const stats = statSync(backupPath);
155
171
  const checksum = await this.calculateChecksum(backupPath);
156
172
  const metadata = {
@@ -453,6 +469,112 @@ export class BackupManager {
453
469
  };
454
470
  }
455
471
  }
472
+ /**
473
+ * v2: One-shot bucket backup of all data JSON files + any WAL archive segments
474
+ * the caller passes in. Designed for scheduled "snapshot to bucket" runs that a
475
+ * client triggers with its OWN bucket credentials — the control plane never holds
476
+ * the client's cloud keys, it only observes results via heartbeats.
477
+ *
478
+ * Returns a structured result with per-stream counts and surfaced errors.
479
+ */
480
+ async backupToBucket(options) {
481
+ const startTime = Date.now();
482
+ const errors = [];
483
+ let uploadedDataFiles = 0;
484
+ let uploadedWALSegments = 0;
485
+ if (!this.s3Client || !this.config.cloudStorage) {
486
+ errors.push('Cloud storage not configured');
487
+ return {
488
+ success: false,
489
+ uploadedDataFiles: 0,
490
+ uploadedWALSegments: 0,
491
+ duration: Date.now() - startTime,
492
+ errors,
493
+ };
494
+ }
495
+ try {
496
+ // 1) Snapshot all data JSON files to bucket.
497
+ const jsonFiles = await this.getJsonFiles();
498
+ for (const file of jsonFiles) {
499
+ try {
500
+ const cloudKey = this.getCloudKey(file.name);
501
+ await this.uploadToCloud(file.path, cloudKey);
502
+ uploadedDataFiles++;
503
+ }
504
+ catch (error) {
505
+ errors.push(`data:${file.name}:${error instanceof Error ? error.message : 'Unknown error'}`);
506
+ }
507
+ }
508
+ // 2) Stream WAL archive segments the caller wants persisted.
509
+ const walPaths = options?.walArchivePaths ?? [];
510
+ for (const archivePath of walPaths) {
511
+ if (!existsSync(archivePath))
512
+ continue;
513
+ try {
514
+ const segName = basename(archivePath);
515
+ const prefix = this.config.cloudStorage.pathPrefix || 'tero-backups';
516
+ const dbName = basename(this.dbPath);
517
+ const cloudKey = `${prefix}/${dbName}/wal/${segName}`;
518
+ await this.uploadToCloud(archivePath, cloudKey);
519
+ uploadedWALSegments++;
520
+ }
521
+ catch (error) {
522
+ errors.push(`wal:${basename(archivePath)}:${error instanceof Error ? error.message : 'Unknown error'}`);
523
+ }
524
+ }
525
+ // 3) Emit a backup manifest so hydrate-on-startup can discover the latest snapshot.
526
+ try {
527
+ const manifest = {
528
+ timestamp: new Date().toISOString(),
529
+ tag: options?.tag ?? 'manual',
530
+ dataFiles: jsonFiles.map(f => f.name),
531
+ walSegments: walPaths.map(p => basename(p)),
532
+ dbPath: basename(this.dbPath),
533
+ };
534
+ const manifestKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${basename(this.dbPath)}/MANIFEST.json`;
535
+ await this.uploadBuffer(JSON.stringify(manifest, null, 2), manifestKey, 'application/json');
536
+ }
537
+ catch (error) {
538
+ errors.push(`manifest:${error instanceof Error ? error.message : 'Unknown error'}`);
539
+ }
540
+ return {
541
+ success: errors.length === 0,
542
+ uploadedDataFiles,
543
+ uploadedWALSegments,
544
+ duration: Date.now() - startTime,
545
+ errors,
546
+ };
547
+ }
548
+ catch (error) {
549
+ errors.push(error instanceof Error ? error.message : 'Unknown error');
550
+ return {
551
+ success: false,
552
+ uploadedDataFiles,
553
+ uploadedWALSegments,
554
+ duration: Date.now() - startTime,
555
+ errors,
556
+ };
557
+ }
558
+ }
559
+ /**
560
+ * Upload an arbitrary buffer (used for the bucket manifest and small artifacts).
561
+ */
562
+ async uploadBuffer(content, cloudKey, contentType) {
563
+ if (!this.s3Client || !this.config.cloudStorage) {
564
+ throw new Error('Cloud storage not configured');
565
+ }
566
+ const cmd = new PutObjectCommand({
567
+ Bucket: this.config.cloudStorage.bucket,
568
+ Key: cloudKey,
569
+ Body: content,
570
+ ContentType: contentType,
571
+ Metadata: {
572
+ 'backup-timestamp': new Date().toISOString(),
573
+ 'source-db': basename(this.dbPath),
574
+ },
575
+ });
576
+ await this.s3Client.send(cmd);
577
+ }
456
578
  destroy() {
457
579
  // Cancel all scheduled backups
458
580
  for (const [id, cronJob] of this.scheduledBackups) {
package/dist/index.d.ts CHANGED
@@ -1,9 +1,47 @@
1
+ import { SynchronousMode } from "./acid-engine.js";
1
2
  import { DocumentSchema, ValidationResult } from "./schema.js";
2
- import { BackupConfig, BackupMetadata } from "./backup.js";
3
+ import { BackupConfig, BackupMetadata, CloudStorageConfig, BucketBackupResult } from "./backup.js";
3
4
  import { RecoveryConfig, RecoveryResult, FileRecoveryInfo } from "./recovery.js";
4
5
  interface TeroConfig {
5
6
  directory?: string;
6
7
  cacheSize?: number;
8
+ /**
9
+ * Durability / throughput trade-off knob (like SQLite's `PRAGMA synchronous`):
10
+ * - 'full' (default): fsync the WAL on every commit. Max durability, ~15–60 ops/s
11
+ * depending on disk. Use when every commit must survive power loss.
12
+ * - 'normal': fsync the WAL on a coalescing timer (commitIntervalMs, default 10ms).
13
+ * 10–100x throughput; up to commitIntervalMs of committed transactions may be lost
14
+ * on power failure. Use for edge workloads where a small RPO is acceptable.
15
+ * - 'off': never fsync. Testing/benchmark only. Data loss on crash is certain.
16
+ */
17
+ synchronous?: SynchronousMode;
18
+ /** Group-commit interval in milliseconds (only used when synchronous='normal'). Default: 10. */
19
+ commitIntervalMs?: number;
20
+ /** Data-file flush interval in ms (how often committedBuffer is checkpointed to disk). Default: 50. */
21
+ dataFlushIntervalMs?: number;
22
+ /** v2: hydrate local state from a bucket on startup before the ACID engine comes up. */
23
+ hydrateOnStartup?: HydrateConfig;
24
+ /** v2: a default backup config installed at construction time (use configureBackup() at runtime too). */
25
+ backup?: BackupConfig;
26
+ /**
27
+ * Acquire an exclusive OS-level file lock (flock) on the data directory to
28
+ * prevent concurrent process access. Two Node.js processes opening the same
29
+ * directory without this flag will corrupt each other's data. Set to true
30
+ * in production; default false for backwards compatibility.
31
+ */
32
+ fileLock?: boolean;
33
+ }
34
+ interface HydrateConfig {
35
+ cloudStorage: CloudStorageConfig;
36
+ /** 'all' overwrites local files from the bucket; 'missing' (default) only pulls files absent
37
+ * locally; 'snapshot' downloads the most recent tar.gz archive first then falls back
38
+ * to individual files. Snapshot mode is the Google-recommended approach — one bulk
39
+ * download vs thousands of individual S3 GETs. */
40
+ mode?: 'all' | 'missing' | 'snapshot';
41
+ /** Continue when a single file fails to download (default true). */
42
+ continueOnError?: boolean;
43
+ /** Maximum time to wait for hydration before attempting engine init (ms). */
44
+ timeout?: number;
7
45
  }
8
46
  interface TransactionOptions {
9
47
  timeout?: number;
@@ -54,9 +92,49 @@ export declare class Tero {
54
92
  private dataRecovery?;
55
93
  private committedCount;
56
94
  private rolledBackCount;
95
+ /**
96
+ * Bounded LRU of known-existing keys. Replaces the unbounded Set<string>
97
+ * that grew linearly with key count (catastrophic memory at 1M+ keys/tenant).
98
+ * Capped at KNOWN_KEYS_MAX (10k) ~ 800KB peak vs ~80MB at 1M keys for Set.
99
+ * Falls back to disk (partitioned path existsSync) on LRU miss.
100
+ */
101
+ private knownKeys;
102
+ private readonly KNOWN_KEYS_MAX;
103
+ /** Optional exclusive file-lock fd on the data directory (flock, via fs-ext). */
104
+ private lockFd?;
105
+ /**
106
+ * Construct an embedded Tero instance synchronously.
107
+ *
108
+ * For v2 startup hydration from a bucket, prefer `await Tero.create(config)` which
109
+ * pulls missing/all files from the client's OWN bucket before the ACID engine is
110
+ * initialized. The control plane never holds client bucket credentials; it only
111
+ * observes instances. Pass `hydrateOnStartup` in config to use this path.
112
+ */
57
113
  constructor(config?: TeroConfig);
114
+ /**
115
+ * v2 async factory. Same as `new Tero(config)` but runs hydrate-on-startup BEFORE
116
+ * the ACID engine is constructed. Use this when `config.hydrateOnStartup` is set
117
+ * so missing/all local files are restored from the client's bucket first.
118
+ */
119
+ static create(config?: TeroConfig): Promise<Tero>;
120
+ /**
121
+ * v2: explicitly run hydration at any time (idempotent). Pulls missing/all files
122
+ * from the client's bucket according to the config passed. Requires either
123
+ * `configureDataRecovery(...)` to have been called, or `hydrateOnStartup` in
124
+ * the constructor config.
125
+ */
126
+ hydrate(options?: {
127
+ mode?: 'all' | 'missing' | 'snapshot';
128
+ timeout?: number;
129
+ }): Promise<RecoveryResult>;
58
130
  private initializeDirectories;
59
131
  private validateKey;
132
+ /**
133
+ * Tracks which keys each active transaction has touched (cache entries tagged
134
+ * with that txId). Used by commit()/rollback() to promote/invalidate only the
135
+ * touched keys instead of scanning the entire LRU cache. O(touched) vs O(cacheSize).
136
+ */
137
+ private txTouchedKeys;
60
138
  private invalidateCacheKeys;
61
139
  private updateCache;
62
140
  beginTransaction(options?: TransactionOptions): Transaction;
@@ -88,7 +166,24 @@ export declare class Tero {
88
166
  schemaName?: string;
89
167
  strict?: boolean;
90
168
  }): Promise<ValidationResult | void>;
169
+ /**
170
+ * Read a document. Returns the document data on success, or `false` if the
171
+ * document is absent. Throws for genuine errors.
172
+ *
173
+ * Fast path (3 tiers, zero-syscall on hit):
174
+ * 1. LRU cache (committed entries) — pure memory, 900k+ ops/s
175
+ * 2. committedBuffer (committed but not yet flushed to disk) — pure memory
176
+ * 3. Read from data file via 2-level hash-prefix partitioned path (atomic
177
+ * rename guarantees valid JSON; no single dentry holds >50k files)
178
+ *
179
+ * NO transaction is created, NO WAL I/O, NO lock acquired.
180
+ */
91
181
  get(key: string): Promise<any>;
182
+ /**
183
+ * Map a document key to its partitioned path on disk (2-level hash-prefix).
184
+ * Matches the layout used by ACIDStorageEngine — same key resolves to same path.
185
+ */
186
+ private keyToPath;
92
187
  remove(key: string): Promise<void>;
93
188
  delete(key: string): Promise<void>;
94
189
  exists(key: string): boolean;
@@ -133,14 +228,97 @@ export declare class Tero {
133
228
  strict?: boolean;
134
229
  }): Promise<ValidationResult>;
135
230
  configureBackup(config: BackupConfig): void;
231
+ /** Alias retained for the existing test surface / older callers. */
232
+ configureAdvancedBackup(config: BackupConfig): void;
136
233
  performBackup(): Promise<{
137
234
  success: boolean;
138
235
  metadata: BackupMetadata;
139
236
  cloudUploaded?: boolean;
140
237
  }>;
238
+ /** Alias retained for the existing test surface / older callers. */
239
+ performAdvancedBackup(): Promise<{
240
+ success: boolean;
241
+ metadata: BackupMetadata;
242
+ cloudUploaded?: boolean;
243
+ }>;
244
+ /** Schedule a recurring backup via cron. Returns a schedule id; cancel with cancelScheduledBackup(). */
245
+ scheduleBackup(config: {
246
+ interval: string;
247
+ retention?: string;
248
+ }): string;
249
+ /** Cancel a previously scheduled backup by id. */
250
+ cancelScheduledBackup(scheduleId: string): boolean;
251
+ /** List currently scheduled backups. */
252
+ getScheduledBackups(): Array<{
253
+ id: string;
254
+ active: boolean;
255
+ }>;
256
+ /** Test reachability of the configured bucket. Returns {success, message}. */
257
+ testCloudConnection(): Promise<{
258
+ success: boolean;
259
+ message: string;
260
+ }>;
261
+ /**
262
+ * v2: One-shot bucket backup of all current data JSON files plus any WAL archive
263
+ * segments retained locally. Designed for scheduled "snapshot to bucket" runs the
264
+ * CLIENT triggers with its OWN bucket credentials — the control plane never holds
265
+ * client cloud keys, it only observes results via heartbeats.
266
+ */
267
+ backupToBucket(options?: {
268
+ tag?: string;
269
+ }): Promise<BucketBackupResult>;
270
+ /**
271
+ * v2: Emit a WAL checkpoint + immediately rotate the WAL into a new archive segment,
272
+ * then back that fresh segment up to the bucket. Useful right after high-write bursts
273
+ * to bound the recovery window (RPO) when hydrating a new instance.
274
+ */
275
+ checkpointAndBackupToBucket(options?: {
276
+ tag?: string;
277
+ }): Promise<BucketBackupResult>;
141
278
  configureDataRecovery(config: RecoveryConfig): void;
142
279
  recoverFromCloud(key: string): Promise<boolean>;
143
280
  recoverAllFromCloud(): Promise<RecoveryResult>;
281
+ /** Recovery info: how many cloud files exist, which are missing locally, which can be pulled. */
282
+ getRecoveryInfo(): Promise<{
283
+ cloudFiles: number;
284
+ localFiles: number;
285
+ missingLocally: string[];
286
+ availableForRecovery: string[];
287
+ }>;
288
+ /** List available backup/archived files in the client bucket. */
289
+ listAvailableFiles(): Promise<string[]>;
290
+ /** List available tar.gz archive backups in the client bucket. */
291
+ listAvailableArchives(): Promise<string[]>;
292
+ /** Check (HEAD) whether a single key exists in the client bucket. */
293
+ checkFileInCloud(key: string): Promise<FileRecoveryInfo>;
294
+ /** Recover an entire archive backup (tar.gz) from the client bucket and extract locally. */
295
+ recoverFromArchive(archiveName?: string): Promise<RecoveryResult>;
296
+ /**
297
+ * Read a key locally; if absent locally, transparently recover it from the client's
298
+ * bucket and cache the result. Returns the data, or `false` if the key genuinely
299
+ * doesn't exist on either side. Throws for real (auth/network) errors so callers
300
+ * don't silently mistake them for "not in cloud".
301
+ *
302
+ * Options:
303
+ * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
304
+ * - mode: 'missing' (default) — only fetch if missing locally; 'all' — always overwrite from cloud
305
+ */
306
+ getWithRecovery(key: string, options?: {
307
+ fallbackToCloud?: boolean;
308
+ mode?: 'missing' | 'all';
309
+ }): Promise<any>;
310
+ /**
311
+ * Probe local + cloud availability for a key without modifying local state.
312
+ * Returns { local, cloud, canRecover }:
313
+ * - local: true if the file exists locally
314
+ * - cloud: true if the file exists in the client bucket (HEAD)
315
+ * - canRecover: true if cloud has it but local doesn't
316
+ */
317
+ existsWithCloudCheck(key: string): Promise<{
318
+ local: boolean;
319
+ cloud: boolean;
320
+ canRecover: boolean;
321
+ }>;
144
322
  getCacheStats(): {
145
323
  size: number;
146
324
  maxSize: number;
@@ -155,6 +333,15 @@ export declare class Tero {
155
333
  healthy: boolean;
156
334
  }>;
157
335
  clearCache(): void;
336
+ /**
337
+ * Acquire an exclusive OS-level lock on the data directory via a .lock file.
338
+ * Uses `openSync(path, 'wx')` — creates the file exclusively, failing if it
339
+ * already exists (i.e., another process holds the lock). Cross-platform,
340
+ * no native modules required. The fd is held open to maintain the lock;
341
+ * destroying the Tero instance closes the fd and deletes the lock file.
342
+ */
343
+ private acquireFileLock;
344
+ private releaseFileLock;
158
345
  destroy(): void;
159
346
  /**
160
347
  * Generates a unique identifier with a custom prefix.
@@ -185,4 +372,4 @@ export declare class Tero {
185
372
  */
186
373
  getNewId(prefix: string): string;
187
374
  }
188
- export { DocumentSchema, ValidationResult, BackupConfig, BackupMetadata, RecoveryConfig, RecoveryResult, FileRecoveryInfo };
375
+ export { DocumentSchema, ValidationResult, BackupConfig, BackupMetadata, BucketBackupResult, CloudStorageConfig, RecoveryConfig, RecoveryResult, FileRecoveryInfo, HydrateConfig };