@liorandb/core 1.0.18 → 1.0.19

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,213 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+
4
+ /* =========================
5
+ WAL RECORD TYPES
6
+ ========================= */
7
+
8
+ export type WALRecord =
9
+ | { lsn: number; tx: number; type: "op"; payload: any }
10
+ | { lsn: number; tx: number; type: "commit" }
11
+ | { lsn: number; tx: number; type: "applied" };
12
+
13
+ type StoredRecord = WALRecord & { crc: number };
14
+
15
+ /* =========================
16
+ CONSTANTS
17
+ ========================= */
18
+
19
+ const MAX_WAL_SIZE = 16 * 1024 * 1024; // 16 MB
20
+ const WAL_DIR = "__wal";
21
+
22
+ /* =========================
23
+ CRC32 IMPLEMENTATION
24
+ (no dependencies)
25
+ ========================= */
26
+
27
+ const CRC32_TABLE = (() => {
28
+ const table = new Uint32Array(256);
29
+ for (let i = 0; i < 256; i++) {
30
+ let c = i;
31
+ for (let k = 0; k < 8; k++) {
32
+ c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
33
+ }
34
+ table[i] = c >>> 0;
35
+ }
36
+ return table;
37
+ })();
38
+
39
+ function crc32(input: string): number {
40
+ let crc = 0xFFFFFFFF;
41
+ for (let i = 0; i < input.length; i++) {
42
+ const byte = input.charCodeAt(i);
43
+ crc = CRC32_TABLE[(crc ^ byte) & 0xFF] ^ (crc >>> 8);
44
+ }
45
+ return (crc ^ 0xFFFFFFFF) >>> 0;
46
+ }
47
+
48
+ /* =========================
49
+ WAL MANAGER
50
+ ========================= */
51
+
52
+ export class WALManager {
53
+ private walDir: string;
54
+ private currentGen = 1;
55
+ private lsn = 0;
56
+ private fd: fs.promises.FileHandle | null = null;
57
+
58
+ constructor(baseDir: string) {
59
+ this.walDir = path.join(baseDir, WAL_DIR);
60
+ fs.mkdirSync(this.walDir, { recursive: true });
61
+ this.currentGen = this.detectLastGeneration();
62
+ }
63
+
64
+ /* -------------------------
65
+ INTERNAL HELPERS
66
+ ------------------------- */
67
+
68
+ private walPath(gen = this.currentGen) {
69
+ return path.join(
70
+ this.walDir,
71
+ `wal-${String(gen).padStart(6, "0")}.log`
72
+ );
73
+ }
74
+
75
+ private detectLastGeneration(): number {
76
+ if (!fs.existsSync(this.walDir)) return 1;
77
+
78
+ const files = fs.readdirSync(this.walDir);
79
+ let max = 0;
80
+
81
+ for (const f of files) {
82
+ const m = f.match(/^wal-(\d+)\.log$/);
83
+ if (m) max = Math.max(max, Number(m[1]));
84
+ }
85
+
86
+ return max || 1;
87
+ }
88
+
89
+ private async open() {
90
+ if (!this.fd) {
91
+ this.fd = await fs.promises.open(this.walPath(), "a");
92
+ }
93
+ }
94
+
95
+ private async rotate() {
96
+ if (this.fd) {
97
+ await this.fd.close();
98
+ this.fd = null;
99
+ }
100
+ this.currentGen++;
101
+ }
102
+
103
+ /* -------------------------
104
+ APPEND
105
+ ------------------------- */
106
+
107
+ async append(record: Omit<WALRecord, "lsn">): Promise<number> {
108
+ await this.open();
109
+
110
+ const full: WALRecord = {
111
+ ...(record as any),
112
+ lsn: ++this.lsn
113
+ };
114
+
115
+ const body = JSON.stringify(full);
116
+ const stored: StoredRecord = {
117
+ ...full,
118
+ crc: crc32(body)
119
+ };
120
+
121
+ await this.fd!.write(JSON.stringify(stored) + "\n");
122
+ await this.fd!.sync();
123
+
124
+ const stat = await this.fd!.stat();
125
+ if (stat.size >= MAX_WAL_SIZE) {
126
+ await this.rotate();
127
+ }
128
+
129
+ return full.lsn;
130
+ }
131
+
132
+ /* -------------------------
133
+ REPLAY
134
+ ------------------------- */
135
+
136
+ async replay(
137
+ fromLSN: number,
138
+ apply: (r: WALRecord) => Promise<void>
139
+ ): Promise<void> {
140
+ if (!fs.existsSync(this.walDir)) return;
141
+
142
+ const files = fs
143
+ .readdirSync(this.walDir)
144
+ .filter(f => f.startsWith("wal-"))
145
+ .sort();
146
+
147
+ for (const file of files) {
148
+ const filePath = path.join(this.walDir, file);
149
+ const data = fs.readFileSync(filePath, "utf8");
150
+ const lines = data.split("\n");
151
+
152
+ for (let i = 0; i < lines.length; i++) {
153
+ const line = lines[i];
154
+ if (!line.trim()) continue;
155
+
156
+ let parsed: StoredRecord;
157
+ try {
158
+ parsed = JSON.parse(line);
159
+ } catch {
160
+ console.error("WAL parse error, stopping replay");
161
+ return;
162
+ }
163
+
164
+ const { crc, ...record } = parsed;
165
+ const expected = crc32(JSON.stringify(record));
166
+
167
+ if (expected !== crc) {
168
+ console.error(
169
+ "WAL checksum mismatch, stopping replay",
170
+ { file, line: i + 1 }
171
+ );
172
+ return;
173
+ }
174
+
175
+ if (record.lsn <= fromLSN) continue;
176
+
177
+ this.lsn = Math.max(this.lsn, record.lsn);
178
+ await apply(record);
179
+ }
180
+ }
181
+ }
182
+
183
+ /* -------------------------
184
+ CLEANUP
185
+ ------------------------- */
186
+
187
+ async cleanup(beforeGen: number) {
188
+ if (!fs.existsSync(this.walDir)) return;
189
+
190
+ const files = fs.readdirSync(this.walDir);
191
+ for (const f of files) {
192
+ const m = f.match(/^wal-(\d+)\.log$/);
193
+ if (!m) continue;
194
+
195
+ const gen = Number(m[1]);
196
+ if (gen < beforeGen) {
197
+ fs.unlinkSync(path.join(this.walDir, f));
198
+ }
199
+ }
200
+ }
201
+
202
+ /* -------------------------
203
+ GETTERS
204
+ ------------------------- */
205
+
206
+ getCurrentLSN() {
207
+ return this.lsn;
208
+ }
209
+
210
+ getCurrentGen() {
211
+ return this.currentGen;
212
+ }
213
+ }