tero 0.0.13 → 0.1.2
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 +16 -27
- package/dist/acid-engine.d.ts +230 -53
- package/dist/acid-engine.js +1201 -323
- package/dist/backup.d.ts +27 -0
- package/dist/backup.js +708 -167
- package/dist/index.d.ts +167 -61
- package/dist/index.js +1498 -277
- package/dist/recovery.d.ts +52 -5
- package/dist/recovery.js +398 -117
- package/package.json +20 -16
- package/dist/schema.d.ts +0 -61
- package/dist/schema.js +0 -425
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',
|
|
216
|
+
await db.create('user', data);
|
|
241
217
|
} catch (error) {
|
|
242
|
-
if (error.message.includes('
|
|
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
|
|
|
@@ -253,12 +228,26 @@ const db = new Tero({
|
|
|
253
228
|
directory: './data', // default: 'TeroDB'
|
|
254
229
|
cacheSize: 1000, // default: 100, configurable LRU capacity
|
|
255
230
|
synchronous: 'full', // 'full' (default, fsync per commit), 'normal' (coalesced timer), or 'off'
|
|
231
|
+
checkpointBatchSize: 5000,// default: 1000, committedBuffer entries flushed per tick
|
|
232
|
+
archiveKeepCount: 50, // default: 20, rotated 1MB WAL segments kept locally
|
|
256
233
|
fileLock: true, // default: true, cross-process .lock directory guard
|
|
257
234
|
backup: { ... }, // optional: install a BackupConfig at construction
|
|
258
235
|
hydrateOnStartup: { ... },// optional: v2 hydration before engine init
|
|
259
236
|
});
|
|
260
237
|
```
|
|
261
238
|
|
|
239
|
+
### WAL retention and live backup
|
|
240
|
+
|
|
241
|
+
Every commit is appended to a WAL that rotates into immutable 1MB segments
|
|
242
|
+
(`.wal.seg-<start>-<end>`); those segments are what a point-in-time restore
|
|
243
|
+
replays, so `archiveKeepCount` is a recovery window, not a cache.
|
|
244
|
+
|
|
245
|
+
With `liveBackup` enabled the keep count is only a floor: a segment whose
|
|
246
|
+
entries have not been durably uploaded yet is **never** pruned, so a bucket
|
|
247
|
+
outage cannot turn a rotation into data loss. That deferral is bounded by a
|
|
248
|
+
per-WAL byte budget (64MB by default) — past it, retention falls back to
|
|
249
|
+
prune-oldest and logs a warning, because filling the disk would be worse.
|
|
250
|
+
|
|
262
251
|
## Testing
|
|
263
252
|
|
|
264
253
|
```bash
|
package/dist/acid-engine.d.ts
CHANGED
|
@@ -1,19 +1,90 @@
|
|
|
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?:
|
|
7
|
-
afterImage?:
|
|
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
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Rotated WAL segments a database keeps locally by default.
|
|
47
|
+
*
|
|
48
|
+
* The old value (3) was a 3MB cache, not a retention window: a 1MB WAL can
|
|
49
|
+
* rotate several times per second under load, so three segments could be
|
|
50
|
+
* unlinked inside the live shipper's 1s tick — the exact window in which their
|
|
51
|
+
* entries would have been uploaded. 20 segments (= 20MB at the 1MB segment
|
|
52
|
+
* size) gives the shipper ~20 rotations of slack. `setArchiveProtector` is what
|
|
53
|
+
* actually guarantees an unshipped segment survives, this is just the floor for
|
|
54
|
+
* databases without live backup.
|
|
55
|
+
*/
|
|
56
|
+
export declare const DEFAULT_ARCHIVE_KEEP_COUNT = 20;
|
|
57
|
+
/**
|
|
58
|
+
* Hard ceiling on the archives retained *only* because they have not been
|
|
59
|
+
* shipped yet (on top of the keep count). This is the disk-safety valve: a
|
|
60
|
+
* bucket that is unreachable for hours must not let the local WAL grow without
|
|
61
|
+
* bound. Segments past this budget are pruned oldest-first and a warning is
|
|
62
|
+
* emitted, because that is the one path where unshipped WAL is discarded.
|
|
63
|
+
*/
|
|
64
|
+
export declare const DEFAULT_ARCHIVE_PROTECT_MAX_BYTES: number;
|
|
65
|
+
export interface WriteAheadLogOptions {
|
|
66
|
+
/** Rotated segments retained locally. Default: DEFAULT_ARCHIVE_KEEP_COUNT. */
|
|
67
|
+
archiveKeepCount?: number;
|
|
68
|
+
/** Byte budget for not-yet-shipped segments. Default: DEFAULT_ARCHIVE_PROTECT_MAX_BYTES. */
|
|
69
|
+
archiveProtectMaxBytes?: number;
|
|
70
|
+
}
|
|
12
71
|
export declare class WriteAheadLog {
|
|
13
72
|
private logPath;
|
|
14
73
|
private currentLSN;
|
|
15
74
|
private readonly LOG_FILE_SIZE_LIMIT;
|
|
16
|
-
|
|
75
|
+
/** Retained rotated segments — see DEFAULT_ARCHIVE_KEEP_COUNT. */
|
|
76
|
+
private archiveKeepCount;
|
|
77
|
+
/** Disk-safety valve — see DEFAULT_ARCHIVE_PROTECT_MAX_BYTES. */
|
|
78
|
+
private archiveProtectMaxBytes;
|
|
79
|
+
/**
|
|
80
|
+
* Owner-supplied predicate answering "has this segment's last LSN NOT been
|
|
81
|
+
* durably shipped yet?". Live backup installs one so rotation can never
|
|
82
|
+
* unlink a segment before its entries reached the bucket. Absent for
|
|
83
|
+
* local-only databases, where pruning is unconditional.
|
|
84
|
+
*/
|
|
85
|
+
private archiveProtector?;
|
|
86
|
+
/** Rate limit for the disk-safety-valve warning (see the constant). */
|
|
87
|
+
private lastProtectOverflowWarnAt;
|
|
17
88
|
private synchronous;
|
|
18
89
|
private commitIntervalMs;
|
|
19
90
|
private dirty;
|
|
@@ -28,7 +99,7 @@ export declare class WriteAheadLog {
|
|
|
28
99
|
private writeBuffer;
|
|
29
100
|
private writeBufferSize;
|
|
30
101
|
private readonly FLUSH_THRESHOLD;
|
|
31
|
-
constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number);
|
|
102
|
+
constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, options?: WriteAheadLogOptions);
|
|
32
103
|
private initializeWAL;
|
|
33
104
|
/**
|
|
34
105
|
* fsync a file path by opening it read-only and synchronizing its (open) descriptor.
|
|
@@ -50,11 +121,15 @@ export declare class WriteAheadLog {
|
|
|
50
121
|
* into a single V8 string. Reads 64KB chunks, processes complete lines, and
|
|
51
122
|
* calls visitor(entry) for each valid (checksum-verified) entry.
|
|
52
123
|
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
124
|
+
* Invariant:
|
|
125
|
+
* - Newline-terminated invalid record -> fatal RecoveryCorruptionError
|
|
126
|
+
* - Interior invalid record -> fatal RecoveryCorruptionError
|
|
127
|
+
* - Final unterminated valid record -> replay (accept)
|
|
128
|
+
* - Final unterminated invalid record -> ignore as torn tail
|
|
129
|
+
* - Monotonic LSN strictly required within the log stream
|
|
56
130
|
*/
|
|
57
131
|
streamLogEntries(visitor: (entry: LogEntry) => void): void;
|
|
132
|
+
streamAllLogEntries(visitor: (entry: LogEntry) => void): void;
|
|
58
133
|
private calculateChecksum;
|
|
59
134
|
private verifyChecksum;
|
|
60
135
|
/**
|
|
@@ -75,22 +150,53 @@ export declare class WriteAheadLog {
|
|
|
75
150
|
flushBuffer(): void;
|
|
76
151
|
private checkLogRotation;
|
|
77
152
|
/**
|
|
78
|
-
* Rotate the WAL:
|
|
79
|
-
*
|
|
80
|
-
*
|
|
153
|
+
* Rotate the WAL:
|
|
154
|
+
* 1. Ensure current WAL is fsynced.
|
|
155
|
+
* 2. Rename current log to .wal.seg-<startLsn>-<endLsn> (atomic segment rotation).
|
|
156
|
+
* 3. Fsync archive and parent directory.
|
|
157
|
+
* 4. Create fresh empty WAL and fsync it and parent directory.
|
|
158
|
+
* 5. Emit a CHECKPOINT entry at the head of the new log.
|
|
159
|
+
* 6. Clean up old archives beyond the keep count, sparing any segment the
|
|
160
|
+
* archive protector reports as not-yet-shipped (see cleanupOldArchives).
|
|
161
|
+
*/
|
|
162
|
+
rotateLog(): string | null;
|
|
163
|
+
/**
|
|
164
|
+
* Every structurally valid rotated segment on disk, oldest first.
|
|
81
165
|
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* only guarantees WAL durability (forceFlush before archiving).
|
|
166
|
+
* Strictly matches deterministic segments `.wal.seg-<start>-<end>`; a partial
|
|
167
|
+
* or foreign file in the directory is ignored rather than guessed at. The end
|
|
168
|
+
* LSN is what retention decisions are made on (see cleanupOldArchives).
|
|
86
169
|
*/
|
|
87
|
-
|
|
170
|
+
private listSegments;
|
|
88
171
|
/**
|
|
89
172
|
* Returns the paths of all locally retained WAL archives (newest first).
|
|
90
173
|
* Used by v2 backup to upload segments to the client's bucket.
|
|
174
|
+
* Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
|
|
91
175
|
*/
|
|
92
176
|
listArchives(): string[];
|
|
177
|
+
/**
|
|
178
|
+
* Declare a segment as "must not be pruned" — used by live backup so a
|
|
179
|
+
* rotation can never unlink WAL that has not reached the bucket yet.
|
|
180
|
+
*
|
|
181
|
+
* The predicate receives a segment's last LSN and returns true while that
|
|
182
|
+
* LSN is still unshipped. Protection is best-effort by design: it is capped
|
|
183
|
+
* by the protect byte budget so an unreachable bucket degrades into the old
|
|
184
|
+
* prune-oldest behaviour instead of filling the disk. Pass null to detach
|
|
185
|
+
* (e.g. when live backup is disabled and pruning should be unconditional).
|
|
186
|
+
*/
|
|
187
|
+
setArchiveProtector(protector: ((segmentEndLsn: number) => boolean) | null): void;
|
|
188
|
+
/**
|
|
189
|
+
* Retain the newest `keepCount` segments and delete the rest, oldest first —
|
|
190
|
+
* except any segment the archive protector still considers unshipped, which
|
|
191
|
+
* is deferred as long as the protect byte budget allows.
|
|
192
|
+
*
|
|
193
|
+
* `force` skips both the keep count and the protector entirely: it is the
|
|
194
|
+
* "wipe the WAL" path (truncateLog), where the caller has explicitly
|
|
195
|
+
* declared the archived entries worthless.
|
|
196
|
+
*/
|
|
93
197
|
private cleanupOldArchives;
|
|
198
|
+
/** Size of a segment in bytes; 0 when it is already gone or unreadable. */
|
|
199
|
+
private segmentSize;
|
|
94
200
|
getLogEntries(fromLSN?: number): LogEntry[];
|
|
95
201
|
/**
|
|
96
202
|
* Explicit flush barrier. Always fsyncs regardless of synchronous mode, so
|
|
@@ -101,16 +207,19 @@ export declare class WriteAheadLog {
|
|
|
101
207
|
forceFlush(): void;
|
|
102
208
|
getCurrentLSN(): number;
|
|
103
209
|
/**
|
|
104
|
-
* Truncate (clear) the WAL entirely.
|
|
105
|
-
*
|
|
106
|
-
*
|
|
210
|
+
* Truncate (clear) the WAL entirely.
|
|
211
|
+
* Force-flushes any buffered entries first, verifies buffer is drained,
|
|
212
|
+
* truncates .wal to 0 bytes, fsyncs file and directory, and cleans up archives.
|
|
107
213
|
*/
|
|
108
214
|
truncateLog(): void;
|
|
109
215
|
destroy(): void;
|
|
110
216
|
}
|
|
111
217
|
export declare class LockManager {
|
|
112
218
|
private locks;
|
|
219
|
+
private waitingOn;
|
|
113
220
|
private readonly DEADLOCK_TIMEOUT;
|
|
221
|
+
private hasCycle;
|
|
222
|
+
private cleanTxGraph;
|
|
114
223
|
/**
|
|
115
224
|
* Acquire a lock. Returns `true` synchronously when the lock is granted
|
|
116
225
|
* immediately (uncontended fast path — zero Promise allocation). Returns a
|
|
@@ -128,6 +237,7 @@ export declare class LockManager {
|
|
|
128
237
|
releaseLocksForTx(transactionId: string, heldKeys: Set<string>, waitingKeys?: Set<string>): void;
|
|
129
238
|
releaseAllLocks(transactionId: string): void;
|
|
130
239
|
detectDeadlock(): string[];
|
|
240
|
+
isKeyLocked(key: string): boolean;
|
|
131
241
|
}
|
|
132
242
|
/**
|
|
133
243
|
* Map a document key to a 2-level hash-prefix partitioned path:
|
|
@@ -145,6 +255,34 @@ export declare class LockManager {
|
|
|
145
255
|
* partition the engine reads from (deterministic from the key).
|
|
146
256
|
*/
|
|
147
257
|
export declare function partitionedPath(dbPath: string, key: string): string;
|
|
258
|
+
/**
|
|
259
|
+
* Remove temp files left behind by a process that died between writing its temp
|
|
260
|
+
* file and renaming it into place.
|
|
261
|
+
*
|
|
262
|
+
* Safety rests on three properties, in order of importance:
|
|
263
|
+
*
|
|
264
|
+
* 1. It runs ONLY from the constructor, after the cross-process `.lock` is
|
|
265
|
+
* held and after crash recovery has run. No writer exists yet, so a temp
|
|
266
|
+
* file observed here can only predate this process. Writes this process
|
|
267
|
+
* makes later are renamed away synchronously and are never observable.
|
|
268
|
+
* 2. The pid embedded in the name must differ from ours (see
|
|
269
|
+
* isOrphanedTempFile), so an in-flight write is never unlinked out from
|
|
270
|
+
* under its own `renameSync`.
|
|
271
|
+
* 3. A name that does not parse as a temp file is left untouched rather than
|
|
272
|
+
* guessed at.
|
|
273
|
+
*
|
|
274
|
+
* The embedded timestamp must also be older than `minAgeMs`, which keeps the
|
|
275
|
+
* sweep inert even if a second process does hold the directory open and writes
|
|
276
|
+
* a temp file while we are walking it.
|
|
277
|
+
*
|
|
278
|
+
* Only temp files are unlinked, and the parent directory is fsynced so the
|
|
279
|
+
* unlink survives power loss. Failing to remove a temp file never fails
|
|
280
|
+
* startup -- it is a space leak, not a correctness problem.
|
|
281
|
+
*/
|
|
282
|
+
export declare function sweepStaleTempFiles(dbPath: string, minAgeMs?: number): {
|
|
283
|
+
scanned: number;
|
|
284
|
+
removed: number;
|
|
285
|
+
};
|
|
148
286
|
/**
|
|
149
287
|
* Walk partitioned directories under dbPath and call `visitor(filePath)` for
|
|
150
288
|
* every *.json file found. Uses fs.opendir async iteration so each directory
|
|
@@ -152,68 +290,97 @@ export declare function partitionedPath(dbPath: string, key: string): string;
|
|
|
152
290
|
* what verifyDataIntegrity + backup enumeration use, replacing readdirSync.
|
|
153
291
|
*/
|
|
154
292
|
export declare function walkPartitions(dbPath: string, visitor: (filePath: string) => void | Promise<void>): Promise<void>;
|
|
293
|
+
export interface RestoreMarker {
|
|
294
|
+
id: string;
|
|
295
|
+
targetDir: string;
|
|
296
|
+
stagingDir: string;
|
|
297
|
+
backupDir: string;
|
|
298
|
+
createdAt: number;
|
|
299
|
+
stage: 'prepared' | 'swapped';
|
|
300
|
+
}
|
|
301
|
+
export declare function safeRemoveDirectory(dirPath: string): void;
|
|
302
|
+
export declare function recoverPendingRestore(dbPath: string): void;
|
|
303
|
+
export declare function verifyWalSegmentContinuity(segmentPaths: string[], verifyContent?: boolean): Array<{
|
|
304
|
+
path: string;
|
|
305
|
+
startLsn: number;
|
|
306
|
+
endLsn: number;
|
|
307
|
+
}>;
|
|
308
|
+
export interface SnapshotHandle {
|
|
309
|
+
readonly lsn: number;
|
|
310
|
+
files(): AsyncGenerator<{
|
|
311
|
+
key: string;
|
|
312
|
+
lsn: number;
|
|
313
|
+
state: 'present' | 'deleted';
|
|
314
|
+
data?: JsonValue;
|
|
315
|
+
}>;
|
|
316
|
+
close(): void;
|
|
317
|
+
}
|
|
155
318
|
export declare class ACIDStorageEngine {
|
|
156
319
|
private wal;
|
|
157
320
|
private lockManager;
|
|
158
321
|
private dbPath;
|
|
159
322
|
private activeTransactions;
|
|
323
|
+
private finishedTransactions;
|
|
160
324
|
/**
|
|
161
|
-
* In-memory pending-writes index per active transaction.
|
|
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
|
-
*
|
|
325
|
+
* In-memory pending-writes index per active transaction.
|
|
166
326
|
* Keyed by transactionId -> key -> { beforeImage, afterImage, op }
|
|
167
327
|
*/
|
|
168
328
|
private pendingWrites;
|
|
169
329
|
/**
|
|
170
330
|
* Compaction cadence: every COMMIT_INTERVAL commits, if there are no active
|
|
171
331
|
* 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
332
|
*/
|
|
174
333
|
private readonly COMMIT_INTERVAL;
|
|
175
334
|
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
335
|
private txCounter;
|
|
186
336
|
private readonly pid;
|
|
187
337
|
private readonly txSalt;
|
|
188
338
|
/**
|
|
189
339
|
* Deferred data-file write buffer. On commit, committed data moves here instead
|
|
190
340
|
* of being written to data files immediately. A background timer flushes this
|
|
191
|
-
* to disk every `dataFlushIntervalMs` (default 50ms).
|
|
192
|
-
* architecture: the WAL is the durable copy; data files are a checkpointed cache
|
|
193
|
-
* rebuilt via redo on crash recovery.
|
|
341
|
+
* to disk every `dataFlushIntervalMs` (default 50ms).
|
|
194
342
|
*/
|
|
195
343
|
private committedBuffer;
|
|
196
344
|
private dataFlushTimer?;
|
|
197
345
|
private readonly DATA_FLUSH_INTERVAL_MS;
|
|
198
346
|
/**
|
|
199
|
-
*
|
|
200
|
-
* Every committed write/delete
|
|
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).
|
|
347
|
+
* Version-consistent dirty-key tracker for cloud checkpoints.
|
|
348
|
+
* Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
|
|
206
349
|
*/
|
|
207
350
|
private dirtyKeys;
|
|
351
|
+
private activeSnapshotLsn;
|
|
352
|
+
private snapshotBeforeImages;
|
|
353
|
+
private lastCommittedLSN;
|
|
354
|
+
private degraded;
|
|
355
|
+
private lastMaintenanceError;
|
|
356
|
+
isDegraded(): boolean;
|
|
357
|
+
getLastMaintenanceError(): Error | null;
|
|
358
|
+
getLastCommittedLSN(): number;
|
|
359
|
+
peekDirtyKeys(upToLsn?: number): Map<string, DirtyEntry>;
|
|
360
|
+
acknowledgeDirtyKeys(acked: Iterable<{
|
|
361
|
+
key: string;
|
|
362
|
+
lsn: number;
|
|
363
|
+
}>): void;
|
|
364
|
+
getDirtyKeyCount(): number;
|
|
208
365
|
/**
|
|
209
|
-
*
|
|
210
|
-
*
|
|
366
|
+
* Creates an isolated logical snapshot handle as of upToLsn.
|
|
367
|
+
* Enforces single-active-snapshot invariant and provides explicit close().
|
|
211
368
|
*/
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
|
|
369
|
+
beginSnapshot(upToLsn: number): SnapshotHandle;
|
|
370
|
+
/**
|
|
371
|
+
* Streams a version-consistent logical snapshot of the database as of upToLsn.
|
|
372
|
+
* Fully protected against concurrent writes via Copy-On-Write snapshotBeforeImages.
|
|
373
|
+
*/
|
|
374
|
+
snapshotFiles(upToLsn: number): AsyncGenerator<{
|
|
375
|
+
key: string;
|
|
376
|
+
lsn: number;
|
|
377
|
+
state: 'present' | 'deleted';
|
|
378
|
+
data?: JsonValue;
|
|
379
|
+
}>;
|
|
380
|
+
private _streamSnapshotFiles;
|
|
215
381
|
private synchronous;
|
|
216
|
-
|
|
382
|
+
private checkpointBatchSize;
|
|
383
|
+
constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number, archiveKeepCount?: number);
|
|
217
384
|
private fsyncFile;
|
|
218
385
|
private fsyncDir;
|
|
219
386
|
private initializeStorage;
|
|
@@ -305,11 +472,21 @@ export declare class ACIDStorageEngine {
|
|
|
305
472
|
* disk). Used by the get() fast path in index.ts.
|
|
306
473
|
*/
|
|
307
474
|
getCommittedData(key: string): any | undefined;
|
|
475
|
+
isKeyLocked(key: string): boolean;
|
|
476
|
+
isKeyInCommittedBuffer(key: string): boolean;
|
|
477
|
+
/**
|
|
478
|
+
* Truncate WAL log with strict precondition checks.
|
|
479
|
+
* Enforces that no active transactions exist, no pending uncommitted writes exist,
|
|
480
|
+
* committedBuffer is drained, flushes committed buffer to disk, writes a CHECKPOINT,
|
|
481
|
+
* and safely truncates the WAL.
|
|
482
|
+
*/
|
|
483
|
+
truncateLog(): void;
|
|
308
484
|
/**
|
|
309
|
-
*
|
|
310
|
-
* and by forceCheckpoint(). Writes
|
|
311
|
-
* the atomic temp→rename pattern,
|
|
485
|
+
* Flush the committedBuffer to data files. Called by the background timer
|
|
486
|
+
* and by forceCheckpoint(). Writes buffered entries to data files using
|
|
487
|
+
* the atomic temp→rename pattern. When unforced, processes in chunks to prevent
|
|
488
|
+
* event loop starvation under sustained heavy write loads.
|
|
312
489
|
*/
|
|
313
|
-
flushCommittedBuffer(forceFsync?: boolean): void;
|
|
490
|
+
flushCommittedBuffer(forceFsync?: boolean, maxBatch?: number): void;
|
|
314
491
|
destroy(): void;
|
|
315
492
|
}
|