tero 0.0.12 → 0.1.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/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
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;
8
9
  /**
9
10
  * Durability / throughput trade-off knob (like SQLite's `PRAGMA synchronous`):
10
11
  * - 'full' (default): fsync the WAL on every commit. Max durability, ~15–60 ops/s
@@ -34,17 +35,22 @@ interface TeroConfig {
34
35
  */
35
36
  fileLock?: boolean;
36
37
  }
38
+ type HydrationMode = 'lazy' | 'eager';
37
39
  interface HydrateConfig {
38
40
  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). */
41
+ /**
42
+ * Hydration mode:
43
+ * - 'lazy' (default): downloads 0 files on startup for instant boot.
44
+ * Files are hydrated gradually on-demand as they are requested.
45
+ * - 'eager': bulk downloads missing files from the bucket before engine init.
46
+ */
47
+ mode?: HydrationMode;
48
+ /** Continue when a single file fails to download in eager mode (default true). */
45
49
  continueOnError?: boolean;
46
- /** Maximum time to wait for hydration before attempting engine init (ms). */
50
+ /** Maximum time to wait for hydration in eager mode before engine init (ms). */
47
51
  timeout?: number;
52
+ /** Optional custom S3 client for mocking/testing */
53
+ customS3Client?: any;
48
54
  }
49
55
  interface TransactionOptions {
50
56
  timeout?: number;
@@ -68,11 +74,16 @@ export declare class Transaction {
68
74
  private committed;
69
75
  private rolledBack;
70
76
  private timeoutTimer?;
77
+ private txState;
78
+ private abortError;
71
79
  constructor(id: string, db: Tero, options?: TransactionOptions);
72
80
  getId(): string;
73
81
  isActive(): boolean;
74
82
  isRolledBack(): boolean;
75
83
  isCommitted(): boolean;
84
+ /** Whether transaction is in ABORTING state (timeout fired, rollback in flight) */
85
+ isAborting(): boolean;
86
+ getAbortError(): Error | null;
76
87
  private _checkActive;
77
88
  create(key: string, initialData?: any): Promise<void>;
78
89
  update(key: string, data: any): Promise<void>;
@@ -112,11 +123,54 @@ export declare class Tero {
112
123
  private cacheHits;
113
124
  private cacheRequests;
114
125
  private acidEngine;
115
- private schemaValidator;
116
126
  private backupManager?;
117
127
  private dataRecovery?;
128
+ private hydrateMode;
129
+ private inFlightHydrations;
130
+ private missingKeys;
131
+ private readonly MISSING_KEYS_MAX;
118
132
  private committedCount;
119
133
  private rolledBackCount;
134
+ /** Monotonic per-key generation for in-flight hydration invalidation (P0-1). */
135
+ private keyGenerations;
136
+ /** Durable cloud reconciliation for deletes (P0-2) — keys needing cloud delete+tombstone, with deletion LSN */
137
+ private cloudPendingTombstones;
138
+ private cloudPendingTombstoneDeletions;
139
+ /**
140
+ * Durable pending local-tombstone-removal retries (P1). When a committed
141
+ * recreate/write cannot unlink the old local tombstone (EBUSY, EPERM, …),
142
+ * the key is queued here — NOT in cloudPendingTombstoneDeletions. The retry
143
+ * worker first retries the local unlink+fsync, and only once that succeeds
144
+ * does it proceed to the cloud tombstone deletion.
145
+ *
146
+ * Previously the code queued a cloud tombstone deletion, but the
147
+ * cloud-deletion retry worker explicitly refuses to process entries while a
148
+ * local tombstone still exists (hasLocal guard) — so the queue was
149
+ * self-cancelling in exactly the failure state it was created to recover,
150
+ * leaving an undeletable local tombstone forever and preventing the cloud
151
+ * tombstone from ever being deleted.
152
+ */
153
+ private pendingLocalTombstoneRemovals;
154
+ private cloudPendingTimer?;
155
+ private reconciliationLocks;
156
+ private reconciliationLockStorage;
157
+ /**
158
+ * Re-entrancy guard for the durable pending-queue journal (P1).
159
+ *
160
+ * `savePendingCloud()` / `savePendingCloudDeletions()` are fully
161
+ * synchronous, and Node's single-threaded execution guarantees that two
162
+ * calls can never interleave at the syscall level — each
163
+ * write/fsync/rename sequence runs atomically w.r.t. the JS thread, which
164
+ * is what prevents lost queue entries and temp-file collisions across
165
+ * concurrently-reconciling keys (reconciliation is only locked *per key*,
166
+ * so different keys reconcile in parallel).
167
+ *
168
+ * This flag makes that invariant explicit and defensively aborts if a
169
+ * future change introduces an `await` (or an async refactor) inside the
170
+ * persistence path, which would break the per-call atomicity the durable
171
+ * reconciliation queue depends on.
172
+ */
173
+ private pendingPersistenceInFlight;
120
174
  /**
121
175
  * Bounded LRU of known-existing keys. Replaces the unbounded Set<string>
122
176
  * that grew linearly with key count (catastrophic memory at 1M+ keys/tenant).
@@ -137,24 +191,38 @@ export declare class Tero {
137
191
  */
138
192
  constructor(config?: TeroConfig);
139
193
  /**
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.
194
+ * v2 async factory.
195
+ * - mode: 'lazy' (default) -> Instant startup, downloads 0 files on boot.
196
+ * Files hydrate gradually on-demand as they are requested.
197
+ * - mode: 'eager' -> Bulk downloads files from cloud bucket before engine init.
143
198
  */
144
199
  static create(config?: TeroConfig): Promise<Tero>;
145
200
  /**
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.
201
+ * Lazily fetches and caches a document from cloud storage on-demand.
202
+ * Pure, efficient design for large workloads at maximum scale:
203
+ * 1. Fast-path negative cache (bounded QuickLRU) prevents repetitive S3 roundtrips for missing keys.
204
+ * 2. Singleflight deduplication coalesces concurrent requests for the same key into a single S3 request.
205
+ * 3. Atomic temp-file persistence + direct in-memory cache update eliminates redundant disk reads.
206
+ * 4. Generation-aware invalidation prevents resurrection: a delete/write that
207
+ * commits while hydration is in-flight bumps the per-key generation; stale
208
+ * hydration results are discarded and any just-written file is removed.
209
+ */
210
+ private hydrateKey;
211
+ /**
212
+ * Run hydration at any time (idempotent).
213
+ * Strictly supports two modes:
214
+ * - 'lazy' (default): enables on-demand gradual hydration (downloads 0 files in bulk).
215
+ * - 'eager': bulk downloads all missing files from cloud before returning.
150
216
  */
151
217
  hydrate(options?: {
152
- mode?: 'all' | 'missing' | 'snapshot';
218
+ mode?: HydrationMode;
153
219
  timeout?: number;
154
220
  }): Promise<RecoveryResult>;
155
221
  private initializeDirectories;
156
222
  private static readonly MAX_KEY_LENGTH;
157
223
  private validateKey;
224
+ private bumpGeneration;
225
+ private getGeneration;
158
226
  /**
159
227
  * Tracks which keys each active transaction has touched (cache entries tagged
160
228
  * with that txId). Used by commit()/rollback() to promote/invalidate only the
@@ -166,11 +234,7 @@ export declare class Tero {
166
234
  beginTransaction(options?: TransactionOptions): Transaction;
167
235
  private _beginTransaction;
168
236
  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>;
237
+ write(transactionId: string | Transaction, key: string, data: any): Promise<void>;
174
238
  read(transactionId: string | Transaction, key: string, options?: {
175
239
  lock?: 'shared' | 'exclusive';
176
240
  }): Promise<any>;
@@ -184,16 +248,8 @@ export declare class Tero {
184
248
  };
185
249
  totalRequests: number;
186
250
  };
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>;
251
+ create(key: string, initialData?: any): Promise<boolean>;
252
+ update(key: string, data: any): Promise<void>;
197
253
  /**
198
254
  * Read a document. Returns the document data on success, or `null` if the
199
255
  * document is absent (use `=== null` to check). For backwards-compat, `false`
@@ -219,17 +275,57 @@ export declare class Tero {
219
275
  * cache-miss reads, which are syscall-dominated — measured impact: none.
220
276
  */
221
277
  private keyToPath;
278
+ private localTombstonePath;
279
+ private writeLocalTombstone;
280
+ private hasLocalTombstone;
281
+ /**
282
+ * fsync a directory path by opening it read-only and synchronizing its
283
+ * (open) descriptor. This flushes the directory's metadata (rename/unlink
284
+ * directory-entry changes) to disk so that file replacements and removals
285
+ * are durable across power loss. No-op if the directory does not exist
286
+ * (ENOENT) — mirrors the pattern in `ACIDStorageEngine.fsyncDir`.
287
+ */
288
+ private fsyncDirectory;
289
+ private deleteLocalTombstone;
290
+ private pendingCloudPath;
291
+ private pendingCloudDeletionsPath;
292
+ private loadPendingCloud;
293
+ private savePendingCloud;
294
+ private loadPendingCloudDeletions;
295
+ private savePendingCloudDeletions;
296
+ private pendingLocalTombstoneRemovalsPath;
297
+ private loadPendingLocalTombstoneRemovals;
298
+ private savePendingLocalTombstoneRemovals;
299
+ private queueLocalTombstoneRemoval;
300
+ private queueCloudTombstoneDeletion;
301
+ private queueCloudTombstone;
302
+ private withReconciliationLock;
303
+ private scheduleCloudRetry;
304
+ /**
305
+ * Retry pending local tombstone removals (P1).
306
+ *
307
+ * For each key, first retries the local unlink + parent-dir fsync. Only once
308
+ * that succeeds does it proceed to the cloud tombstone deletion (which the
309
+ * cloud-deletion retry worker cannot do while a local tombstone exists).
310
+ * If the key was re-deleted in the meantime, the local tombstone should
311
+ * stay — the pending removal is cancelled.
312
+ */
313
+ private retryPendingLocalTombstoneRemovals;
314
+ private retryPendingCloudTombstones;
315
+ private retryPendingCloudTombstoneDeletions;
316
+ /** Whether cloud tombstone reconciliation is pending (P0-2). */
317
+ isCloudReconciliationPending(): boolean;
318
+ /** Keys with pending cloud delete/tombstone (P0-2). */
319
+ getCloudReconciliationPendingKeys(): string[];
320
+ /** Retry pending cloud tombstones immediately (P0-2). */
321
+ retryCloudReconciliation(): Promise<void>;
222
322
  remove(key: string): Promise<void>;
223
323
  delete(key: string): Promise<void>;
224
324
  exists(key: string): boolean;
225
325
  batchWrite(operations: Array<{
226
326
  key: string;
227
327
  data: any;
228
- }>, options?: {
229
- validate?: boolean;
230
- schemaName?: string;
231
- strict?: boolean;
232
- }): Promise<void>;
328
+ }>): Promise<void>;
233
329
  batchRead(keys: string[]): Promise<{
234
330
  [key: string]: any;
235
331
  }>;
@@ -239,29 +335,8 @@ export declare class Tero {
239
335
  _deleteRaw(transactionId: string, key: string): Promise<void>;
240
336
  _rollbackRaw(transactionId: string): Promise<void>;
241
337
  _getTxStatus(transactionId: string): 'active' | 'committed' | 'aborted' | 'not_found';
338
+ _isTransactionActive(transactionId: string): boolean;
242
339
  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
340
  configureBackup(config: BackupConfig): void;
266
341
  /** Alias retained for the existing test surface / older callers. */
267
342
  configureAdvancedBackup(config: BackupConfig): void;
@@ -327,6 +402,8 @@ export declare class Tero {
327
402
  cloudStorage: CloudStorageConfig;
328
403
  nodeId?: string;
329
404
  pointInTime?: number;
405
+ targetLsn?: number;
406
+ customS3Client?: any;
330
407
  /** Name of the ORIGINAL database directory in the bucket, if restoring to a
331
408
  * new directory name (disaster-recovery / staging restores). Defaults to `directory`. */
332
409
  sourceDirectory?: string;
@@ -358,10 +435,20 @@ export declare class Tero {
358
435
  * Options:
359
436
  * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
360
437
  * - mode: 'missing' (default) — only fetch if missing locally; 'all' — always overwrite from cloud
438
+ * - throwOnRecoveryError: boolean (default false) — re-throw cloud/recovery errors instead of returning null
361
439
  */
362
440
  getWithRecovery(key: string, options?: {
363
441
  fallbackToCloud?: boolean;
364
442
  mode?: 'missing' | 'all';
443
+ throwOnRecoveryError?: boolean;
444
+ }): Promise<any | null>;
445
+ /**
446
+ * Strict version of getWithRecovery that throws any recovery/cloud error (auth, network, corruption)
447
+ * instead of swallowing and returning null.
448
+ */
449
+ getWithRecoveryStrict(key: string, options?: {
450
+ fallbackToCloud?: boolean;
451
+ mode?: 'missing' | 'all';
365
452
  }): Promise<any | null>;
366
453
  /**
367
454
  * Probe local + cloud availability for a key without modifying local state.
@@ -401,6 +488,15 @@ export declare class Tero {
401
488
  destroyAsync(): Promise<void>;
402
489
  close(): Promise<void>;
403
490
  destroy(): void;
491
+ /**
492
+ * Returns true if the database encountered a non-fatal maintenance error
493
+ * (such as background checkpoint or archive failure) and is running in degraded mode.
494
+ */
495
+ isDegraded(): boolean;
496
+ /**
497
+ * Returns the most recent background maintenance error, if any.
498
+ */
499
+ getLastMaintenanceError(): Error | null;
404
500
  /**
405
501
  * Generates a unique identifier with a custom prefix.
406
502
  *
@@ -430,4 +526,4 @@ export declare class Tero {
430
526
  */
431
527
  getNewId(prefix: string): string;
432
528
  }
433
- export { DocumentSchema, ValidationResult, BackupConfig, BackupMetadata, BucketBackupResult, CloudStorageConfig, RecoveryConfig, RecoveryResult, FileRecoveryInfo, HydrateConfig, TeroConfig, LiveBackupOptions, LiveBackupStatus, LiveCheckpointResult, RestoreLiveResult, BackupLogger };
529
+ export { BackupConfig, BackupMetadata, BucketBackupResult, CloudStorageConfig, RecoveryConfig, RecoveryResult, FileRecoveryInfo, HydrateConfig, HydrationMode, TeroConfig, LiveBackupOptions, LiveBackupStatus, LiveCheckpointResult, RestoreLiveResult, BackupLogger, RecoveryCorruptionError, DataCorruptionError };