inibase 2.0.0 → 3.0.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.
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Write-ahead journal for crash-atomic, multi-file commits.
3
+ *
4
+ * A transaction writes its intent to `journal.jsonl` (fsynced) before touching
5
+ * any live file, then swaps each live file aside (see `backup`), renames the
6
+ * freshly-written temp file into place, optionally renames the pagination
7
+ * metadata file, and finally appends a `commit` marker (fsynced).
8
+ *
9
+ * Two journal layouts share one recovery rule:
10
+ * - single-table ops: one `begin` entry carrying `files` + `pagination`;
11
+ * - database transactions: a `begin` entry (tables only) followed by one `op`
12
+ * entry per staged mutation (`files` + optional `pagination`), then `commit`.
13
+ *
14
+ * Recovery rule (run under the lock before any access):
15
+ * - journal without `commit` -> roll back (restore backups, undo pagination,
16
+ * discard temps);
17
+ * - journal with `commit` -> roll forward (complete swaps, discard backups).
18
+ *
19
+ * After recovery the journal is removed, so a logical operation spanning many
20
+ * column files + pagination (single- or multi-table) is atomic w.r.t. crashes.
21
+ */
22
+ export interface JournalFileOp {
23
+ /** Absolute path of the live file being replaced or removed. */
24
+ live: string;
25
+ /** Absolute path where the original file is parked while the swap is in flight. */
26
+ backup: string;
27
+ /** Absolute path of the fully-written replacement, or null for pure removals. */
28
+ tmp: string | null;
29
+ /** Whether the live file existed when the transaction began. */
30
+ existed: boolean;
31
+ }
32
+ export interface JournalBeginEntry {
33
+ txn: string;
34
+ type: "begin";
35
+ /** Tables touched by a database transaction (single-table ops omit this). */
36
+ tables?: string[];
37
+ /** Single-table ops carry their intent directly on the begin entry. */
38
+ files?: JournalFileOp[];
39
+ /** Old/new absolute pagination file paths, or null when counts don't change. */
40
+ pagination?: {
41
+ from: string;
42
+ to: string;
43
+ } | null;
44
+ }
45
+ export interface JournalOpEntry {
46
+ txn: string;
47
+ type: "op";
48
+ files: JournalFileOp[];
49
+ /** Old/new absolute pagination file paths, or null when counts don't change. */
50
+ pagination?: {
51
+ from: string;
52
+ to: string;
53
+ } | null;
54
+ }
55
+ export interface JournalCommitEntry {
56
+ txn: string;
57
+ type: "commit";
58
+ }
59
+ export type JournalEntry = JournalBeginEntry | JournalOpEntry | JournalCommitEntry;
60
+ export declare class Journal {
61
+ readonly path: string;
62
+ private readonly txn;
63
+ private handle;
64
+ constructor(tablePath: string, txn: string);
65
+ private openJournal;
66
+ private append;
67
+ begin(files: JournalFileOp[], pagination?: JournalBeginEntry["pagination"]): Promise<void>;
68
+ commit(): Promise<void>;
69
+ /**
70
+ * Undo an in-flight transaction whose `commit` marker was never written.
71
+ * Restores originals from backups, undoes the pagination rename (if any),
72
+ * removes created files and leftovers, then discards the journal.
73
+ */
74
+ rollback(): Promise<void>;
75
+ dispose(): Promise<void>;
76
+ }
77
+ /**
78
+ * Write-ahead journal for a database-level transaction spanning multiple
79
+ * tables. Holds `begin(tables)` once, then one `op` per staged mutation, and
80
+ * finally a single `commit` marker. Lives in `<database>/.tmp/journal.jsonl`
81
+ * next to the per-table `.tmp` directories.
82
+ */
83
+ export declare class DatabaseJournal {
84
+ readonly path: string;
85
+ private readonly txn;
86
+ private handle;
87
+ constructor(dbPath: string, txn: string);
88
+ private openJournal;
89
+ private append;
90
+ begin(tables: string[]): Promise<void>;
91
+ op(files: JournalFileOp[], pagination?: JournalOpEntry["pagination"]): Promise<void>;
92
+ commit(): Promise<void>;
93
+ /**
94
+ * Undo the transaction: restore any published files (crash mid-commit in
95
+ * the same process — callers normally roll back before anything is
96
+ * published), discard temps/journals. Handles the un-published case
97
+ * identically (no backups exist -> restores are no-ops).
98
+ */
99
+ rollback(): Promise<void>;
100
+ dispose(): Promise<void>;
101
+ }
102
+ /**
103
+ * Recover from a crash. `tmpDirPath` is a `.tmp` directory (a table's or the
104
+ * database's) where `journal.jsonl` lives, in either single-table or
105
+ * database-transaction layout. Entries carry absolute paths, so no other
106
+ * context is needed. Must be called while holding the corresponding lock so no
107
+ * live writer can interleave.
108
+ */
109
+ export declare function recover(tmpDirPath: string): Promise<void>;
@@ -0,0 +1,263 @@
1
+ import { open, readFile, rename, rmdir, unlink, } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ // Durability mirror of src/file.ts (kept local to avoid an ESM import cycle:
4
+ // file.ts imports recover() from here). `none` skips fsyncs, `full` fsyncs
5
+ // journal appends, recoveries and directory touches.
6
+ const DURABLE = (process.env.INIBASE_DURABILITY ?? "full") !== "none";
7
+ const maybeSync = async (handle) => {
8
+ if (DURABLE)
9
+ await handle.sync();
10
+ };
11
+ const exists = async (path) => {
12
+ try {
13
+ const handle = await open(path, "r");
14
+ await handle.close();
15
+ return true;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ };
21
+ const syncDir = async (path) => {
22
+ let handle = null;
23
+ try {
24
+ handle = await open(path, "r");
25
+ await maybeSync(handle);
26
+ }
27
+ catch {
28
+ // Directory fsync is not supported on every platform/filesystem.
29
+ }
30
+ finally {
31
+ await handle?.close();
32
+ }
33
+ };
34
+ /** Parse every journal entry; partial trailing lines (crash mid-append) are ignored. */
35
+ const readEntries = async (journalPath) => {
36
+ let content;
37
+ try {
38
+ content = await readFile(journalPath, "utf8");
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ const entries = [];
44
+ for (const line of content.split("\n")) {
45
+ if (!line)
46
+ continue;
47
+ try {
48
+ entries.push(JSON.parse(line));
49
+ }
50
+ catch {
51
+ // Partial trailing line: the append that wrote it was never
52
+ // fsynced, so the transaction never reached its `commit` marker.
53
+ }
54
+ }
55
+ return entries;
56
+ };
57
+ const readBegin = async (journalPath) => {
58
+ for (const entry of await readEntries(journalPath))
59
+ if (entry.type === "begin")
60
+ return entry;
61
+ return null;
62
+ };
63
+ /** Flatten begin/op entries into ordered file ops and pagination renames. */
64
+ const collectOps = (entries) => {
65
+ const ops = [];
66
+ const paginations = [];
67
+ for (const entry of entries) {
68
+ if (entry.type === "commit")
69
+ continue;
70
+ if (entry.files?.length)
71
+ ops.push(...entry.files);
72
+ if (entry.pagination)
73
+ paginations.push(entry.pagination);
74
+ }
75
+ return { ops, paginations };
76
+ };
77
+ /**
78
+ * Undo an uncommitted transaction (in reverse order so chained pagination
79
+ * renames and repeated swaps of the same live file unwind correctly), discard
80
+ * temps and backups, and fsync the affected directories.
81
+ */
82
+ const applyRollback = async (ops, paginations) => {
83
+ for (const op of ops.toReversed()) {
84
+ if (op.existed && (await exists(op.backup))) {
85
+ await unlink(op.live).catch(() => { });
86
+ await rename(op.backup, op.live);
87
+ }
88
+ else if (!op.existed) {
89
+ await unlink(op.live).catch(() => { });
90
+ }
91
+ if (op.tmp)
92
+ await unlink(op.tmp).catch(() => { });
93
+ await unlink(op.backup).catch(() => { });
94
+ // Drop the per-txn backup subdirectory once it is empty.
95
+ await rmEmptyDir(dirname(op.backup));
96
+ }
97
+ for (const { from, to } of paginations.toReversed())
98
+ if ((await exists(to)) && !(await exists(from)))
99
+ await rename(to, from);
100
+ };
101
+ /** Complete a committed transaction: finish any missing swaps, drop backups. */
102
+ const applyRollForward = async (ops, paginations) => {
103
+ for (const op of ops) {
104
+ if (op.tmp && !(await exists(op.live)) && (await exists(op.tmp)))
105
+ await rename(op.tmp, op.live);
106
+ await unlink(op.backup).catch(() => { });
107
+ if (op.tmp)
108
+ await unlink(op.tmp).catch(() => { });
109
+ await rmEmptyDir(dirname(op.backup));
110
+ }
111
+ for (const { from, to } of paginations)
112
+ if ((await exists(from)) && !(await exists(to)))
113
+ await rename(from, to);
114
+ };
115
+ /** Best-effort removal of an empty directory (per-txn backup dir). */
116
+ const rmEmptyDir = async (dirPath) => {
117
+ try {
118
+ await rmdir(dirPath);
119
+ }
120
+ catch {
121
+ // Not empty or already gone: leave it.
122
+ }
123
+ };
124
+ export class Journal {
125
+ path;
126
+ txn;
127
+ handle = null;
128
+ constructor(tablePath, txn) {
129
+ this.txn = txn;
130
+ this.path = join(tablePath, ".tmp", "journal.jsonl");
131
+ }
132
+ async openJournal() {
133
+ if (!this.handle)
134
+ this.handle = await open(this.path, "a+");
135
+ }
136
+ async append(entry) {
137
+ await this.openJournal();
138
+ const handle = this.handle;
139
+ if (!handle)
140
+ throw new Error("JOURNAL_NOT_OPEN");
141
+ await handle.writeFile(`${JSON.stringify(entry)}\n`);
142
+ await maybeSync(handle);
143
+ }
144
+ async begin(files, pagination = null) {
145
+ await this.append({ txn: this.txn, type: "begin", files, pagination });
146
+ }
147
+ async commit() {
148
+ await this.append({ txn: this.txn, type: "commit" });
149
+ }
150
+ /**
151
+ * Undo an in-flight transaction whose `commit` marker was never written.
152
+ * Restores originals from backups, undoes the pagination rename (if any),
153
+ * removes created files and leftovers, then discards the journal.
154
+ */
155
+ async rollback() {
156
+ try {
157
+ const begin = await readBegin(this.path);
158
+ if (!begin)
159
+ return;
160
+ const { ops, paginations } = collectOps([begin]);
161
+ await applyRollback(ops, paginations);
162
+ }
163
+ finally {
164
+ await this.dispose();
165
+ await unlink(this.path).catch(() => { });
166
+ }
167
+ }
168
+ async dispose() {
169
+ await this.handle?.close();
170
+ this.handle = null;
171
+ }
172
+ }
173
+ /**
174
+ * Write-ahead journal for a database-level transaction spanning multiple
175
+ * tables. Holds `begin(tables)` once, then one `op` per staged mutation, and
176
+ * finally a single `commit` marker. Lives in `<database>/.tmp/journal.jsonl`
177
+ * next to the per-table `.tmp` directories.
178
+ */
179
+ export class DatabaseJournal {
180
+ path;
181
+ txn;
182
+ handle = null;
183
+ constructor(dbPath, txn) {
184
+ this.txn = txn;
185
+ this.path = join(dbPath, ".tmp", "journal.jsonl");
186
+ }
187
+ async openJournal() {
188
+ if (!this.handle)
189
+ this.handle = await open(this.path, "a+");
190
+ }
191
+ async append(entry) {
192
+ await this.openJournal();
193
+ const handle = this.handle;
194
+ if (!handle)
195
+ throw new Error("JOURNAL_NOT_OPEN");
196
+ await handle.writeFile(`${JSON.stringify(entry)}\n`);
197
+ await maybeSync(handle);
198
+ }
199
+ async begin(tables) {
200
+ await this.append({ txn: this.txn, type: "begin", tables });
201
+ }
202
+ async op(files, pagination = null) {
203
+ await this.append({ txn: this.txn, type: "op", files, pagination });
204
+ }
205
+ async commit() {
206
+ await this.append({ txn: this.txn, type: "commit" });
207
+ }
208
+ /**
209
+ * Undo the transaction: restore any published files (crash mid-commit in
210
+ * the same process — callers normally roll back before anything is
211
+ * published), discard temps/journals. Handles the un-published case
212
+ * identically (no backups exist -> restores are no-ops).
213
+ */
214
+ async rollback() {
215
+ try {
216
+ const { ops, paginations } = collectOps(await readEntries(this.path));
217
+ await applyRollback(ops, paginations);
218
+ }
219
+ finally {
220
+ await this.dispose();
221
+ await unlink(this.path).catch(() => { });
222
+ }
223
+ }
224
+ async dispose() {
225
+ await this.handle?.close();
226
+ this.handle = null;
227
+ }
228
+ }
229
+ /**
230
+ * Recover from a crash. `tmpDirPath` is a `.tmp` directory (a table's or the
231
+ * database's) where `journal.jsonl` lives, in either single-table or
232
+ * database-transaction layout. Entries carry absolute paths, so no other
233
+ * context is needed. Must be called while holding the corresponding lock so no
234
+ * live writer can interleave.
235
+ */
236
+ export async function recover(tmpDirPath) {
237
+ const journalPath = join(tmpDirPath, "journal.jsonl");
238
+ const entries = await readEntries(journalPath);
239
+ if (!entries.length)
240
+ return; // no journal -> nothing to recover
241
+ const begin = entries.find((entry) => entry.type === "begin");
242
+ if (!begin) {
243
+ // Journal exists but its begin entry never became durable: no rename
244
+ // was performed, so the live files are untouched. Discard the journal.
245
+ await unlink(journalPath).catch(() => { });
246
+ return;
247
+ }
248
+ const committed = entries.some((entry) => entry.type === "commit");
249
+ const { ops, paginations } = collectOps(entries);
250
+ if (committed) {
251
+ // Roll forward: every rename already happened before `commit` was
252
+ // written; just make sure swaps completed and discard the backups.
253
+ await applyRollForward(ops, paginations);
254
+ }
255
+ else {
256
+ // Roll back: restore originals, undo pagination renames, remove files
257
+ // the transaction created and discard every leftover.
258
+ await applyRollback(ops, paginations);
259
+ }
260
+ await unlink(journalPath).catch(() => { });
261
+ await syncDir(tmpDirPath);
262
+ await syncDir(dirname(tmpDirPath));
263
+ }
package/dist/utils.d.ts CHANGED
@@ -115,7 +115,8 @@ export declare const isPassword: (input: unknown) => input is string;
115
115
  * @param input - The input to be checked, can be of any type.
116
116
  * @returns A boolean indicating whether the input is a valid date.
117
117
  */
118
- export declare const isDate: (input: unknown) => input is Date | number;
118
+ export declare const dateToTimestamp: (input: unknown) => number | null;
119
+ export declare const isDate: (input: unknown) => boolean;
119
120
  /**
120
121
  * Checks if the input is a valid ID.
121
122
  *
package/dist/utils.js CHANGED
@@ -163,20 +163,36 @@ export const isPassword = (input) => typeof input === "string" && input.length =
163
163
  * @param input - The input to be checked, can be of any type.
164
164
  * @returns A boolean indicating whether the input is a valid date.
165
165
  */
166
- export const isDate = (input) => {
166
+ export const dateToTimestamp = (input) => {
167
167
  // Check if the input is null, undefined, or an empty string
168
168
  if (input == null || input === "")
169
- return false;
169
+ return null;
170
+ if (typeof input === "string") {
171
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(input);
172
+ if (match) {
173
+ const year = Number(match[1]);
174
+ const month = Number(match[2]);
175
+ const day = Number(match[3]);
176
+ const timestamp = Date.UTC(year, month - 1, day);
177
+ const date = new Date(timestamp);
178
+ return date.getUTCFullYear() === year &&
179
+ date.getUTCMonth() === month - 1 &&
180
+ date.getUTCDate() === day
181
+ ? timestamp
182
+ : null;
183
+ }
184
+ }
170
185
  // Convert to number and check if it's a valid number
171
186
  const numTimestamp = Number(input);
172
187
  // Check if the converted number is NaN or not finite
173
188
  if (Number.isNaN(numTimestamp) || !Number.isFinite(numTimestamp))
174
- return false;
189
+ return null;
175
190
  // Create a Date object from the timestamp
176
191
  const date = new Date(numTimestamp);
177
192
  // Check if the date is valid
178
- return date.getTime() === numTimestamp;
193
+ return date.getTime() === numTimestamp ? numTimestamp : null;
179
194
  };
195
+ export const isDate = (input) => dateToTimestamp(input) !== null;
180
196
  /**
181
197
  * Checks if the input is a valid ID.
182
198
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inibase",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "type": "module",
5
5
  "author": {
6
6
  "name": "Karim Amahtil",
@@ -17,7 +17,7 @@
17
17
  "bugs": {
18
18
  "url": "https://github.com/inicontent/inibase/issues"
19
19
  },
20
- "description": "A file-based & memory-efficient, serverless, ACID compliant, relational database management system",
20
+ "description": "A file-based & memory-efficient, serverless relational database with crash-atomic ACID: single-table DML + multi-table transactions (per-table writer locks, write-ahead journal + crash recovery, fsync-backed durability, begin/commit/rollback)",
21
21
  "engines": {
22
22
  "node": ">=22"
23
23
  },
@@ -86,7 +86,10 @@
86
86
  "prebuild": "biome check --write src",
87
87
  "build": "tsc",
88
88
  "benchmark": "./benchmark/run.js",
89
+ "benchmark:durability": "tsx ./benchmark/durability.ts",
89
90
  "test": "tsx ./tests/inibase.test.ts",
91
+ "test:durability": "tsx ./tests/durability.test.ts",
92
+ "test:transaction": "tsx ./tests/transaction.test.ts",
90
93
  "test:utils": "tsx ./tests/utils.test.ts",
91
94
  "test:advanced": "tsx ./tests/inibase.advanced.test.ts"
92
95
  }