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/README.md CHANGED
@@ -13,7 +13,6 @@ Tero is a **library**, not a service. You embed it in a worker, container, or ed
13
13
  - **Embedded JSON document DB** with key/value + batch operations
14
14
  - **Real ACID**: WAL with fsync barriers on COMMIT/ROLLBACK, atomic data-file writes (temp → rename → fsync), in-memory pending-writes index so transaction reads never re-scan the WAL
15
15
  - **WAL rotation** into archive segments — backs up WAL segments and snapshots to object storage
16
- - **Schema validation** with strict mode (string/number/boolean/object/array/date/any, formats, enums, defaults, custom validators)
17
16
  - **Cloud backup** to AWS S3 or Cloudflare R2 (cron-scheduled), archive or individual-file format
18
17
  - **Cloud recovery** — full, single-file, or archive restore
19
18
  - **v2: hydrate on startup** — pull missing or all files from object storage before the ACID engine initializes to reconstruct node state
@@ -75,28 +74,6 @@ The money-transfer example demonstrates atomicity: `db.transferMoney('savings',
75
74
 
76
75
  A `commit()` returns only after the WAL `COMMIT` record and all pending writes have been fsynced to disk. A crash after `commit()` returns cannot lose the transaction. A crash mid-`commit()` leaves either the old or new state on disk, never a partial of either — data files are written via temp-file → fsync → atomic rename.
77
76
 
78
- ## Schema validation
79
-
80
- ```javascript
81
- db.setSchema('users', {
82
- name: { type: 'string', required: true, min: 2, max: 50 },
83
- email: { type: 'string', required: true, format: 'email' },
84
- age: { type: 'number', min: 0, max: 150 },
85
- profile: {
86
- type: 'object',
87
- properties: {
88
- bio: { type: 'string', max: 500 },
89
- website: { type: 'string', format: 'url' },
90
- },
91
- },
92
- });
93
-
94
- await db.create('user1', userData, { validate: true, schemaName: 'users', strict: true });
95
- ```
96
-
97
- Field types: `string`, `number`, `boolean`, `object`, `array`, `date`, `any`.
98
- Validation options: `required`, `min`, `max`, `format` (email/url/uuid/date/time/datetime/phone/ip), `pattern`, `enum`, `default`, `custom`.
99
-
100
77
  ## Batch operations
101
78
 
102
79
  ```javascript
@@ -227,7 +204,6 @@ Tero instance (one per process)
227
204
  │ ├── WriteAheadLog ─── append-only, fsync on barriers, rotates to archive segments
228
205
  │ ├── LockManager ─── per-key shared/exclusive locks with wait queue
229
206
  │ └── pendingWrites ─── in-memory per-transaction op index (O(1) reads within a tx)
230
- ├── SchemaValidator
231
207
  ├── BackupManager ─── cron-scheduled snapshot + WAL segment upload to object storage
232
208
  └── DataRecovery ─── hydrate-on-startup + runtime getWithRecovery
233
209
  ```
@@ -237,10 +213,9 @@ Tero instance (one per process)
237
213
 
238
214
  ```javascript
239
215
  try {
240
- await db.create('user', invalidData, { validate: true, strict: true });
216
+ await db.create('user', data);
241
217
  } catch (error) {
242
- if (error.message.includes('Schema validation failed')) { /* validation error */ }
243
- else if (error.message.includes('already exists')) { /* duplicate key */ }
218
+ if (error.message.includes('already exists')) { /* duplicate key */ }
244
219
  }
245
220
  ```
246
221
 
@@ -1,14 +1,47 @@
1
+ export type JsonPrimitive = string | number | boolean | null;
2
+ export type JsonArray = JsonValue[];
3
+ export type JsonObject = {
4
+ [key: string]: JsonValue;
5
+ };
6
+ export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
7
+ export declare function padLsn(lsn: number): string;
8
+ export declare class RecoveryCorruptionError extends Error {
9
+ walPath: string;
10
+ offset: number;
11
+ reason: string;
12
+ lsn?: number | undefined;
13
+ code: string;
14
+ constructor(walPath: string, offset: number, reason: string, lsn?: number | undefined);
15
+ }
16
+ export declare class DataCorruptionError extends Error {
17
+ code: string;
18
+ filePath?: string;
19
+ constructor(filePathOrMessage: string, details?: string);
20
+ }
21
+ export declare function cloneJson<T>(value: T): T;
22
+ export declare function verifyLogEntryChecksum(entry: LogEntry): boolean;
23
+ export interface DirtyEntry {
24
+ key: string;
25
+ lsn: number;
26
+ state: 'present' | 'deleted';
27
+ data?: JsonValue;
28
+ }
1
29
  export interface LogEntry {
2
30
  lsn: number;
3
31
  transactionId: string;
4
32
  operation: 'BEGIN' | 'WRITE' | 'DELETE' | 'COMMIT' | 'ROLLBACK' | 'CHECKPOINT';
5
33
  key?: string;
6
- beforeImage?: any;
7
- afterImage?: any;
34
+ beforeImage?: JsonValue;
35
+ afterImage?: JsonValue;
8
36
  timestamp: number;
9
37
  checksum: string;
10
38
  }
11
39
  export type SynchronousMode = 'full' | 'normal' | 'off';
40
+ export declare function streamLogFile(filePath: string, visitor: (entry: LogEntry) => void, allowTornTail?: boolean): {
41
+ firstLsn: number | null;
42
+ lastLsn: number | null;
43
+ count: number;
44
+ };
12
45
  export declare class WriteAheadLog {
13
46
  private logPath;
14
47
  private currentLSN;
@@ -50,11 +83,15 @@ export declare class WriteAheadLog {
50
83
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
51
84
  * calls visitor(entry) for each valid (checksum-verified) entry.
52
85
  *
53
- * This prevents OOM on large WALs — a 200MB, 1M-entry log previously
54
- * allocated ~400MB of V8 string objects via readFileSync + split(); now
55
- * peak memory is bounded to ~64KB + any objects the visitor retains.
86
+ * Invariant:
87
+ * - Newline-terminated invalid record -> fatal RecoveryCorruptionError
88
+ * - Interior invalid record -> fatal RecoveryCorruptionError
89
+ * - Final unterminated valid record -> replay (accept)
90
+ * - Final unterminated invalid record -> ignore as torn tail
91
+ * - Monotonic LSN strictly required within the log stream
56
92
  */
57
93
  streamLogEntries(visitor: (entry: LogEntry) => void): void;
94
+ streamAllLogEntries(visitor: (entry: LogEntry) => void): void;
58
95
  private calculateChecksum;
59
96
  private verifyChecksum;
60
97
  /**
@@ -75,19 +112,19 @@ export declare class WriteAheadLog {
75
112
  flushBuffer(): void;
76
113
  private checkLogRotation;
77
114
  /**
78
- * Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
79
- * and write a CHECKPOINT entry at the head of the new log. Old archives beyond
80
- * ARCHIVE_KEEP_COUNT are pruned locally (cloud upload in v2 retains durable copies).
81
- *
82
- * NOTE: ACIDStorageEngine.flushCommittedBuffer() MUST be called before
83
- * rotateLog() — see commitTransaction() — otherwise deferred writes still
84
- * in memory would be lost on crash after truncation. rotateLog() itself
85
- * only guarantees WAL durability (forceFlush before archiving).
115
+ * Rotate the WAL:
116
+ * 1. Ensure current WAL is fsynced.
117
+ * 2. Rename current log to .wal.seg-<startLsn>-<endLsn> (atomic segment rotation).
118
+ * 3. Fsync archive and parent directory.
119
+ * 4. Create fresh empty WAL and fsync it and parent directory.
120
+ * 5. Emit a CHECKPOINT entry at the head of the new log.
121
+ * 6. Clean up old archives beyond ARCHIVE_KEEP_COUNT.
86
122
  */
87
- rotateLog(): void;
123
+ rotateLog(): string | null;
88
124
  /**
89
125
  * Returns the paths of all locally retained WAL archives (newest first).
90
126
  * Used by v2 backup to upload segments to the client's bucket.
127
+ * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
91
128
  */
92
129
  listArchives(): string[];
93
130
  private cleanupOldArchives;
@@ -101,16 +138,19 @@ export declare class WriteAheadLog {
101
138
  forceFlush(): void;
102
139
  getCurrentLSN(): number;
103
140
  /**
104
- * Truncate (clear) the WAL entirely. Only safe when there are no active transactions
105
- * AND all data has been durably persisted to data files (which happens during commit).
106
- * In v2 this is also called after a successful bucket snapshot upload to bound growth.
141
+ * Truncate (clear) the WAL entirely.
142
+ * Force-flushes any buffered entries first, verifies buffer is drained,
143
+ * truncates .wal to 0 bytes, fsyncs file and directory, and cleans up archives.
107
144
  */
108
145
  truncateLog(): void;
109
146
  destroy(): void;
110
147
  }
111
148
  export declare class LockManager {
112
149
  private locks;
150
+ private waitingOn;
113
151
  private readonly DEADLOCK_TIMEOUT;
152
+ private hasCycle;
153
+ private cleanTxGraph;
114
154
  /**
115
155
  * Acquire a lock. Returns `true` synchronously when the lock is granted
116
156
  * immediately (uncontended fast path — zero Promise allocation). Returns a
@@ -128,6 +168,7 @@ export declare class LockManager {
128
168
  releaseLocksForTx(transactionId: string, heldKeys: Set<string>, waitingKeys?: Set<string>): void;
129
169
  releaseAllLocks(transactionId: string): void;
130
170
  detectDeadlock(): string[];
171
+ isKeyLocked(key: string): boolean;
131
172
  }
132
173
  /**
133
174
  * Map a document key to a 2-level hash-prefix partitioned path:
@@ -152,68 +193,97 @@ export declare function partitionedPath(dbPath: string, key: string): string;
152
193
  * what verifyDataIntegrity + backup enumeration use, replacing readdirSync.
153
194
  */
154
195
  export declare function walkPartitions(dbPath: string, visitor: (filePath: string) => void | Promise<void>): Promise<void>;
196
+ export interface RestoreMarker {
197
+ id: string;
198
+ targetDir: string;
199
+ stagingDir: string;
200
+ backupDir: string;
201
+ createdAt: number;
202
+ stage: 'prepared' | 'swapped';
203
+ }
204
+ export declare function safeRemoveDirectory(dirPath: string): void;
205
+ export declare function recoverPendingRestore(dbPath: string): void;
206
+ export declare function verifyWalSegmentContinuity(segmentPaths: string[], verifyContent?: boolean): Array<{
207
+ path: string;
208
+ startLsn: number;
209
+ endLsn: number;
210
+ }>;
211
+ export interface SnapshotHandle {
212
+ readonly lsn: number;
213
+ files(): AsyncGenerator<{
214
+ key: string;
215
+ lsn: number;
216
+ state: 'present' | 'deleted';
217
+ data?: JsonValue;
218
+ }>;
219
+ close(): void;
220
+ }
155
221
  export declare class ACIDStorageEngine {
156
222
  private wal;
157
223
  private lockManager;
158
224
  private dbPath;
159
225
  private activeTransactions;
226
+ private finishedTransactions;
160
227
  /**
161
- * In-memory pending-writes index per active transaction. This is the performant
162
- * replacement for the previous per-op full-WAL re-read + filter. Each write/read
163
- * within a transaction reads/writes this map directly in O(1) instead of replaying
164
- * the entire WAL on every operation.
165
- *
228
+ * In-memory pending-writes index per active transaction.
166
229
  * Keyed by transactionId -> key -> { beforeImage, afterImage, op }
167
230
  */
168
231
  private pendingWrites;
169
232
  /**
170
233
  * Compaction cadence: every COMMIT_INTERVAL commits, if there are no active
171
234
  * transactions, we rotate the WAL into an archive and start a fresh log.
172
- * This bounds WAL size without rewriting it on every commit.
173
235
  */
174
236
  private readonly COMMIT_INTERVAL;
175
237
  private commitCount;
176
- /**
177
- * Monotonic counter + PID + per-process random salt. The old counter-only
178
- * scheme reused IDs after a restart (txCounter resets to 0), so a WAL
179
- * containing t<oldPid>_0 COMMIT and a new uncommitted t<newPid>_0 would
180
- * collide — recovery treated the new writes as committed (data loss / ghost
181
- * docs). Including a per-process 3-byte random + timestamp makes IDs
182
- * unique across restarts with zero hot-path cost (one random draw at
183
- * construction, then cheap counter).
184
- */
185
238
  private txCounter;
186
239
  private readonly pid;
187
240
  private readonly txSalt;
188
241
  /**
189
242
  * Deferred data-file write buffer. On commit, committed data moves here instead
190
243
  * of being written to data files immediately. A background timer flushes this
191
- * to disk every `dataFlushIntervalMs` (default 50ms). This is the SQLite WAL-mode
192
- * architecture: the WAL is the durable copy; data files are a checkpointed cache
193
- * rebuilt via redo on crash recovery.
244
+ * to disk every `dataFlushIntervalMs` (default 50ms).
194
245
  */
195
246
  private committedBuffer;
196
247
  private dataFlushTimer?;
197
248
  private readonly DATA_FLUSH_INTERVAL_MS;
198
249
  /**
199
- * Dirty-key tracker for incremental cloud checkpoints (roadmap4.md).
200
- * Every committed write/delete marks its key here at commit time — O(1) per
201
- * committed op, no I/O, no locks on the hot path. The backup layer drains
202
- * the set via takeDirtyKeys() to upload ONLY changed documents; the set is
203
- * cleared atomically on take. Unbounded growth is bounded by checkpoint
204
- * cadence (drained on every live checkpoint), and even with no checkpoints
205
- * each entry is just the key string (~50-100 bytes).
250
+ * Version-consistent dirty-key tracker for cloud checkpoints.
251
+ * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
206
252
  */
207
253
  private dirtyKeys;
254
+ private activeSnapshotLsn;
255
+ private snapshotBeforeImages;
256
+ private lastCommittedLSN;
257
+ private degraded;
258
+ private lastMaintenanceError;
259
+ isDegraded(): boolean;
260
+ getLastMaintenanceError(): Error | null;
261
+ getLastCommittedLSN(): number;
262
+ peekDirtyKeys(upToLsn?: number): Map<string, DirtyEntry>;
263
+ acknowledgeDirtyKeys(acked: Iterable<{
264
+ key: string;
265
+ lsn: number;
266
+ }>): void;
267
+ getDirtyKeyCount(): number;
208
268
  /**
209
- * Atomically drain the dirty-key set: returns the keys changed since the
210
- * last take and clears the set in one swap. Used by incremental checkpoints.
269
+ * Creates an isolated logical snapshot handle as of upToLsn.
270
+ * Enforces single-active-snapshot invariant and provides explicit close().
211
271
  */
212
- takeDirtyKeys(): Set<string>;
213
- /** Current dirty-key count (diagnostics/status). */
214
- getDirtyKeyCount(): number;
272
+ beginSnapshot(upToLsn: number): SnapshotHandle;
273
+ /**
274
+ * Streams a version-consistent logical snapshot of the database as of upToLsn.
275
+ * Fully protected against concurrent writes via Copy-On-Write snapshotBeforeImages.
276
+ */
277
+ snapshotFiles(upToLsn: number): AsyncGenerator<{
278
+ key: string;
279
+ lsn: number;
280
+ state: 'present' | 'deleted';
281
+ data?: JsonValue;
282
+ }>;
283
+ private _streamSnapshotFiles;
215
284
  private synchronous;
216
- constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number);
285
+ private checkpointBatchSize;
286
+ constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number);
217
287
  private fsyncFile;
218
288
  private fsyncDir;
219
289
  private initializeStorage;
@@ -305,11 +375,21 @@ export declare class ACIDStorageEngine {
305
375
  * disk). Used by the get() fast path in index.ts.
306
376
  */
307
377
  getCommittedData(key: string): any | undefined;
378
+ isKeyLocked(key: string): boolean;
379
+ isKeyInCommittedBuffer(key: string): boolean;
380
+ /**
381
+ * Truncate WAL log with strict precondition checks.
382
+ * Enforces that no active transactions exist, no pending uncommitted writes exist,
383
+ * committedBuffer is drained, flushes committed buffer to disk, writes a CHECKPOINT,
384
+ * and safely truncates the WAL.
385
+ */
386
+ truncateLog(): void;
308
387
  /**
309
- * Force-flush the committedBuffer to data files. Called by the background timer
310
- * and by forceCheckpoint(). Writes each buffered entry to its data file using
311
- * the atomic temp→rename pattern, then clears the buffer.
388
+ * Flush the committedBuffer to data files. Called by the background timer
389
+ * and by forceCheckpoint(). Writes buffered entries to data files using
390
+ * the atomic temp→rename pattern. When unforced, processes in chunks to prevent
391
+ * event loop starvation under sustained heavy write loads.
312
392
  */
313
- flushCommittedBuffer(forceFsync?: boolean): void;
393
+ flushCommittedBuffer(forceFsync?: boolean, maxBatch?: number): void;
314
394
  destroy(): void;
315
395
  }