tero 0.0.13 → 0.1.2

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/index.d.ts CHANGED
@@ -1,10 +1,21 @@
1
- import { SynchronousMode } from "./acid-engine.js";
2
- import { DocumentSchema, ValidationResult } from "./schema.js";
1
+ import { SynchronousMode, RecoveryCorruptionError, DataCorruptionError } from "./acid-engine.js";
3
2
  import { BackupConfig, BackupMetadata, CloudStorageConfig, BucketBackupResult, LiveBackupOptions, LiveBackupStatus, LiveCheckpointResult, RestoreLiveResult, BackupLogger } from "./backup.js";
4
3
  import { RecoveryConfig, RecoveryResult, FileRecoveryInfo } from "./recovery.js";
5
4
  interface TeroConfig {
6
5
  directory?: string;
7
6
  cacheSize?: number;
7
+ /** Max committedBuffer entries flushed to disk per tick (prevents event loop stalls). Default: 1000. */
8
+ checkpointBatchSize?: number;
9
+ /**
10
+ * Rotated WAL segments retained locally (1MB each). Default: 20.
11
+ *
12
+ * Retention is a *recovery window*, not a cache: every segment is a slice of
13
+ * history that a point-in-time restore can replay. With live backup enabled
14
+ * this only sets the floor — a segment that has not been shipped to the bucket
15
+ * is never pruned at all (up to the protect byte budget), so a bucket outage
16
+ * cannot turn a rotation into data loss.
17
+ */
18
+ archiveKeepCount?: number;
8
19
  /**
9
20
  * Durability / throughput trade-off knob (like SQLite's `PRAGMA synchronous`):
10
21
  * - 'full' (default): fsync the WAL on every commit. Max durability, ~15–60 ops/s
@@ -34,17 +45,22 @@ interface TeroConfig {
34
45
  */
35
46
  fileLock?: boolean;
36
47
  }
48
+ type HydrationMode = 'lazy' | 'eager';
37
49
  interface HydrateConfig {
38
50
  cloudStorage: CloudStorageConfig;
39
- /** 'all' overwrites local files from the bucket; 'missing' (default) only pulls files absent
40
- * locally; 'snapshot' downloads the most recent tar.gz archive first then falls back
41
- * to individual files. Snapshot mode is the Google-recommended approach — one bulk
42
- * download vs thousands of individual S3 GETs. */
43
- mode?: 'all' | 'missing' | 'snapshot';
44
- /** Continue when a single file fails to download (default true). */
51
+ /**
52
+ * Hydration mode:
53
+ * - 'lazy' (default): downloads 0 files on startup for instant boot.
54
+ * Files are hydrated gradually on-demand as they are requested.
55
+ * - 'eager': bulk downloads missing files from the bucket before engine init.
56
+ */
57
+ mode?: HydrationMode;
58
+ /** Continue when a single file fails to download in eager mode (default true). */
45
59
  continueOnError?: boolean;
46
- /** Maximum time to wait for hydration before attempting engine init (ms). */
60
+ /** Maximum time to wait for hydration in eager mode before engine init (ms). */
47
61
  timeout?: number;
62
+ /** Optional custom S3 client for mocking/testing */
63
+ customS3Client?: any;
48
64
  }
49
65
  interface TransactionOptions {
50
66
  timeout?: number;
@@ -68,11 +84,16 @@ export declare class Transaction {
68
84
  private committed;
69
85
  private rolledBack;
70
86
  private timeoutTimer?;
87
+ private txState;
88
+ private abortError;
71
89
  constructor(id: string, db: Tero, options?: TransactionOptions);
72
90
  getId(): string;
73
91
  isActive(): boolean;
74
92
  isRolledBack(): boolean;
75
93
  isCommitted(): boolean;
94
+ /** Whether transaction is in ABORTING state (timeout fired, rollback in flight) */
95
+ isAborting(): boolean;
96
+ getAbortError(): Error | null;
76
97
  private _checkActive;
77
98
  create(key: string, initialData?: any): Promise<void>;
78
99
  update(key: string, data: any): Promise<void>;
@@ -112,11 +133,54 @@ export declare class Tero {
112
133
  private cacheHits;
113
134
  private cacheRequests;
114
135
  private acidEngine;
115
- private schemaValidator;
116
136
  private backupManager?;
117
137
  private dataRecovery?;
138
+ private hydrateMode;
139
+ private inFlightHydrations;
140
+ private missingKeys;
141
+ private readonly MISSING_KEYS_MAX;
118
142
  private committedCount;
119
143
  private rolledBackCount;
144
+ /** Monotonic per-key generation for in-flight hydration invalidation (P0-1). */
145
+ private keyGenerations;
146
+ /** Durable cloud reconciliation for deletes (P0-2) — keys needing cloud delete+tombstone, with deletion LSN */
147
+ private cloudPendingTombstones;
148
+ private cloudPendingTombstoneDeletions;
149
+ /**
150
+ * Durable pending local-tombstone-removal retries (P1). When a committed
151
+ * recreate/write cannot unlink the old local tombstone (EBUSY, EPERM, …),
152
+ * the key is queued here — NOT in cloudPendingTombstoneDeletions. The retry
153
+ * worker first retries the local unlink+fsync, and only once that succeeds
154
+ * does it proceed to the cloud tombstone deletion.
155
+ *
156
+ * Previously the code queued a cloud tombstone deletion, but the
157
+ * cloud-deletion retry worker explicitly refuses to process entries while a
158
+ * local tombstone still exists (hasLocal guard) — so the queue was
159
+ * self-cancelling in exactly the failure state it was created to recover,
160
+ * leaving an undeletable local tombstone forever and preventing the cloud
161
+ * tombstone from ever being deleted.
162
+ */
163
+ private pendingLocalTombstoneRemovals;
164
+ private cloudPendingTimer?;
165
+ private reconciliationLocks;
166
+ private reconciliationLockStorage;
167
+ /**
168
+ * Re-entrancy guard for the durable pending-queue journal (P1).
169
+ *
170
+ * `savePendingCloud()` / `savePendingCloudDeletions()` are fully
171
+ * synchronous, and Node's single-threaded execution guarantees that two
172
+ * calls can never interleave at the syscall level — each
173
+ * write/fsync/rename sequence runs atomically w.r.t. the JS thread, which
174
+ * is what prevents lost queue entries and temp-file collisions across
175
+ * concurrently-reconciling keys (reconciliation is only locked *per key*,
176
+ * so different keys reconcile in parallel).
177
+ *
178
+ * This flag makes that invariant explicit and defensively aborts if a
179
+ * future change introduces an `await` (or an async refactor) inside the
180
+ * persistence path, which would break the per-call atomicity the durable
181
+ * reconciliation queue depends on.
182
+ */
183
+ private pendingPersistenceInFlight;
120
184
  /**
121
185
  * Bounded LRU of known-existing keys. Replaces the unbounded Set<string>
122
186
  * that grew linearly with key count (catastrophic memory at 1M+ keys/tenant).
@@ -137,24 +201,38 @@ export declare class Tero {
137
201
  */
138
202
  constructor(config?: TeroConfig);
139
203
  /**
140
- * v2 async factory. Same as `new Tero(config)` but runs hydrate-on-startup BEFORE
141
- * the ACID engine is constructed. Use this when `config.hydrateOnStartup` is set
142
- * so missing/all local files are restored from the client's bucket first.
204
+ * v2 async factory.
205
+ * - mode: 'lazy' (default) -> Instant startup, downloads 0 files on boot.
206
+ * Files hydrate gradually on-demand as they are requested.
207
+ * - mode: 'eager' -> Bulk downloads files from cloud bucket before engine init.
143
208
  */
144
209
  static create(config?: TeroConfig): Promise<Tero>;
145
210
  /**
146
- * v2: explicitly run hydration at any time (idempotent). Pulls missing/all files
147
- * from the client's bucket according to the config passed. Requires either
148
- * `configureDataRecovery(...)` to have been called, or `hydrateOnStartup` in
149
- * the constructor config.
211
+ * Lazily fetches and caches a document from cloud storage on-demand.
212
+ * Pure, efficient design for large workloads at maximum scale:
213
+ * 1. Fast-path negative cache (bounded QuickLRU) prevents repetitive S3 roundtrips for missing keys.
214
+ * 2. Singleflight deduplication coalesces concurrent requests for the same key into a single S3 request.
215
+ * 3. Atomic temp-file persistence + direct in-memory cache update eliminates redundant disk reads.
216
+ * 4. Generation-aware invalidation prevents resurrection: a delete/write that
217
+ * commits while hydration is in-flight bumps the per-key generation; stale
218
+ * hydration results are discarded and any just-written file is removed.
219
+ */
220
+ private hydrateKey;
221
+ /**
222
+ * Run hydration at any time (idempotent).
223
+ * Strictly supports two modes:
224
+ * - 'lazy' (default): enables on-demand gradual hydration (downloads 0 files in bulk).
225
+ * - 'eager': bulk downloads all missing files from cloud before returning.
150
226
  */
151
227
  hydrate(options?: {
152
- mode?: 'all' | 'missing' | 'snapshot';
228
+ mode?: HydrationMode;
153
229
  timeout?: number;
154
230
  }): Promise<RecoveryResult>;
155
231
  private initializeDirectories;
156
232
  private static readonly MAX_KEY_LENGTH;
157
233
  private validateKey;
234
+ private bumpGeneration;
235
+ private getGeneration;
158
236
  /**
159
237
  * Tracks which keys each active transaction has touched (cache entries tagged
160
238
  * with that txId). Used by commit()/rollback() to promote/invalidate only the
@@ -166,11 +244,7 @@ export declare class Tero {
166
244
  beginTransaction(options?: TransactionOptions): Transaction;
167
245
  private _beginTransaction;
168
246
  private _txId;
169
- write(transactionId: string | Transaction, key: string, data: any, options?: {
170
- validate?: boolean;
171
- schemaName?: string;
172
- strict?: boolean;
173
- }): Promise<ValidationResult | void>;
247
+ write(transactionId: string | Transaction, key: string, data: any): Promise<void>;
174
248
  read(transactionId: string | Transaction, key: string, options?: {
175
249
  lock?: 'shared' | 'exclusive';
176
250
  }): Promise<any>;
@@ -184,16 +258,8 @@ export declare class Tero {
184
258
  };
185
259
  totalRequests: number;
186
260
  };
187
- create(key: string, initialData?: any, options?: {
188
- validate?: boolean;
189
- schemaName?: string;
190
- strict?: boolean;
191
- }): Promise<ValidationResult | boolean>;
192
- update(key: string, data: any, options?: {
193
- validate?: boolean;
194
- schemaName?: string;
195
- strict?: boolean;
196
- }): Promise<ValidationResult | void>;
261
+ create(key: string, initialData?: any): Promise<boolean>;
262
+ update(key: string, data: any): Promise<void>;
197
263
  /**
198
264
  * Read a document. Returns the document data on success, or `null` if the
199
265
  * document is absent (use `=== null` to check). For backwards-compat, `false`
@@ -219,17 +285,57 @@ export declare class Tero {
219
285
  * cache-miss reads, which are syscall-dominated — measured impact: none.
220
286
  */
221
287
  private keyToPath;
288
+ private localTombstonePath;
289
+ private writeLocalTombstone;
290
+ private hasLocalTombstone;
291
+ /**
292
+ * fsync a directory path by opening it read-only and synchronizing its
293
+ * (open) descriptor. This flushes the directory's metadata (rename/unlink
294
+ * directory-entry changes) to disk so that file replacements and removals
295
+ * are durable across power loss. No-op if the directory does not exist
296
+ * (ENOENT) — mirrors the pattern in `ACIDStorageEngine.fsyncDir`.
297
+ */
298
+ private fsyncDirectory;
299
+ private deleteLocalTombstone;
300
+ private pendingCloudPath;
301
+ private pendingCloudDeletionsPath;
302
+ private loadPendingCloud;
303
+ private savePendingCloud;
304
+ private loadPendingCloudDeletions;
305
+ private savePendingCloudDeletions;
306
+ private pendingLocalTombstoneRemovalsPath;
307
+ private loadPendingLocalTombstoneRemovals;
308
+ private savePendingLocalTombstoneRemovals;
309
+ private queueLocalTombstoneRemoval;
310
+ private queueCloudTombstoneDeletion;
311
+ private queueCloudTombstone;
312
+ private withReconciliationLock;
313
+ private scheduleCloudRetry;
314
+ /**
315
+ * Retry pending local tombstone removals (P1).
316
+ *
317
+ * For each key, first retries the local unlink + parent-dir fsync. Only once
318
+ * that succeeds does it proceed to the cloud tombstone deletion (which the
319
+ * cloud-deletion retry worker cannot do while a local tombstone exists).
320
+ * If the key was re-deleted in the meantime, the local tombstone should
321
+ * stay — the pending removal is cancelled.
322
+ */
323
+ private retryPendingLocalTombstoneRemovals;
324
+ private retryPendingCloudTombstones;
325
+ private retryPendingCloudTombstoneDeletions;
326
+ /** Whether cloud tombstone reconciliation is pending (P0-2). */
327
+ isCloudReconciliationPending(): boolean;
328
+ /** Keys with pending cloud delete/tombstone (P0-2). */
329
+ getCloudReconciliationPendingKeys(): string[];
330
+ /** Retry pending cloud tombstones immediately (P0-2). */
331
+ retryCloudReconciliation(): Promise<void>;
222
332
  remove(key: string): Promise<void>;
223
333
  delete(key: string): Promise<void>;
224
334
  exists(key: string): boolean;
225
335
  batchWrite(operations: Array<{
226
336
  key: string;
227
337
  data: any;
228
- }>, options?: {
229
- validate?: boolean;
230
- schemaName?: string;
231
- strict?: boolean;
232
- }): Promise<void>;
338
+ }>): Promise<void>;
233
339
  batchRead(keys: string[]): Promise<{
234
340
  [key: string]: any;
235
341
  }>;
@@ -239,29 +345,8 @@ export declare class Tero {
239
345
  _deleteRaw(transactionId: string, key: string): Promise<void>;
240
346
  _rollbackRaw(transactionId: string): Promise<void>;
241
347
  _getTxStatus(transactionId: string): 'active' | 'committed' | 'aborted' | 'not_found';
348
+ _isTransactionActive(transactionId: string): boolean;
242
349
  getTransactionStats(): TransactionStats;
243
- setSchema(collectionName: string, schema: DocumentSchema): void;
244
- getSchema(collectionName: string): DocumentSchema | undefined;
245
- removeSchema(collectionName: string): boolean;
246
- validateData(collectionName: string, data: any): ValidationResult;
247
- hasSchema(collectionName: string): boolean;
248
- listSchemas(): string[];
249
- exportSchemas(): Record<string, DocumentSchema>;
250
- getSchemaStats(): {
251
- totalSchemas: number;
252
- schemaNames: string[];
253
- totalFields: number;
254
- };
255
- createWithValidation(key: string, initialData?: any, options?: {
256
- validate?: boolean;
257
- schemaName?: string;
258
- strict?: boolean;
259
- }): Promise<ValidationResult>;
260
- updateWithValidation(key: string, data: any, options?: {
261
- validate?: boolean;
262
- schemaName?: string;
263
- strict?: boolean;
264
- }): Promise<ValidationResult>;
265
350
  configureBackup(config: BackupConfig): void;
266
351
  /** Alias retained for the existing test surface / older callers. */
267
352
  configureAdvancedBackup(config: BackupConfig): void;
@@ -327,6 +412,8 @@ export declare class Tero {
327
412
  cloudStorage: CloudStorageConfig;
328
413
  nodeId?: string;
329
414
  pointInTime?: number;
415
+ targetLsn?: number;
416
+ customS3Client?: any;
330
417
  /** Name of the ORIGINAL database directory in the bucket, if restoring to a
331
418
  * new directory name (disaster-recovery / staging restores). Defaults to `directory`. */
332
419
  sourceDirectory?: string;
@@ -358,10 +445,20 @@ export declare class Tero {
358
445
  * Options:
359
446
  * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
360
447
  * - mode: 'missing' (default) — only fetch if missing locally; 'all' — always overwrite from cloud
448
+ * - throwOnRecoveryError: boolean (default false) — re-throw cloud/recovery errors instead of returning null
361
449
  */
362
450
  getWithRecovery(key: string, options?: {
363
451
  fallbackToCloud?: boolean;
364
452
  mode?: 'missing' | 'all';
453
+ throwOnRecoveryError?: boolean;
454
+ }): Promise<any | null>;
455
+ /**
456
+ * Strict version of getWithRecovery that throws any recovery/cloud error (auth, network, corruption)
457
+ * instead of swallowing and returning null.
458
+ */
459
+ getWithRecoveryStrict(key: string, options?: {
460
+ fallbackToCloud?: boolean;
461
+ mode?: 'missing' | 'all';
365
462
  }): Promise<any | null>;
366
463
  /**
367
464
  * Probe local + cloud availability for a key without modifying local state.
@@ -401,6 +498,15 @@ export declare class Tero {
401
498
  destroyAsync(): Promise<void>;
402
499
  close(): Promise<void>;
403
500
  destroy(): void;
501
+ /**
502
+ * Returns true if the database encountered a non-fatal maintenance error
503
+ * (such as background checkpoint or archive failure) and is running in degraded mode.
504
+ */
505
+ isDegraded(): boolean;
506
+ /**
507
+ * Returns the most recent background maintenance error, if any.
508
+ */
509
+ getLastMaintenanceError(): Error | null;
404
510
  /**
405
511
  * Generates a unique identifier with a custom prefix.
406
512
  *
@@ -430,4 +536,4 @@ export declare class Tero {
430
536
  */
431
537
  getNewId(prefix: string): string;
432
538
  }
433
- export { DocumentSchema, ValidationResult, BackupConfig, BackupMetadata, BucketBackupResult, CloudStorageConfig, RecoveryConfig, RecoveryResult, FileRecoveryInfo, HydrateConfig, TeroConfig, LiveBackupOptions, LiveBackupStatus, LiveCheckpointResult, RestoreLiveResult, BackupLogger };
539
+ export { BackupConfig, BackupMetadata, BucketBackupResult, CloudStorageConfig, RecoveryConfig, RecoveryResult, FileRecoveryInfo, HydrateConfig, HydrationMode, TeroConfig, LiveBackupOptions, LiveBackupStatus, LiveCheckpointResult, RestoreLiveResult, BackupLogger, RecoveryCorruptionError, DataCorruptionError };