@liorandb/core 1.0.18 → 1.1.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,268 @@
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; // 16MB
20
+ const WAL_DIR = "__wal";
21
+
22
+ /* =========================
23
+ CRC32 (no deps)
24
+ ========================= */
25
+
26
+ const CRC32_TABLE = (() => {
27
+ const table = new Uint32Array(256);
28
+ for (let i = 0; i < 256; i++) {
29
+ let c = i;
30
+ for (let k = 0; k < 8; k++) {
31
+ c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
32
+ }
33
+ table[i] = c >>> 0;
34
+ }
35
+ return table;
36
+ })();
37
+
38
+ function crc32(input: string): number {
39
+ let crc = 0xffffffff;
40
+ for (let i = 0; i < input.length; i++) {
41
+ crc = CRC32_TABLE[(crc ^ input.charCodeAt(i)) & 0xff] ^ (crc >>> 8);
42
+ }
43
+ return (crc ^ 0xffffffff) >>> 0;
44
+ }
45
+
46
+ /* =========================
47
+ WAL MANAGER
48
+ ========================= */
49
+
50
+ export class WALManager {
51
+ private walDir: string;
52
+ private currentGen = 1;
53
+ private lsn = 0;
54
+ private fd: fs.promises.FileHandle | null = null;
55
+
56
+ constructor(baseDir: string) {
57
+ this.walDir = path.join(baseDir, WAL_DIR);
58
+ fs.mkdirSync(this.walDir, { recursive: true });
59
+
60
+ this.currentGen = this.detectLastGeneration();
61
+ this.recoverLSNFromExistingLogs();
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) {
84
+ const gen = Number(m[1]);
85
+ if (!Number.isNaN(gen)) {
86
+ max = Math.max(max, gen);
87
+ }
88
+ }
89
+ }
90
+
91
+ return max || 1;
92
+ }
93
+
94
+ private recoverLSNFromExistingLogs() {
95
+ const files = this.getSortedWalFiles();
96
+
97
+ for (const file of files) {
98
+ const filePath = path.join(this.walDir, file);
99
+ const lines = fs.readFileSync(filePath, "utf8").split("\n");
100
+
101
+ for (const line of lines) {
102
+ if (!line.trim()) continue;
103
+
104
+ try {
105
+ const parsed: StoredRecord = JSON.parse(line);
106
+ const { crc, ...record } = parsed;
107
+
108
+ if (crc32(JSON.stringify(record)) !== crc) break;
109
+
110
+ this.lsn = Math.max(this.lsn, record.lsn);
111
+ } catch {
112
+ break; // stop on corruption
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ private getSortedWalFiles(): string[] {
119
+ return fs
120
+ .readdirSync(this.walDir)
121
+ .filter(f => /^wal-\d+\.log$/.test(f))
122
+ .sort((a, b) => {
123
+ const ga = Number(a.match(/^wal-(\d+)\.log$/)![1]);
124
+ const gb = Number(b.match(/^wal-(\d+)\.log$/)![1]);
125
+ return ga - gb;
126
+ });
127
+ }
128
+
129
+ private async open() {
130
+ if (!this.fd) {
131
+ this.fd = await fs.promises.open(this.walPath(), "a");
132
+ }
133
+ }
134
+
135
+ private async rotate() {
136
+ if (this.fd) {
137
+ await this.fd.sync();
138
+ await this.fd.close();
139
+ this.fd = null;
140
+ }
141
+ this.currentGen++;
142
+ }
143
+
144
+ /* -------------------------
145
+ APPEND (Crash-safe)
146
+ ------------------------- */
147
+
148
+ async append(record: Omit<WALRecord, "lsn">): Promise<number> {
149
+ await this.open();
150
+
151
+ const full: WALRecord = {
152
+ ...(record as any),
153
+ lsn: ++this.lsn
154
+ };
155
+
156
+ const body = JSON.stringify(full);
157
+
158
+ const stored: StoredRecord = {
159
+ ...full,
160
+ crc: crc32(body)
161
+ };
162
+
163
+ const line = JSON.stringify(stored) + "\n";
164
+
165
+ await this.fd!.write(line);
166
+ await this.fd!.sync();
167
+
168
+ const stat = await this.fd!.stat();
169
+ if (stat.size >= MAX_WAL_SIZE) {
170
+ await this.rotate();
171
+ }
172
+
173
+ return full.lsn;
174
+ }
175
+
176
+ /* -------------------------
177
+ REPLAY (Auto-heal tail)
178
+ ------------------------- */
179
+
180
+ async replay(
181
+ fromLSN: number,
182
+ apply: (r: WALRecord) => Promise<void>
183
+ ): Promise<void> {
184
+ if (!fs.existsSync(this.walDir)) return;
185
+
186
+ const files = this.getSortedWalFiles();
187
+
188
+ for (const file of files) {
189
+ const filePath = path.join(this.walDir, file);
190
+
191
+ const fd = fs.openSync(filePath, "r+");
192
+ const content = fs.readFileSync(filePath, "utf8");
193
+ const lines = content.split("\n");
194
+
195
+ let validOffset = 0;
196
+
197
+ for (let i = 0; i < lines.length; i++) {
198
+ const line = lines[i];
199
+ if (!line.trim()) {
200
+ validOffset += line.length + 1;
201
+ continue;
202
+ }
203
+
204
+ let parsed: StoredRecord;
205
+
206
+ try {
207
+ parsed = JSON.parse(line);
208
+ } catch {
209
+ break;
210
+ }
211
+
212
+ const { crc, ...record } = parsed;
213
+ const expected = crc32(JSON.stringify(record));
214
+
215
+ if (expected !== crc) {
216
+ break;
217
+ }
218
+
219
+ validOffset += line.length + 1;
220
+
221
+ if (record.lsn <= fromLSN) continue;
222
+
223
+ this.lsn = Math.max(this.lsn, record.lsn);
224
+ await apply(record);
225
+ }
226
+
227
+ // Truncate corrupted tail (auto-heal)
228
+ const stat = fs.fstatSync(fd);
229
+ if (validOffset < stat.size) {
230
+ fs.ftruncateSync(fd, validOffset);
231
+ }
232
+
233
+ fs.closeSync(fd);
234
+ }
235
+ }
236
+
237
+ /* -------------------------
238
+ CLEANUP
239
+ ------------------------- */
240
+
241
+ async cleanup(beforeGen: number) {
242
+ if (!fs.existsSync(this.walDir)) return;
243
+
244
+ const files = fs.readdirSync(this.walDir);
245
+
246
+ for (const f of files) {
247
+ const m = f.match(/^wal-(\d+)\.log$/);
248
+ if (!m) continue;
249
+
250
+ const gen = Number(m[1]);
251
+ if (gen < beforeGen) {
252
+ fs.unlinkSync(path.join(this.walDir, f));
253
+ }
254
+ }
255
+ }
256
+
257
+ /* -------------------------
258
+ GETTERS
259
+ ------------------------- */
260
+
261
+ getCurrentLSN() {
262
+ return this.lsn;
263
+ }
264
+
265
+ getCurrentGen() {
266
+ return this.currentGen;
267
+ }
268
+ }