tero 0.0.9 → 0.0.12

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Friday Candour (fridaycandours@gmail.com) / CodeDynasty
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -53,18 +53,18 @@ await db.remove('user1');
53
53
 
54
54
  ## ACID transactions
55
55
 
56
- Every convenience method (`create`, `get`, `update`, `remove`) is auto-wrapped in a transaction. For multi-step operations, use explicit transactions:
56
+ 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:
57
57
 
58
58
  ```javascript
59
59
  const tx = db.beginTransaction();
60
60
 
61
61
  try {
62
- await db.write(tx, 'account1', { balance: 900 });
63
- await db.write(tx, 'account2', { balance: 1100 });
64
- const a = await db.read(tx, 'account1'); // reads pending state within the tx
65
- await db.commit(tx);
62
+ await tx.update('account1', { balance: 900 });
63
+ await tx.update('account2', { balance: 1100 });
64
+ const a = await tx.read('account1'); // reads pending state within the tx
65
+ await tx.commit();
66
66
  } catch (error) {
67
- await db.rollback(tx);
67
+ await tx.rollback();
68
68
  throw error;
69
69
  }
70
70
  ```
@@ -250,23 +250,25 @@ Keys are validated to prevent path traversal (`..`, `/`, `\` are rejected).
250
250
 
251
251
  ```javascript
252
252
  const db = new Tero({
253
- directory: './data', // default: 'TeroDB'
254
- cacheSize: 1000, // default: 100, capped at 1000
255
- backup: { ... }, // optional: install a BackupConfig at construction
256
- hydrateOnStartup: { ... }, // optional: v2 hydration before engine init
253
+ directory: './data', // default: 'TeroDB'
254
+ cacheSize: 1000, // default: 100, configurable LRU capacity
255
+ synchronous: 'full', // 'full' (default, fsync per commit), 'normal' (coalesced timer), or 'off'
256
+ fileLock: true, // default: true, cross-process .lock directory guard
257
+ backup: { ... }, // optional: install a BackupConfig at construction
258
+ hydrateOnStartup: { ... },// optional: v2 hydration before engine init
257
259
  });
258
260
  ```
259
261
 
260
262
  ## Testing
261
263
 
262
264
  ```bash
263
- npm run build # tsc + full test suite
264
- npm run test # full suite (includes the ~60s benchmark)
265
- npm run test:production # ACID + schema + transactions + perf
266
- npm run test:backup # backup + scheduling + retention
267
- npm run test:schema # schema validation
268
- npm run test:legacy # legacy suite
269
- node local_tests/v2-test.js # v2: hydrate + bucket backup surface
265
+ npm run build # compile TypeScript
266
+ npm run test # unit test suite
267
+ npm run test:production # comprehensive ACID production test suite (54/54)
268
+ npm run ci # CI suite (unit tests + production test suite)
269
+ npm run verify # pre-flight verification
270
+ npm run bench:quick # quick engine benchmark suite
271
+ npm run bench:live # live bucket S3 benchmark suite
270
272
  ```
271
273
 
272
274
  ### Testing S3 live backup locally (MinIO)
@@ -78,6 +78,11 @@ export declare class WriteAheadLog {
78
78
  * Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
79
79
  * and write a CHECKPOINT entry at the head of the new log. Old archives beyond
80
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).
81
86
  */
82
87
  rotateLog(): void;
83
88
  /**
@@ -118,11 +123,9 @@ export declare class LockManager {
118
123
  private processWaitQueue;
119
124
  private removeLockRequest;
120
125
  /**
121
- * Release only the locks the given transaction actually holds. O(heldKeys) instead
122
- * of O(allLocks) — the previous releaseAllLocks iterated every lock in the system
123
- * on every commit, which dominated commit latency at scale.
126
+ * Release locks and remove pending wait-queue requests for a transaction.
124
127
  */
125
- releaseLocksForTx(transactionId: string, heldKeys: Set<string>): void;
128
+ releaseLocksForTx(transactionId: string, heldKeys: Set<string>, waitingKeys?: Set<string>): void;
126
129
  releaseAllLocks(transactionId: string): void;
127
130
  detectDeadlock(): string[];
128
131
  }
@@ -171,14 +174,17 @@ export declare class ACIDStorageEngine {
171
174
  private readonly COMMIT_INTERVAL;
172
175
  private commitCount;
173
176
  /**
174
- * Monotonic transaction counter + PID. Replaces randomUUID() in the hot path —
175
- * a counter increment is ~10x faster than a crypto-random 128-bit UUID generation.
176
- * Transaction IDs only need to be unique within a single process lifetime; on
177
- * crash recovery the WAL is replayed and old txIds are resolved, so a fresh
178
- * counter starting at 0 cannot collide with stale entries.
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).
179
184
  */
180
185
  private txCounter;
181
186
  private readonly pid;
187
+ private readonly txSalt;
182
188
  /**
183
189
  * Deferred data-file write buffer. On commit, committed data moves here instead
184
190
  * of being written to data files immediately. A background timer flushes this
@@ -206,7 +212,10 @@ export declare class ACIDStorageEngine {
206
212
  takeDirtyKeys(): Set<string>;
207
213
  /** Current dirty-key count (diagnostics/status). */
208
214
  getDirtyKeyCount(): number;
215
+ private synchronous;
209
216
  constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number);
217
+ private fsyncFile;
218
+ private fsyncDir;
210
219
  private initializeStorage;
211
220
  private performCrashRecovery;
212
221
  private redoOperation;
@@ -221,6 +230,7 @@ export declare class ACIDStorageEngine {
221
230
  * per commit, leaving only the WAL fsync as the single durability barrier.
222
231
  */
223
232
  private atomicWriteFile;
233
+ private static readonly MAX_ACTIVE_TXNS;
224
234
  beginTransaction(): string;
225
235
  /**
226
236
  * Write data for a transaction. Returns `void` synchronously when the lock is
@@ -228,13 +238,24 @@ export declare class ACIDStorageEngine {
228
238
  * `Promise<void>` only when the lock is contended and we must wait in queue.
229
239
  * Callers should check: `if (result !== undefined) await result;`
230
240
  */
231
- write(transactionId: string, key: string, data: any): void | Promise<void>;
241
+ write(transactionId: string, key: string, data: any, cachedBeforeImage?: any): void | Promise<void>;
232
242
  /**
233
243
  * Synchronous write work — called from write() after the lock is acquired.
234
244
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
235
245
  * pendingWrites tracking. No syscalls, no Promises.
236
246
  */
237
247
  private doWriteSync;
248
+ /**
249
+ * Acquire an exclusive lock without writing. Used for SELECT FOR UPDATE
250
+ * / transferMoney: acquire locks in global sorted order BEFORE reading
251
+ * so reads are serializable and the read→write upgrade never deadlocks.
252
+ * Same sync fast-path pattern as write/read — returns void or Promise.
253
+ */
254
+ acquireExclusiveLock(transactionId: string, key: string): void | Promise<void>;
255
+ /**
256
+ * Acquire a shared lock for a transaction.
257
+ */
258
+ acquireSharedLock(transactionId: string, key: string): void | Promise<void>;
238
259
  /**
239
260
  * Read data for a transaction. Same pattern as write: returns the data
240
261
  * synchronously when the lock is uncontended, returns a Promise only when
@@ -273,11 +294,6 @@ export declare class ACIDStorageEngine {
273
294
  * archived segments to the client's bucket, and to drive snapshot+replay recovery).
274
295
  */
275
296
  getWAL(): WriteAheadLog;
276
- /**
277
- * Check if a key has committed-but-unflushed data. Returns the data if present
278
- * in committedBuffer, or `undefined` if not in the buffer (caller should check
279
- * disk). Used by the get() fast path in index.ts.
280
- */
281
297
  /**
282
298
  * Return the pending afterImage for a key in an active transaction's pendingWrites.
283
299
  * Used by index.ts write() to cache the MERGED result, not the raw user data.
@@ -294,6 +310,6 @@ export declare class ACIDStorageEngine {
294
310
  * and by forceCheckpoint(). Writes each buffered entry to its data file using
295
311
  * the atomic temp→rename pattern, then clears the buffer.
296
312
  */
297
- flushCommittedBuffer(): void;
313
+ flushCommittedBuffer(forceFsync?: boolean): void;
298
314
  destroy(): void;
299
315
  }