tero 0.1.2 → 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 CHANGED
@@ -46,10 +46,16 @@ const db = new Tero({
46
46
 
47
47
  await db.create('user1', { name: 'Alice', email: 'alice@example.com' });
48
48
  const user = await db.get('user1');
49
- await db.update('user1', { age: 30 });
49
+ await db.update('user1', { age: 30 }); // deep-merges into the document
50
+ await db.set('user1', { name: 'Alice' }); // replaces it: fields not given are removed
50
51
  await db.remove('user1');
51
52
  ```
52
53
 
54
+ `update()` merges, so it can add or change fields but never remove one. When you
55
+ hold the whole document (read → modify → write), use `set()` — it is an upsert
56
+ that replaces the document exactly. Transactions have `tx.set()` and
57
+ `batchWrite()` accepts `{ key, data, replace: true }`.
58
+
53
59
  ## ACID transactions
54
60
 
55
61
  All mutation methods (`create`, `update`, `remove`) are auto-wrapped in atomic ACID transactions with two-phase locking. `get()` provides a zero-latency point-in-time snapshot read (LRU cache → committed buffer → partitioned disk). For multi-step atomic workflows, use explicit transactions:
@@ -231,11 +237,54 @@ const db = new Tero({
231
237
  checkpointBatchSize: 5000,// default: 1000, committedBuffer entries flushed per tick
232
238
  archiveKeepCount: 50, // default: 20, rotated 1MB WAL segments kept locally
233
239
  fileLock: true, // default: true, cross-process .lock directory guard
240
+ durableCheckpointIntervalMs: 30000, // default: 30000; fsync data files + log a durable
241
+ // checkpoint so a restart replays only WAL written since
234
242
  backup: { ... }, // optional: install a BackupConfig at construction
235
243
  hydrateOnStartup: { ... },// optional: v2 hydration before engine init
236
244
  });
237
245
  ```
238
246
 
247
+ ### Crash recovery
248
+
249
+ Recovery is redo-only and starts at the last durable checkpoint (taken every
250
+ `durableCheckpointIntervalMs` and on close), so boot time and memory are bounded
251
+ by one checkpoint interval of writes, not by how long the process ran.
252
+ Uncommitted transactions never reach data files, so nothing is undone.
253
+
254
+ ### Cloud recovery modes
255
+
256
+ `configureDataRecovery({ ..., mode })`:
257
+
258
+ - `'lazy'` (default): a missing key is fetched from the bucket on read, and
259
+ deletes/re-creates are mirrored there with tombstones.
260
+ - `'off'`: the bucket is never touched by `get/create/update/delete` — use it
261
+ when the local disk is authoritative and restores happen explicitly
262
+ (`Tero.restoreFromLiveBackup`, `recoverAllFromCloud`) before the database opens.
263
+
264
+ S3 clients use a 30s request timeout and 5s connect timeout by default
265
+ (`cloudStorage.requestTimeoutMs`, `cloudStorage.connectionTimeoutMs`).
266
+
267
+ ### Live backup cadence and checkpoints
268
+
269
+ ```javascript
270
+ db.enableLiveBackup({
271
+ consistency: 'interval', // or 'per-second' (intervalMs ≤ 1000)
272
+ intervalMs: 5000, // RPO; one PUT per ship — slower = cheaper
273
+ checkpointIntervalMs: 900000, // default 15 min, 0 disables
274
+ initialCheckpointDelayMs: 15000, // default 0: let the app boot before the full upload
275
+ });
276
+ ```
277
+
278
+ The first checkpoint after every start is a FULL one (it re-bases whatever is on
279
+ disk — a restore, history whose WAL was pruned), so a restart never leaves
280
+ documents that exist only in old WAL. Periodic durable checkpoints fsync on the
281
+ libuv thread pool, so they don't block the event loop.
282
+
283
+ Each checkpoint uploads the documents changed since the last one, records the
284
+ replay floor in `latest.json`, and deletes bucket WAL objects that end before it.
285
+ A point-in-time restore can only go back to the latest checkpoint; asking for an
286
+ earlier moment throws instead of returning newer data.
287
+
239
288
  ### WAL retention and live backup
240
289
 
241
290
  Every commit is appended to a WAL that rotates into immutable 1MB segments
@@ -33,10 +33,36 @@ export interface LogEntry {
33
33
  key?: string;
34
34
  beforeImage?: JsonValue;
35
35
  afterImage?: JsonValue;
36
+ /** CHECKPOINT only: every commit with lsn <= this record is durably on the data files. */
37
+ durable?: boolean;
38
+ /** CHECKPOINT only: last commit LSN captured BEFORE the data files were synced. Commits above it are redone on recovery even when they sit below this record's own LSN (they landed while the checkpoint was in flight). */
39
+ durableLsn?: number;
40
+ /** CHECKPOINT only: oldest LSN a transaction committing after this checkpoint may have written at. */
41
+ floorLsn?: number;
36
42
  timestamp: number;
37
43
  checksum: string;
38
44
  }
39
45
  export type SynchronousMode = 'full' | 'normal' | 'off';
46
+ /**
47
+ * Start a fresh WAL whose numbering continues at `lsn` (used after a restore).
48
+ * The single record is a durable CHECKPOINT: the restored data files are the
49
+ * complete state, so recovery replays nothing, and every LSN the engine issues
50
+ * from here on is above anything already in the bucket — a new session can never
51
+ * ship WAL objects that collide with history.
52
+ */
53
+ export declare function writeWalSeed(dbPath: string, lsn: number): void;
54
+ /**
55
+ * Raw WAL lines with LSN > afterLsn, without parsing records. A record's own LSN is
56
+ * the last `"lsn":` field in its line (it is serialized after the document), so
57
+ * the document's content can never be mistaken for it. A trailing line without a
58
+ * newline (a write in progress) is left for the next read. Checksums are not
59
+ * verified here; whoever replays the lines (restore) verifies every record.
60
+ */
61
+ export declare function readRawWalLines(path: string, afterLsn: number): {
62
+ lines: string[];
63
+ firstLsn: number | null;
64
+ lastLsn: number | null;
65
+ };
40
66
  export declare function streamLogFile(filePath: string, visitor: (entry: LogEntry) => void, allowTornTail?: boolean): {
41
67
  firstLsn: number | null;
42
68
  lastLsn: number | null;
@@ -113,9 +139,16 @@ export declare class WriteAheadLog {
113
139
  * trading a small RPO window (commitIntervalMs, default 10ms) for 10–100x
114
140
  * throughput. This is the same knob SQLite exposes as `PRAGMA synchronous=NORMAL`.
115
141
  */
142
+ private groupFsyncInFlight;
116
143
  private startGroupCommitTimer;
117
144
  private stopGroupCommitTimer;
118
145
  private recoverFromLog;
146
+ /**
147
+ * LSN of the first record in the active log (null while it is empty). Tracked
148
+ * in memory so rotation doesn't have to re-read and re-checksum the whole
149
+ * file — at high write rates that re-read cost as much as the writes.
150
+ */
151
+ private activeFirstLsn;
119
152
  /**
120
153
  * Stream WAL entries from disk line-by-line without loading the entire file
121
154
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
@@ -129,6 +162,16 @@ export declare class WriteAheadLog {
129
162
  * - Monotonic LSN strictly required within the log stream
130
163
  */
131
164
  streamLogEntries(visitor: (entry: LogEntry) => void): void;
165
+ /**
166
+ * The newest durable CHECKPOINT, searching newest file first and stopping at the
167
+ * first file that has one — older segments are never read.
168
+ */
169
+ findLastDurableCheckpoint(): {
170
+ lsn: number;
171
+ floorLsn: number;
172
+ } | null;
173
+ /** Stream entries from the segments that can contain LSN >= minLsn, then the active log. */
174
+ streamSince(minLsn: number, visitor: (entry: LogEntry) => void): void;
132
175
  streamAllLogEntries(visitor: (entry: LogEntry) => void): void;
133
176
  private calculateChecksum;
134
177
  private verifyChecksum;
@@ -140,7 +183,13 @@ export declare class WriteAheadLog {
140
183
  * This eliminates per-entry syscalls: a transaction with N writes does 1
141
184
  * appendFileSync (of all N+2 entries) instead of N+2 separate appends.
142
185
  */
143
- writeLog(entry: Omit<LogEntry, 'lsn' | 'checksum' | 'timestamp'>): number;
186
+ /**
187
+ * @param afterImageJson JSON.stringify(entry.afterImage), when the caller already
188
+ * has it: the record is then assembled around it instead of serializing the
189
+ * document again. The text is byte-identical to JSON.stringify(record), so
190
+ * checksums verify exactly as before.
191
+ */
192
+ writeLog(entry: Omit<LogEntry, 'lsn' | 'checksum' | 'timestamp'>, afterImageJson?: string): number;
144
193
  /**
145
194
  * Flush the in-memory write buffer to disk in a single appendFileSync call.
146
195
  * This is the ONLY place we call appendFileSync — all writeLog calls just
@@ -185,6 +234,13 @@ export declare class WriteAheadLog {
185
234
  * (e.g. when live backup is disabled and pruning should be unconditional).
186
235
  */
187
236
  setArchiveProtector(protector: ((segmentEndLsn: number) => boolean) | null): void;
237
+ /**
238
+ * Oldest LSN crash recovery still needs (the last durable checkpoint's replay
239
+ * floor). Segments ending at or after it are never pruned by the keep count:
240
+ * dropping one would lose commits whose data files are not fsynced yet.
241
+ */
242
+ private recoveryFloor;
243
+ setRecoveryFloor(lsn: number | null): void;
188
244
  /**
189
245
  * Retain the newest `keepCount` segments and delete the rest, oldest first —
190
246
  * except any segment the archive protector still considers unshipped, which
@@ -205,6 +261,8 @@ export declare class WriteAheadLog {
205
261
  * the dirty flag so the next timer tick won't re-fsync.
206
262
  */
207
263
  forceFlush(): void;
264
+ /** Path of the active log file (for raw readers such as the live shipper). */
265
+ getLogPath(): string;
208
266
  getCurrentLSN(): number;
209
267
  /**
210
268
  * Truncate (clear) the WAL entirely.
@@ -348,6 +406,22 @@ export declare class ACIDStorageEngine {
348
406
  * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
349
407
  */
350
408
  private dirtyKeys;
409
+ /**
410
+ * Dirty-key tracking is only needed while a consumer (live backup) acknowledges
411
+ * entries. Without one, every committed document would be cloned into this map
412
+ * forever — an unbounded copy of the whole working set. The engine tracks by
413
+ * default (standalone snapshots rely on it); Tero turns it off unless live
414
+ * backup is enabled.
415
+ */
416
+ private trackDirty;
417
+ /** Data files written without fsync (normal mode) since the last durable checkpoint. */
418
+ private unsyncedFiles;
419
+ private unsyncedDirs;
420
+ /** Last durable checkpoint: commits <= lsn are on disk; replay starts at floorLsn. */
421
+ private durableCheckpoint;
422
+ private commitsSinceDurableCheckpoint;
423
+ private recoveredCommits;
424
+ private durableCheckpointTimer?;
351
425
  private activeSnapshotLsn;
352
426
  private snapshotBeforeImages;
353
427
  private lastCommittedLSN;
@@ -356,17 +430,31 @@ export declare class ACIDStorageEngine {
356
430
  isDegraded(): boolean;
357
431
  getLastMaintenanceError(): Error | null;
358
432
  getLastCommittedLSN(): number;
359
- peekDirtyKeys(upToLsn?: number): Map<string, DirtyEntry>;
433
+ peekDirtyKeys(upToLsn?: number, clone?: boolean): Map<string, DirtyEntry>;
360
434
  acknowledgeDirtyKeys(acked: Iterable<{
361
435
  key: string;
362
436
  lsn: number;
363
437
  }>): void;
364
438
  getDirtyKeyCount(): number;
439
+ /** Enable/disable dirty-key tracking. Disabling drops everything tracked so far. */
440
+ setDirtyTracking(enabled: boolean): void;
441
+ isDirtyTrackingEnabled(): boolean;
442
+ /**
443
+ * Oldest LSN any transaction that has not committed yet may have written at.
444
+ * A checkpoint (local or cloud) taken now must keep WAL from this LSN onward:
445
+ * a transaction that BEGAN before the checkpoint and COMMITS after it has its
446
+ * WRITE records below the checkpoint LSN.
447
+ */
448
+ getReplayFloorLsn(): number;
449
+ getDurableCheckpoint(): {
450
+ lsn: number;
451
+ floorLsn: number;
452
+ } | null;
365
453
  /**
366
454
  * Creates an isolated logical snapshot handle as of upToLsn.
367
455
  * Enforces single-active-snapshot invariant and provides explicit close().
368
456
  */
369
- beginSnapshot(upToLsn: number): SnapshotHandle;
457
+ beginSnapshot(upToLsn: number, preCapturedDirty?: Map<string, DirtyEntry>): SnapshotHandle;
370
458
  /**
371
459
  * Streams a version-consistent logical snapshot of the database as of upToLsn.
372
460
  * Fully protected against concurrent writes via Copy-On-Write snapshotBeforeImages.
@@ -380,14 +468,27 @@ export declare class ACIDStorageEngine {
380
468
  private _streamSnapshotFiles;
381
469
  private synchronous;
382
470
  private checkpointBatchSize;
383
- constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number, archiveKeepCount?: number);
471
+ constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number, archiveKeepCount?: number, durableCheckpointIntervalMs?: number);
384
472
  private fsyncFile;
385
473
  private fsyncDir;
386
474
  private initializeStorage;
475
+ /**
476
+ * Redo-only crash recovery, bounded by the last durable checkpoint.
477
+ *
478
+ * Data files only ever receive COMMITTED after-images (writes are deferred to
479
+ * committedBuffer until commit), so there is nothing to undo: an uncommitted
480
+ * transaction never touched a data file. (Earlier versions "undid" such
481
+ * transactions by writing their before-image — on every boot, after redo —
482
+ * which rolled newer commits back to stale data.)
483
+ *
484
+ * The last durable CHECKPOINT is found newest-file-first. Only segments that
485
+ * reach its replay floor are read: one pass collects transactions committed
486
+ * after the checkpoint, a second re-applies just their records in WAL order,
487
+ * streaming — nothing but transaction ids is held in memory.
488
+ */
387
489
  private performCrashRecovery;
388
490
  private redoOperation;
389
491
  private redoDelete;
390
- private undoOperation;
391
492
  /**
392
493
  * Atomic data file write: write to a temp file then atomically rename over
393
494
  * the target. The atomic rename guarantees readers never see a partial file
@@ -405,7 +506,7 @@ export declare class ACIDStorageEngine {
405
506
  * `Promise<void>` only when the lock is contended and we must wait in queue.
406
507
  * Callers should check: `if (result !== undefined) await result;`
407
508
  */
408
- write(transactionId: string, key: string, data: any, cachedBeforeImage?: any): void | Promise<void>;
509
+ write(transactionId: string, key: string, data: any, cachedBeforeImage?: any, replace?: boolean, dataJson?: string): void | Promise<void>;
409
510
  /**
410
511
  * Synchronous write work — called from write() after the lock is acquired.
411
512
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
@@ -447,6 +548,8 @@ export declare class ACIDStorageEngine {
447
548
  * work on the happy path.
448
549
  */
449
550
  rollbackTransaction(transactionId: string): void;
551
+ /** Last committed image of a key: committedBuffer first, then the data file. null when absent. */
552
+ private readCommittedState;
450
553
  private deepMerge;
451
554
  getTransactionStatus(transactionId: string): 'active' | 'committed' | 'aborted' | 'not_found';
452
555
  /**
@@ -455,6 +558,21 @@ export declare class ACIDStorageEngine {
455
558
  */
456
559
  isTransactionActive(transactionId: string): boolean;
457
560
  getActiveTransactions(): string[];
561
+ private checkpointInFlight;
562
+ /**
563
+ * forceCheckpoint() without blocking the event loop on fsync: data files are
564
+ * written now, fsynced on the libuv pool, and only then is the durable
565
+ * CHECKPOINT logged. Used by the periodic timer; close() uses the sync form.
566
+ */
567
+ forceCheckpointAsync(): Promise<void>;
568
+ private inFlightFsync;
569
+ /**
570
+ * Durable checkpoint. Afterwards every commit up to now is fsynced into the data
571
+ * files, so crash recovery only replays WAL written after this point.
572
+ *
573
+ * Order matters: capture the LSN and replay floor first (synchronously, so no
574
+ * commit can slip between), then make data durable, then log the CHECKPOINT.
575
+ */
458
576
  forceCheckpoint(): void;
459
577
  /**
460
578
  * Returns a reference to the underlying WAL (used by v2 backup to upload