mpackdb
All repositories: gitoria
5.2 KB
// 1.0.8: indexes must never be trusted blindly. Covers// - bug 1 (find(pk) after update/delete + restart compaction)// - bug 2 (hard kill without close, indexes not persisted)// - stale index files that do not match the data file (index from before a compaction, torn index line)// - stores written by mpackdb 1.0.6 (set MPACKDB_106=<path to 1.0.6 src/MPackDB.js> to enable)// MPACKDB_LIB=<path to MPackDB.js> runs the same checks against another version (e.g. 1.0.7) to show they fail there.import { rm, cp, readFile, writeFile, readdir } from 'node:fs/promises';import { resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';import { spawnSync } from 'node:child_process';import assert from 'node:assert/strict';const here = dirname(fileURLToPath(import.meta.url));const lib = resolve(process.env.MPACKDB_LIB || resolve(here, '../src/MPackDB.js'));const { MPackDB } = await import(lib);const base = resolve(here, 'db/index-recovery');await rm(base, { recursive: true, force: true });const opts = { primaryKey: 'sessionId', indexes: ['userId'], indexPersistInterval: 0 };let failures = 0;async function check(name, fn) {try { await fn(); console.log('✓', name); } catch (e) { failures++; console.log('✗', name, '-', e.message.split('\n')[0]); }}async function findAll(db, ids) {for (const id of ids) {const r = await db.find(id).toArray();assert.equal(r.length, 1, `find(${id}) returned ${r.length}`);assert.equal(r[0].sessionId, id);}}const seed = async (dir, n = 7) => {const db = new MPackDB(`${dir}/sessions`, opts);for (let i = 0; i < n; i++) await db.insert({ sessionId: 's' + i, userId: 'u' + (i % 3), n: i, pad: 'x'.repeat(10 + i * 7) });return db;};await check('bug1: update+delete, close, reopen (compaction), find(pk) for all', async () => {const dir = `${base}/bug1`;let db = await seed(dir);await db.update('s1', r => ({ ...r, n: 100 }));await db.update('s4', r => ({ ...r, n: 400, extra: 'longer value'.repeat(5) }));await db.delete('s2');await db.close();db = new MPackDB(`${dir}/sessions`, opts);await findAll(db, ['s0', 's1', 's3', 's4', 's5', 's6']);assert.equal((await db.find('s2').toArray()).length, 0);assert.equal((await db.find(() => true).toArray()).length, 6);await db.close();});await check('bug2: SIGKILL without close, reopen, find(pk) for all', () => {const r = spawnSync(process.execPath, [resolve(here, 'repro-bug2-hardkill.mjs'), lib, `${base}/bug2`], { encoding: 'utf8' });assert.equal(r.status, 0, r.stdout.trim().split('\n').slice(-2).join(' | '));});await check('stale index files from before a compaction are detected (compact:false open)', async () => {const dir = `${base}/stale`;let db = await seed(dir);await db.close(); // persists indexes + idxstate for the 7 recordsconst files = (await readdir(dir)).filter(f => f.endsWith('.txt') || f.endsWith('.idxstate.json'));const saved = {};for (const f of files) saved[f] = await readFile(`${dir}/${f}`);db = new MPackDB(`${dir}/sessions`, opts);await db.delete('s0'); await db.delete('s3');await db.close();db = new MPackDB(`${dir}/sessions`, opts); // compaction shifts every offsetawait db.init();assert.equal((await db.find(() => true).toArray()).length, 5);await db.close();for (const f of files) await writeFile(`${dir}/${f}`, saved[f]); // simulate crash before index rebuilddb = new MPackDB(`${dir}/sessions`, { ...opts, compact: false });await findAll(db, ['s1', 's2', 's4', 's5', 's6']);assert.equal((await db.find('s0').toArray()).length, 0);await db.close();});await check('torn index line is detected and the index rebuilt', async () => {const dir = `${base}/torn`;let db = await seed(dir);await db.close();const f = `${dir}/sessions.sessionId.txt`;const txt = await readFile(f, 'utf8');await writeFile(f, txt.slice(0, txt.length - 6)); // cut the last linedb = new MPackDB(`${dir}/sessions`, { ...opts, compact: false });await findAll(db, ['s0', 's1', 's2', 's3', 's4', 's5', 's6']);await db.close();});const old = process.env.MPACKDB_106;if (old) {for (const scenario of ['compact-bug', 'hardkill']) {await check(`1.0.6-written store (${scenario}) opens, repairs and finds every pk`, async () => {const dir = `${base}/old-${scenario}`;spawnSync(process.execPath, [resolve(here, 'helpers/stage-old.mjs'), resolve(old), dir, scenario]);const expect = scenario === 'compact-bug' ? ['s0', 's1', 's3', 's4', 's5', 's6'] : ['s0', 's1', 's2', 's3', 's4', 's6', 's7', 's8'];for (const compact of [false, true]) {const copy = `${dir}-copy-${compact}`;await cp(dir, copy, { recursive: true });const db = new MPackDB(`${copy}/sessions`, { ...opts, compact });await findAll(db, expect);assert.equal((await db.find(() => true).toArray()).length, expect.length);await db.close();// and a second open (now with 1.0.8 state files) still worksconst db2 = new MPackDB(`${copy}/sessions`, { ...opts, compact });await findAll(db2, expect);await db2.close();}});}} else console.log('- 1.0.6 compatibility checks skipped (set MPACKDB_106)');await rm(base, { recursive: true, force: true });console.log(failures ? `FAIL: ${failures}` : 'ALL PASS');process.exit(failures ? 1 : 0);
Branches
- mastermain branch
Latest commits
- cde6b2751.0.8: validate indexes against the data file on open, atomic index writes, invalidate index state before compaction; tests for pk find after compaction and hard killmre
- 87888725release 1.0.7caramboleyo
- c4cdb9b6node: import prefixes (Deno compat) + pre-existing index-state WIPcaramboleyo
- 0afb8f4bupdate now must be a callbackcaramboleyo
- cde73eb4release 1.0.6caramboleyo
- d01dda02add index hints, intersection, boundingBox; remove findByIndexcaramboleyo
- b8ffc1a0release 1.0.5caramboleyo
- d47876a1reimplemented lost features like indexed find and more testscaramboleyo
- 7f08da9afixed insert ignoring model definitioncaramboleyo
- 705774a9added flush before findcaramboleyo
- b4db6391initial commitcaramboleyo