tero 0.0.10 → 0.0.13
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 +21 -0
- package/README.md +19 -17
- package/dist/acid-engine.d.ts +11 -10
- package/dist/acid-engine.js +169 -48
- package/dist/backup.d.ts +18 -2
- package/dist/backup.js +168 -33
- package/dist/index.d.ts +35 -10
- package/dist/index.js +308 -151
- package/dist/recovery.d.ts +3 -2
- package/dist/recovery.js +61 -9
- package/package.json +31 -13
package/dist/index.js
CHANGED
|
@@ -15,19 +15,21 @@ import QuickLRU from "quick-lru";
|
|
|
15
15
|
*/
|
|
16
16
|
const PROCESS_UNIQUE = randomBytes(5);
|
|
17
17
|
let idCounter = ~~(Math.random() * 0xffffff);
|
|
18
|
+
const MAX_DOCUMENT_DEPTH = 32;
|
|
19
|
+
const MAX_DOCUMENT_SIZE = 16 * 1024 * 1024; // 16MB max document size limit
|
|
18
20
|
/**
|
|
19
21
|
* Clone for cache safety — hot-path optimized.
|
|
20
22
|
* Flat JSON docs (no nested objects/arrays) are shallow-copied via spread
|
|
21
23
|
* (~0.04µs) vs ~2.7µs for structuredClone — 60× faster. Bench tiny docs
|
|
22
24
|
* are flat, so hot cached `get()` stays near 500k ops/s instead of 85k.
|
|
23
|
-
* Nested docs
|
|
24
|
-
* Cloning on store *and* on return guarantees `doc = await get(k); doc.x=evil`
|
|
25
|
-
* cannot poison the LRU, and `data = {nested:{a:1}}; create(k,data); data.nested.a=2`
|
|
26
|
-
* cannot poison pendingWrites.
|
|
25
|
+
* Nested docs are recursively cloned with depth and cycle guards.
|
|
27
26
|
*/
|
|
28
|
-
function deepClone(value) {
|
|
27
|
+
function deepClone(value, depth = 0, seen = new WeakSet()) {
|
|
29
28
|
if (value === null || typeof value !== 'object')
|
|
30
29
|
return value;
|
|
30
|
+
if (depth > MAX_DOCUMENT_DEPTH) {
|
|
31
|
+
throw new Error(`Document depth exceeds maximum allowed depth (${MAX_DOCUMENT_DEPTH})`);
|
|
32
|
+
}
|
|
31
33
|
if (!Array.isArray(value)) {
|
|
32
34
|
let hasNested = false;
|
|
33
35
|
for (const k in value) {
|
|
@@ -41,13 +43,18 @@ function deepClone(value) {
|
|
|
41
43
|
}
|
|
42
44
|
if (!hasNested)
|
|
43
45
|
return { ...value };
|
|
46
|
+
if (seen.has(value)) {
|
|
47
|
+
throw new Error('Circular reference detected in document');
|
|
48
|
+
}
|
|
49
|
+
seen.add(value);
|
|
44
50
|
const copy = {};
|
|
45
51
|
for (const k in value) {
|
|
46
52
|
if (Object.prototype.hasOwnProperty.call(value, k)) {
|
|
47
53
|
const v = value[k];
|
|
48
|
-
copy[k] = (v !== null && typeof v === 'object') ? deepClone(v) : v;
|
|
54
|
+
copy[k] = (v !== null && typeof v === 'object') ? deepClone(v, depth + 1, seen) : v;
|
|
49
55
|
}
|
|
50
56
|
}
|
|
57
|
+
seen.delete(value);
|
|
51
58
|
return copy;
|
|
52
59
|
}
|
|
53
60
|
let hasNested = false;
|
|
@@ -61,27 +68,28 @@ function deepClone(value) {
|
|
|
61
68
|
}
|
|
62
69
|
if (!hasNested)
|
|
63
70
|
return [...value];
|
|
71
|
+
if (seen.has(value)) {
|
|
72
|
+
throw new Error('Circular reference detected in document');
|
|
73
|
+
}
|
|
74
|
+
seen.add(value);
|
|
64
75
|
const arr = new Array(len);
|
|
65
76
|
for (let i = 0; i < len; i++) {
|
|
66
77
|
const el = value[i];
|
|
67
|
-
arr[i] = (el !== null && typeof el === 'object') ? deepClone(el) : el;
|
|
78
|
+
arr[i] = (el !== null && typeof el === 'object') ? deepClone(el, depth + 1, seen) : el;
|
|
68
79
|
}
|
|
80
|
+
seen.delete(value);
|
|
69
81
|
return arr;
|
|
70
82
|
}
|
|
71
83
|
/**
|
|
72
|
-
* Validate a user-supplied data directory name.
|
|
73
|
-
* were silently stripped ('my db' quietly became 'mydb' — users wrote to the
|
|
74
|
-
* wrong directory without knowing). Now: throw with an actionable message.
|
|
75
|
-
* Allowed: letters, digits, '_', '-', '/' separators; absolute paths are
|
|
76
|
-
* accepted as an explicit user choice; '..' segments always rejected; a
|
|
77
|
-
* RELATIVE path must resolve inside the process working directory.
|
|
78
|
-
* Called once at construction — zero hot-path cost. Returns the resolved
|
|
79
|
-
* absolute path so all downstream joins are unambiguous.
|
|
84
|
+
* Validate a user-supplied data directory name.
|
|
80
85
|
*/
|
|
81
86
|
function validateDirectory(raw) {
|
|
82
87
|
const dir = raw.trim();
|
|
83
88
|
if (!dir)
|
|
84
89
|
throw new Error('Directory name cannot be empty.');
|
|
90
|
+
if (dir === '.' || dir === './') {
|
|
91
|
+
throw new Error(`Invalid directory '${raw}': cannot use working directory root as database directory. Specify a named directory.`);
|
|
92
|
+
}
|
|
85
93
|
if (/[^A-Za-z0-9_\-./]/.test(dir)) {
|
|
86
94
|
throw new Error(`Invalid directory '${raw}': directory names may only contain letters, digits, '_', '-', '.' and '/' path separators.`);
|
|
87
95
|
}
|
|
@@ -109,6 +117,8 @@ export class Transaction {
|
|
|
109
117
|
* including deletes. One array push per op: O(1), off the engine hot path. */
|
|
110
118
|
operationsLog = [];
|
|
111
119
|
destroyed = false;
|
|
120
|
+
committed = false;
|
|
121
|
+
rolledBack = false;
|
|
112
122
|
timeoutTimer;
|
|
113
123
|
constructor(id, db, options) {
|
|
114
124
|
this.id = id;
|
|
@@ -117,34 +127,69 @@ export class Transaction {
|
|
|
117
127
|
if (options?.timeout) {
|
|
118
128
|
this.timeoutTimer = setTimeout(() => {
|
|
119
129
|
this.destroyed = true;
|
|
130
|
+
this.rolledBack = true;
|
|
120
131
|
this.db._rollbackRaw(this.id).catch(() => { });
|
|
121
132
|
}, options.timeout);
|
|
133
|
+
this.timeoutTimer.unref?.();
|
|
122
134
|
}
|
|
123
135
|
}
|
|
124
136
|
getId() {
|
|
125
137
|
return this.id;
|
|
126
138
|
}
|
|
127
139
|
isActive() {
|
|
128
|
-
if (this.destroyed)
|
|
140
|
+
if (this.destroyed || this.committed || this.rolledBack)
|
|
129
141
|
return false;
|
|
130
142
|
return this.db.getActiveTransactions().includes(this.id);
|
|
131
143
|
}
|
|
132
144
|
isRolledBack() {
|
|
133
|
-
|
|
145
|
+
if (this.rolledBack)
|
|
146
|
+
return true;
|
|
147
|
+
if (this.destroyed)
|
|
148
|
+
return true;
|
|
149
|
+
const status = this.db._getTxStatus(this.id);
|
|
150
|
+
if (status === 'aborted') {
|
|
151
|
+
this.rolledBack = true;
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
isCommitted() {
|
|
157
|
+
if (this.committed)
|
|
158
|
+
return true;
|
|
159
|
+
return this.db._getTxStatus(this.id) === 'committed';
|
|
134
160
|
}
|
|
135
161
|
_checkActive() {
|
|
136
162
|
if (this.destroyed)
|
|
137
163
|
throw new Error('Transaction has been destroyed');
|
|
164
|
+
if (this.committed)
|
|
165
|
+
throw new Error('Transaction has already been committed');
|
|
166
|
+
if (this.rolledBack)
|
|
167
|
+
throw new Error('Transaction has been rolled back');
|
|
138
168
|
const status = this.db._getTxStatus(this.id);
|
|
139
|
-
if (status === 'committed')
|
|
169
|
+
if (status === 'committed') {
|
|
170
|
+
this.committed = true;
|
|
140
171
|
throw new Error('Transaction has already been committed');
|
|
141
|
-
|
|
172
|
+
}
|
|
173
|
+
if (status === 'aborted') {
|
|
174
|
+
this.rolledBack = true;
|
|
142
175
|
throw new Error('Transaction has been rolled back');
|
|
143
|
-
|
|
176
|
+
}
|
|
177
|
+
if (status === 'not_found') {
|
|
178
|
+
// Engine GC'd the transaction (after commit/rollback). Use local flags to give precise error
|
|
179
|
+
if (this.committed)
|
|
180
|
+
throw new Error('Transaction has already been committed');
|
|
181
|
+
if (this.rolledBack)
|
|
182
|
+
throw new Error('Transaction has been rolled back');
|
|
144
183
|
throw new Error('Transaction is not active');
|
|
184
|
+
}
|
|
145
185
|
}
|
|
146
186
|
async create(key, initialData) {
|
|
147
187
|
this._checkActive();
|
|
188
|
+
// Acquire exclusive lock BEFORE existence check to close TOCTOU
|
|
189
|
+
// (two concurrent create('same') both passed exists() before either held the lock)
|
|
190
|
+
const lockRes = this.db.acidEngine.acquireExclusiveLock(this.id, key);
|
|
191
|
+
if (lockRes instanceof Promise)
|
|
192
|
+
await lockRes;
|
|
148
193
|
if (this.db.exists(key))
|
|
149
194
|
throw new Error(`Document '${key}' already exists`);
|
|
150
195
|
await this.db._writeRaw(this.id, key, initialData || {});
|
|
@@ -163,11 +208,30 @@ export class Transaction {
|
|
|
163
208
|
this.opCount++;
|
|
164
209
|
this.operationsLog.push({ key, operation: 'delete' });
|
|
165
210
|
}
|
|
166
|
-
|
|
211
|
+
/**
|
|
212
|
+
* Read document within this transaction.
|
|
213
|
+
* @param options.lock - 'shared' (default) or 'exclusive' (SELECT FOR UPDATE)
|
|
214
|
+
*/
|
|
215
|
+
async get(key, options) {
|
|
216
|
+
this._checkActive();
|
|
217
|
+
return await this.db.read(this.id, key, options);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Alias for get() with explicit locking semantics.
|
|
221
|
+
* @param options.lock - 'shared' (default) or 'exclusive' (SELECT FOR UPDATE)
|
|
222
|
+
*/
|
|
223
|
+
async read(key, options) {
|
|
167
224
|
this._checkActive();
|
|
168
|
-
return await this.db.
|
|
225
|
+
return await this.db.read(this.id, key, options);
|
|
169
226
|
}
|
|
170
227
|
getState() {
|
|
228
|
+
if (this.committed)
|
|
229
|
+
return { status: 'committed', operations: [...this.operationsLog], startTime: this.startTime };
|
|
230
|
+
if (this.rolledBack || this.destroyed) {
|
|
231
|
+
const s = this.db._getTxStatus(this.id);
|
|
232
|
+
if (s === 'aborted' || this.rolledBack)
|
|
233
|
+
return { status: 'rolled_back', operations: [...this.operationsLog], startTime: this.startTime };
|
|
234
|
+
}
|
|
171
235
|
const status = this.db._getTxStatus(this.id);
|
|
172
236
|
return {
|
|
173
237
|
status: status === 'active' ? 'active' : (status === 'committed' ? 'committed' : 'rolled_back'),
|
|
@@ -178,11 +242,27 @@ export class Transaction {
|
|
|
178
242
|
getOperationCount() {
|
|
179
243
|
return this.opCount;
|
|
180
244
|
}
|
|
181
|
-
|
|
182
|
-
|
|
245
|
+
async commit() {
|
|
246
|
+
this._checkActive();
|
|
247
|
+
if (this.timeoutTimer)
|
|
248
|
+
clearTimeout(this.timeoutTimer);
|
|
249
|
+
await this.db.commit(this.id);
|
|
250
|
+
this.committed = true;
|
|
251
|
+
}
|
|
252
|
+
async abort() {
|
|
253
|
+
if (this.destroyed)
|
|
254
|
+
return;
|
|
255
|
+
if (this.timeoutTimer)
|
|
256
|
+
clearTimeout(this.timeoutTimer);
|
|
257
|
+
await this.db._rollbackRaw(this.id);
|
|
258
|
+
this.rolledBack = true;
|
|
259
|
+
}
|
|
260
|
+
async rollback() {
|
|
261
|
+
await this.abort();
|
|
183
262
|
}
|
|
184
263
|
destroy() {
|
|
185
264
|
this.destroyed = true;
|
|
265
|
+
this.rolledBack = true;
|
|
186
266
|
if (this.timeoutTimer)
|
|
187
267
|
clearTimeout(this.timeoutTimer);
|
|
188
268
|
this.db._rollbackRaw(this.id).catch(() => { });
|
|
@@ -225,8 +305,14 @@ export class Tero {
|
|
|
225
305
|
if (config?.liveBackup && !config.backup?.cloudStorage) {
|
|
226
306
|
throw new Error('config.liveBackup requires config.backup with cloudStorage configured — live backup needs a bucket.');
|
|
227
307
|
}
|
|
228
|
-
const rawDirectory = config?.
|
|
308
|
+
const rawDirectory = config?.directory;
|
|
229
309
|
const { cacheSize, synchronous, commitIntervalMs, dataFlushIntervalMs } = config || {};
|
|
310
|
+
if (synchronous && !['full', 'normal', 'off'].includes(synchronous)) {
|
|
311
|
+
throw new Error(`Invalid synchronous mode '${synchronous}'. Expected 'full', 'normal', or 'off'.`);
|
|
312
|
+
}
|
|
313
|
+
if (synchronous === 'off' && (process.env.TERO_ALLOW_UNSAFE_OFF !== '1' && process.env.NODE_ENV !== 'test' && process.env.NODE_ENV !== 'development')) {
|
|
314
|
+
throw new Error("synchronous='off' is not allowed — it disables all fsync and will lose data on crash. Use 'full' or 'normal'. Set TERO_ALLOW_UNSAFE_OFF=1 to force in benchmarks.");
|
|
315
|
+
}
|
|
230
316
|
if (typeof rawDirectory === "string" && rawDirectory.trim()) {
|
|
231
317
|
// Throw on illegal characters instead of silently stripping them —
|
|
232
318
|
// 'my db' used to quietly become 'mydb' and users wrote to the wrong
|
|
@@ -234,14 +320,13 @@ export class Tero {
|
|
|
234
320
|
this.teroDirectory = validateDirectory(rawDirectory);
|
|
235
321
|
}
|
|
236
322
|
if (typeof cacheSize === "number" && cacheSize > 0) {
|
|
237
|
-
this.cacheSize =
|
|
323
|
+
this.cacheSize = cacheSize;
|
|
238
324
|
}
|
|
239
325
|
// Create directories with proper error handling
|
|
240
326
|
this.initializeDirectories();
|
|
241
|
-
//
|
|
242
|
-
// same data directory concurrently (
|
|
243
|
-
|
|
244
|
-
if (config?.fileLock) {
|
|
327
|
+
// Cross-process lock enabled by default — prevents two processes from opening the
|
|
328
|
+
// same data directory concurrently (Google Pillar #2). Set fileLock: false to disable.
|
|
329
|
+
if (config?.fileLock !== false) {
|
|
245
330
|
this.acquireFileLock();
|
|
246
331
|
}
|
|
247
332
|
// Initialize QuickLRU cache
|
|
@@ -289,7 +374,7 @@ export class Tero {
|
|
|
289
374
|
// applies. The old strip-regex diverged ('my db' hydrated into 'mydb'
|
|
290
375
|
// while `new Tero` resolved the real path below), causing split-brain
|
|
291
376
|
// directories where hydrated data became invisible to the engine.
|
|
292
|
-
const rawDirectory = config?.
|
|
377
|
+
const rawDirectory = config?.directory || 'TeroDB';
|
|
293
378
|
const teroDirectory = validateDirectory(rawDirectory);
|
|
294
379
|
if (!existsSync(teroDirectory)) {
|
|
295
380
|
mkdirSync(teroDirectory, { recursive: true });
|
|
@@ -303,35 +388,39 @@ export class Tero {
|
|
|
303
388
|
mode: hydrate.mode === 'all' ? 'all' : 'missing',
|
|
304
389
|
continueOnError: hydrate.continueOnError ?? true,
|
|
305
390
|
});
|
|
391
|
+
let hydrateCancelled = false;
|
|
306
392
|
const hydrateWork = async () => {
|
|
307
393
|
try {
|
|
308
394
|
const mode = hydrate.mode ?? 'missing';
|
|
395
|
+
if (hydrateCancelled)
|
|
396
|
+
return;
|
|
309
397
|
if (mode === 'all') {
|
|
310
|
-
const r = await recovery.recoverIndividualFiles();
|
|
398
|
+
const r = await recovery.recoverIndividualFiles(undefined, () => hydrateCancelled);
|
|
311
399
|
if (!r.success && r.failed.length > 0) { /* continue */ }
|
|
312
400
|
}
|
|
313
401
|
else if (mode === 'snapshot') {
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
// fill gaps with individual file recovery for any data written since the
|
|
317
|
-
// snapshot's checkpoint. This is the Google-recommended hydration pattern:
|
|
318
|
-
// one bulk download instead of sequential individual S3 GETs.
|
|
402
|
+
if (hydrateCancelled)
|
|
403
|
+
return;
|
|
319
404
|
try {
|
|
320
405
|
const snapshotResult = await recovery.recoverFromArchive();
|
|
406
|
+
if (hydrateCancelled)
|
|
407
|
+
return;
|
|
321
408
|
if (!snapshotResult.success) {
|
|
322
|
-
|
|
323
|
-
|
|
409
|
+
if (hydrateCancelled)
|
|
410
|
+
return;
|
|
411
|
+
const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
|
|
324
412
|
if (!r.success && r.failed.length > 0) { /* continue */ }
|
|
325
413
|
}
|
|
326
414
|
}
|
|
327
415
|
catch {
|
|
328
|
-
|
|
329
|
-
|
|
416
|
+
if (hydrateCancelled)
|
|
417
|
+
return;
|
|
418
|
+
const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
|
|
330
419
|
if (!r.success && r.failed.length > 0) { /* continue */ }
|
|
331
420
|
}
|
|
332
421
|
}
|
|
333
422
|
else {
|
|
334
|
-
const r = await recovery.recoverMissingFiles();
|
|
423
|
+
const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
|
|
335
424
|
if (!r.success && r.failed.length > 0) { /* continue */ }
|
|
336
425
|
}
|
|
337
426
|
}
|
|
@@ -339,15 +428,11 @@ export class Tero {
|
|
|
339
428
|
// Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
|
|
340
429
|
}
|
|
341
430
|
};
|
|
342
|
-
// HydrateConfig.timeout was declared but never enforced — a hung bucket GET
|
|
343
|
-
// could block engine construction forever. Race the hydration against the
|
|
344
|
-
// deadline; on expiry the engine proceeds with whatever local state exists
|
|
345
|
-
// (same non-fatal contract as a hydration failure).
|
|
346
431
|
const timeoutMs = hydrate.timeout;
|
|
347
432
|
if (typeof timeoutMs === 'number' && timeoutMs > 0) {
|
|
348
433
|
await Promise.race([
|
|
349
434
|
hydrateWork(),
|
|
350
|
-
new Promise((resolve) => { const t = setTimeout(resolve, timeoutMs); t.unref?.(); }),
|
|
435
|
+
new Promise((resolve) => { const t = setTimeout(() => { hydrateCancelled = true; resolve(); }, timeoutMs); t.unref?.(); }),
|
|
351
436
|
]);
|
|
352
437
|
}
|
|
353
438
|
else {
|
|
@@ -374,19 +459,39 @@ export class Tero {
|
|
|
374
459
|
throw new Error('Data recovery not configured. Call configureDataRecovery() or pass hydrateOnStartup in config.');
|
|
375
460
|
}
|
|
376
461
|
const mode = options?.mode ?? 'missing';
|
|
377
|
-
|
|
378
|
-
|
|
462
|
+
const timeoutMs = options?.timeout;
|
|
463
|
+
let cancelled = false;
|
|
464
|
+
let timeoutTimer;
|
|
465
|
+
if (typeof timeoutMs === 'number' && timeoutMs > 0) {
|
|
466
|
+
timeoutTimer = setTimeout(() => { cancelled = true; }, timeoutMs);
|
|
467
|
+
timeoutTimer.unref?.();
|
|
379
468
|
}
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
469
|
+
try {
|
|
470
|
+
if (cancelled)
|
|
471
|
+
throw new Error(`Hydrate timed out after ${timeoutMs}ms`);
|
|
472
|
+
if (mode === 'all') {
|
|
473
|
+
return await recovery.recoverIndividualFiles(undefined, () => cancelled);
|
|
383
474
|
}
|
|
384
|
-
|
|
385
|
-
|
|
475
|
+
else if (mode === 'snapshot') {
|
|
476
|
+
try {
|
|
477
|
+
const r = await recovery.recoverFromArchive();
|
|
478
|
+
if (cancelled)
|
|
479
|
+
throw new Error(`Hydrate timed out after ${timeoutMs}ms`);
|
|
480
|
+
return r;
|
|
481
|
+
}
|
|
482
|
+
catch (e) {
|
|
483
|
+
if (cancelled)
|
|
484
|
+
throw e;
|
|
485
|
+
return await recovery.recoverMissingFiles(() => cancelled);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
else {
|
|
489
|
+
return await recovery.recoverMissingFiles(() => cancelled);
|
|
386
490
|
}
|
|
387
491
|
}
|
|
388
|
-
|
|
389
|
-
|
|
492
|
+
finally {
|
|
493
|
+
if (timeoutTimer)
|
|
494
|
+
clearTimeout(timeoutTimer);
|
|
390
495
|
}
|
|
391
496
|
}
|
|
392
497
|
initializeDirectories() {
|
|
@@ -403,12 +508,16 @@ export class Tero {
|
|
|
403
508
|
throw new Error(`Failed to create directories: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
|
|
404
509
|
}
|
|
405
510
|
}
|
|
511
|
+
static MAX_KEY_LENGTH = 200;
|
|
406
512
|
validateKey(key) {
|
|
407
|
-
if (!key || typeof key !== 'string') {
|
|
513
|
+
if (!key || typeof key !== 'string' || !key.trim()) {
|
|
408
514
|
throw new Error('Key must be a non-empty string');
|
|
409
515
|
}
|
|
410
|
-
|
|
411
|
-
|
|
516
|
+
if (key.length > Tero.MAX_KEY_LENGTH) {
|
|
517
|
+
throw new Error(`Key exceeds maximum length of ${Tero.MAX_KEY_LENGTH} characters (got ${key.length})`);
|
|
518
|
+
}
|
|
519
|
+
// Sanitize key to prevent path traversal, hidden files, and illegal chars
|
|
520
|
+
if (key.includes('..') || key.includes('/') || key.includes('\\') || key.includes('\0') || key === '.' || key.startsWith('.')) {
|
|
412
521
|
throw new Error('Key contains invalid characters');
|
|
413
522
|
}
|
|
414
523
|
}
|
|
@@ -463,6 +572,13 @@ export class Tero {
|
|
|
463
572
|
if (data === undefined || data === null) {
|
|
464
573
|
throw new Error('Data cannot be null or undefined');
|
|
465
574
|
}
|
|
575
|
+
data = deepClone(data);
|
|
576
|
+
// Use byte length, not char length — 'é' is 1 char but 2 bytes UTF-8, emoji is 4 bytes
|
|
577
|
+
const jsonStr = JSON.stringify(data);
|
|
578
|
+
const byteLen = Buffer.byteLength(jsonStr, 'utf8');
|
|
579
|
+
if (byteLen > MAX_DOCUMENT_SIZE) {
|
|
580
|
+
throw new Error(`Document size exceeds maximum allowed size (${MAX_DOCUMENT_SIZE / (1024 * 1024)}MB) — got ${(byteLen / (1024 * 1024)).toFixed(2)}MB`);
|
|
581
|
+
}
|
|
466
582
|
// Perform schema validation if requested
|
|
467
583
|
if (options?.validate || options?.schemaName) {
|
|
468
584
|
const schemaName = options.schemaName || key;
|
|
@@ -501,11 +617,21 @@ export class Tero {
|
|
|
501
617
|
throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
|
|
502
618
|
}
|
|
503
619
|
}
|
|
504
|
-
async read(transactionId, key) {
|
|
620
|
+
async read(transactionId, key, options) {
|
|
505
621
|
try {
|
|
506
622
|
const txId = this._txId(transactionId);
|
|
507
623
|
this.validateKey(key);
|
|
508
624
|
this.cacheRequests++;
|
|
625
|
+
if (options?.lock === 'exclusive') {
|
|
626
|
+
const lockRes = this.acidEngine.acquireExclusiveLock(txId, key);
|
|
627
|
+
if (lockRes !== undefined && lockRes instanceof Promise)
|
|
628
|
+
await lockRes;
|
|
629
|
+
}
|
|
630
|
+
else {
|
|
631
|
+
const lockRes = this.acidEngine.acquireSharedLock(txId, key);
|
|
632
|
+
if (lockRes !== undefined && lockRes instanceof Promise)
|
|
633
|
+
await lockRes;
|
|
634
|
+
}
|
|
509
635
|
// Check cache first, but only if it's from the same transaction or committed
|
|
510
636
|
const cachedEntry = this.cache.get(key);
|
|
511
637
|
if (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) {
|
|
@@ -586,38 +712,46 @@ export class Tero {
|
|
|
586
712
|
// Convenience Methods (Auto-transaction)
|
|
587
713
|
async create(key, initialData, options) {
|
|
588
714
|
this.validateKey(key);
|
|
589
|
-
// Fast existence check: LRU hit → known exists. On LRU miss we MUST
|
|
590
|
-
// verify on disk — a miss means either "new key" OR "evicted / cold-boot
|
|
591
|
-
// / restarted node". The previous `size >= MAX` guard only checked at
|
|
592
|
-
// capacity, so a cold boot with 1 existing doc would never hit the
|
|
593
|
-
// fallback and would silently overwrite via merge.
|
|
594
|
-
if (this.knownKeys.has(key)) {
|
|
595
|
-
return false; // already exists
|
|
596
|
-
}
|
|
597
|
-
// Check committedBuffer before disk — a just-committed doc may not be
|
|
598
|
-
// flushed to its data file yet (deferred via committedBuffer, 50ms).
|
|
599
|
-
const pending = this.acidEngine.getCommittedData(key);
|
|
600
|
-
if (pending !== undefined) {
|
|
601
|
-
// committedBuffer says "exists" (write) or "deleted" (null tombstone)
|
|
602
|
-
if (pending !== null) {
|
|
603
|
-
this.knownKeys.set(key, true);
|
|
604
|
-
return false; // duplicate — already committed, not yet flushed
|
|
605
|
-
}
|
|
606
|
-
// tombstone → logically absent, fall through to allow re-create
|
|
607
|
-
}
|
|
608
|
-
else if (existsSync(this.keyToPath(key))) {
|
|
609
|
-
this.knownKeys.set(key, true); // re-pin; existed all along
|
|
610
|
-
return false;
|
|
611
|
-
}
|
|
612
715
|
const transactionId = this._beginTransaction();
|
|
613
716
|
try {
|
|
717
|
+
// Serialize existence check under an exclusive lock — two concurrent
|
|
718
|
+
// create('sameKey') must not both succeed (TOCTOU). Acquire exclusive
|
|
719
|
+
// first, then check committed state under that lock.
|
|
720
|
+
const lockRes = this.acidEngine.acquireExclusiveLock(transactionId, key);
|
|
721
|
+
if (lockRes instanceof Promise)
|
|
722
|
+
await lockRes;
|
|
723
|
+
// Check existence while holding the lock (covers knownKeys, committedBuffer, disk)
|
|
724
|
+
if (this.knownKeys.has(key)) {
|
|
725
|
+
await this.rollback(transactionId);
|
|
726
|
+
return false; // already exists
|
|
727
|
+
}
|
|
728
|
+
const pending = this.acidEngine.getCommittedData(key);
|
|
729
|
+
if (pending !== undefined) {
|
|
730
|
+
if (pending !== null) {
|
|
731
|
+
this.knownKeys.set(key, true);
|
|
732
|
+
await this.rollback(transactionId);
|
|
733
|
+
return false; // duplicate — already committed, not yet flushed
|
|
734
|
+
}
|
|
735
|
+
// tombstone → logically absent, fall through to allow re-create
|
|
736
|
+
}
|
|
737
|
+
else if (existsSync(this.keyToPath(key))) {
|
|
738
|
+
this.knownKeys.set(key, true); // re-pin; existed all along
|
|
739
|
+
await this.rollback(transactionId);
|
|
740
|
+
return false;
|
|
741
|
+
}
|
|
742
|
+
// Also check pendingWrites of other active tx via reading within tx
|
|
743
|
+
// (write will deepMerge, but for create we need empty). The exclusive
|
|
744
|
+
// lock guarantees no other tx is writing this key concurrently.
|
|
614
745
|
const result = await this.write(transactionId, key, initialData || {}, options);
|
|
615
746
|
await this.commit(transactionId);
|
|
616
747
|
this.knownKeys.set(key, true);
|
|
617
748
|
return result || true;
|
|
618
749
|
}
|
|
619
750
|
catch (error) {
|
|
620
|
-
|
|
751
|
+
try {
|
|
752
|
+
await this.rollback(transactionId);
|
|
753
|
+
}
|
|
754
|
+
catch { }
|
|
621
755
|
throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
|
|
622
756
|
}
|
|
623
757
|
}
|
|
@@ -634,8 +768,10 @@ export class Tero {
|
|
|
634
768
|
}
|
|
635
769
|
}
|
|
636
770
|
/**
|
|
637
|
-
* Read a document. Returns the document data on success, or `
|
|
638
|
-
* document is absent
|
|
771
|
+
* Read a document. Returns the document data on success, or `null` if the
|
|
772
|
+
* document is absent (use `=== null` to check). For backwards-compat, `false`
|
|
773
|
+
* is still treated as "not found" by callers, but new code should check for null.
|
|
774
|
+
* Throws for genuine errors (invalid key, corrupt file).
|
|
639
775
|
*
|
|
640
776
|
* Fast path (3 tiers, zero-syscall on hit):
|
|
641
777
|
* 1. LRU cache (committed entries) — pure memory, 900k+ ops/s
|
|
@@ -658,14 +794,14 @@ export class Tero {
|
|
|
658
794
|
const committed = this.acidEngine.getCommittedData(key);
|
|
659
795
|
if (committed !== undefined) {
|
|
660
796
|
if (committed === null)
|
|
661
|
-
return
|
|
797
|
+
return null;
|
|
662
798
|
this.updateCache(key, committed, undefined);
|
|
663
799
|
return deepClone(committed);
|
|
664
800
|
}
|
|
665
801
|
// 3. Slow path: read directly from disk (partitioned path; atomic rename = consistent)
|
|
666
802
|
const filePath = this.keyToPath(key);
|
|
667
803
|
if (!existsSync(filePath)) {
|
|
668
|
-
return
|
|
804
|
+
return null;
|
|
669
805
|
}
|
|
670
806
|
try {
|
|
671
807
|
const content = readFileSync(filePath, 'utf-8');
|
|
@@ -705,26 +841,22 @@ export class Tero {
|
|
|
705
841
|
return await this.remove(key);
|
|
706
842
|
}
|
|
707
843
|
exists(key) {
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
}
|
|
723
|
-
return false;
|
|
724
|
-
}
|
|
725
|
-
catch (error) {
|
|
726
|
-
return false;
|
|
844
|
+
// Fail-fast on invalid keys — don't mask programming errors as "not found"
|
|
845
|
+
this.validateKey(key);
|
|
846
|
+
// Fast path: in-memory set
|
|
847
|
+
if (this.knownKeys.has(key))
|
|
848
|
+
return true;
|
|
849
|
+
// Check committedBuffer for pending deletes (deferred writes may not have
|
|
850
|
+
// unlinked the file yet — a committed delete should appear as absent)
|
|
851
|
+
const committed = this.acidEngine.getCommittedData(key);
|
|
852
|
+
if (committed !== undefined)
|
|
853
|
+
return committed !== null;
|
|
854
|
+
// Slow path: check disk via partitioned path
|
|
855
|
+
if (existsSync(this.keyToPath(key))) {
|
|
856
|
+
this.knownKeys.set(key, true);
|
|
857
|
+
return true;
|
|
727
858
|
}
|
|
859
|
+
return false;
|
|
728
860
|
}
|
|
729
861
|
// Batch Operations
|
|
730
862
|
async batchWrite(operations, options) {
|
|
@@ -1116,9 +1248,9 @@ export class Tero {
|
|
|
1116
1248
|
}
|
|
1117
1249
|
/**
|
|
1118
1250
|
* Read a key locally; if absent locally, transparently recover it from the client's
|
|
1119
|
-
* bucket and cache the result. Returns the data, or `
|
|
1120
|
-
* doesn't exist on either side
|
|
1121
|
-
* don't silently mistake them for "not in cloud".
|
|
1251
|
+
* bucket and cache the result. Returns the data, or `null` if the key genuinely
|
|
1252
|
+
* doesn't exist on either side (returns `false` for backwards compat — both mean "not found").
|
|
1253
|
+
* Throws for real (auth/network) errors so callers don't silently mistake them for "not in cloud".
|
|
1122
1254
|
*
|
|
1123
1255
|
* Options:
|
|
1124
1256
|
* - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
|
|
@@ -1132,17 +1264,17 @@ export class Tero {
|
|
|
1132
1264
|
throw error;
|
|
1133
1265
|
}
|
|
1134
1266
|
const fallbackToCloud = options?.fallbackToCloud ?? true;
|
|
1135
|
-
// 1) Try local first.
|
|
1267
|
+
// 1) Try local first. Handle both null (new) and false (legacy) as "not found"
|
|
1136
1268
|
const localData = await this.get(key);
|
|
1137
|
-
if (localData !== false) {
|
|
1269
|
+
if (localData !== null && localData !== false) {
|
|
1138
1270
|
return localData;
|
|
1139
1271
|
}
|
|
1140
1272
|
// 2) Not local. Optionally fall back to cloud.
|
|
1141
1273
|
if (!fallbackToCloud)
|
|
1142
|
-
return
|
|
1274
|
+
return null;
|
|
1143
1275
|
if (!this.dataRecovery) {
|
|
1144
|
-
// No cloud configured — return
|
|
1145
|
-
return
|
|
1276
|
+
// No cloud configured — return null to keep "absent" semantics consistent with get().
|
|
1277
|
+
return null;
|
|
1146
1278
|
}
|
|
1147
1279
|
// 3) Best-effort cloud fetch. If it fails for any reason (auth, network, timeout,
|
|
1148
1280
|
// no such key), we don't crash the local read path — `getWithRecovery` is a
|
|
@@ -1152,7 +1284,7 @@ export class Tero {
|
|
|
1152
1284
|
try {
|
|
1153
1285
|
const recovered = await this.dataRecovery.recoverSingleFile(key);
|
|
1154
1286
|
if (!recovered) {
|
|
1155
|
-
return
|
|
1287
|
+
return null;
|
|
1156
1288
|
}
|
|
1157
1289
|
// Cache + return the freshly hydrated data.
|
|
1158
1290
|
// Re-run get() so the read goes through the cache + lint path.
|
|
@@ -1160,7 +1292,7 @@ export class Tero {
|
|
|
1160
1292
|
return await this.get(key);
|
|
1161
1293
|
}
|
|
1162
1294
|
catch (error) {
|
|
1163
|
-
return
|
|
1295
|
+
return null;
|
|
1164
1296
|
}
|
|
1165
1297
|
}
|
|
1166
1298
|
/**
|
|
@@ -1273,44 +1405,49 @@ export class Tero {
|
|
|
1273
1405
|
};
|
|
1274
1406
|
if (tryAcquire())
|
|
1275
1407
|
return;
|
|
1276
|
-
//
|
|
1277
|
-
let
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
const pidNum = parseInt(pid, 10);
|
|
1285
|
-
if (Number.isInteger(pidNum) && pidNum > 0 && pidNum !== process.pid) {
|
|
1286
|
-
let alive = true;
|
|
1287
|
-
try {
|
|
1288
|
-
process.kill(pidNum, 0);
|
|
1289
|
-
}
|
|
1290
|
-
catch (e) {
|
|
1291
|
-
// ESRCH = no such process → stale lock from a crashed holder.
|
|
1292
|
-
// EPERM = process exists but is owned by another user → treat as alive.
|
|
1293
|
-
alive = e?.code === 'EPERM';
|
|
1408
|
+
// Retry loop with bounded attempts for TOCTOU races during stale-lock reclamation
|
|
1409
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
1410
|
+
let pid = '?';
|
|
1411
|
+
if (existsSync(lockPath)) {
|
|
1412
|
+
try {
|
|
1413
|
+
pid = readFileSync(lockPath, 'utf-8').trim();
|
|
1414
|
+
}
|
|
1415
|
+
catch { /* unreadable */ }
|
|
1294
1416
|
}
|
|
1295
|
-
|
|
1296
|
-
|
|
1417
|
+
const pidNum = parseInt(pid, 10);
|
|
1418
|
+
if (Number.isInteger(pidNum) && pidNum > 0 && pidNum !== process.pid) {
|
|
1419
|
+
let alive = true;
|
|
1297
1420
|
try {
|
|
1298
|
-
|
|
1421
|
+
process.kill(pidNum, 0);
|
|
1422
|
+
}
|
|
1423
|
+
catch (e) {
|
|
1424
|
+
// ESRCH = no such process → stale lock from a crashed holder.
|
|
1425
|
+
// EPERM = process exists but is owned by another user → treat as alive.
|
|
1426
|
+
alive = e?.code === 'EPERM';
|
|
1427
|
+
}
|
|
1428
|
+
if (!alive) {
|
|
1429
|
+
// Reclaim the stale lock (crashed previous owner) and retry once.
|
|
1430
|
+
try {
|
|
1431
|
+
unlinkSync(lockPath);
|
|
1432
|
+
}
|
|
1433
|
+
catch { /* racing holder */ }
|
|
1434
|
+
if (tryAcquire())
|
|
1435
|
+
return;
|
|
1436
|
+
continue;
|
|
1437
|
+
}
|
|
1438
|
+
if (alive) {
|
|
1439
|
+
throw new Error(`Data directory '${this.teroDirectory}' is locked by live process ${pidNum}. ` +
|
|
1440
|
+
'Stop that process (or use a different directory) and retry.');
|
|
1299
1441
|
}
|
|
1300
|
-
catch { /* racing holder */ }
|
|
1301
|
-
if (tryAcquire())
|
|
1302
|
-
return;
|
|
1303
1442
|
}
|
|
1304
|
-
if (
|
|
1305
|
-
throw new Error(`
|
|
1306
|
-
'
|
|
1443
|
+
if (pid === String(process.pid)) {
|
|
1444
|
+
throw new Error(`Another Tero instance in THIS process is already using '${this.teroDirectory}'. ` +
|
|
1445
|
+
'Destroy the existing instance before constructing a new one.');
|
|
1307
1446
|
}
|
|
1447
|
+
if (tryAcquire())
|
|
1448
|
+
return;
|
|
1308
1449
|
}
|
|
1309
|
-
|
|
1310
|
-
throw new Error(`Another Tero instance in THIS process is already using '${this.teroDirectory}'. ` +
|
|
1311
|
-
'Destroy the existing instance before constructing a new one.');
|
|
1312
|
-
}
|
|
1313
|
-
throw new Error(`Data directory '${this.teroDirectory}' is locked (holder PID: ${pid}). ` +
|
|
1450
|
+
throw new Error(`Data directory '${this.teroDirectory}' is locked. ` +
|
|
1314
1451
|
`If the holder crashed, delete '${lockPath}' and retry.`);
|
|
1315
1452
|
}
|
|
1316
1453
|
releaseFileLock() {
|
|
@@ -1322,14 +1459,34 @@ export class Tero {
|
|
|
1322
1459
|
}
|
|
1323
1460
|
catch { /* best-effort */ }
|
|
1324
1461
|
}
|
|
1325
|
-
// Cleanup
|
|
1326
|
-
|
|
1462
|
+
// Cleanup methods
|
|
1463
|
+
async destroyAsync() {
|
|
1464
|
+
if (this.backupManager) {
|
|
1465
|
+
await this.backupManager.drainInFlight();
|
|
1466
|
+
this.backupManager.destroy();
|
|
1467
|
+
}
|
|
1327
1468
|
if (this.acidEngine) {
|
|
1328
1469
|
this.acidEngine.destroy();
|
|
1329
1470
|
}
|
|
1471
|
+
this.clearCache();
|
|
1472
|
+
this.releaseFileLock();
|
|
1473
|
+
}
|
|
1474
|
+
async close() {
|
|
1475
|
+
await this.destroyAsync();
|
|
1476
|
+
}
|
|
1477
|
+
destroy() {
|
|
1478
|
+
// Sync destroy cannot drain inflight S3 uploads (that's async) — warn if live backup has in-flight work.
|
|
1479
|
+
// Prefer `await db.destroyAsync()` / `await db.close()` in production when live backup is enabled.
|
|
1330
1480
|
if (this.backupManager) {
|
|
1481
|
+
const live = this.backupManager.liveCheckpointPromise;
|
|
1482
|
+
if (live) {
|
|
1483
|
+
console.warn('[Tero] destroy() called with inflight live checkpoint — use await destroyAsync() to avoid losing the last checkpoint.');
|
|
1484
|
+
}
|
|
1331
1485
|
this.backupManager.destroy();
|
|
1332
1486
|
}
|
|
1487
|
+
if (this.acidEngine) {
|
|
1488
|
+
this.acidEngine.destroy();
|
|
1489
|
+
}
|
|
1333
1490
|
this.clearCache();
|
|
1334
1491
|
this.releaseFileLock();
|
|
1335
1492
|
}
|