上线单个审计覆盖索引并严格核验旧库的结构增量

This commit is contained in:
黄健铭 committed 2026-12-05 19:39:07 -08:00
1 parent cf0b0be83f
commit 240452d8a1
5 files changed
+230 -6

No files matched your search

+11 -5
View File
@@ -13,6 +13,7 @@ const { Session } = require('./lib/client');
const { Normalizer } = require('./lib/normalize');
const { dumpDatabase } = require('./lib/db-dump');
const { compare, report } = require('./lib/diff');
const ApprovedAuditIndex = require('./lib/approved-audit-index');
const scenario = require('./golden-scenario');
const args = process.argv.slice(2),
check = args.includes('--check'),
@@ -46,9 +47,11 @@ async function run() {
} finally {
await server.stop();
}
const dump = dumpDatabase(path.join(dataDir, 'ledger.sqlite'), {
const filename = path.join(dataDir, 'ledger.sqlite');
const dump = dumpDatabase(filename, {
mask: { users: { salt: () => MASKED, hash: () => MASKED }, sessions: { hash: () => MASKED } },
});
const auditIndex = check ? ApprovedAuditIndex.inspect(filename) : null;
fs.rmSync(dataDir, { recursive: true, force: true });
const n = new Normalizer();
n.literal(session.base, 'http://<host>');
@@ -58,7 +61,7 @@ async function run() {
// JSON 往返,去掉 undefined 字段,使内存结果与落盘基线同形。
const transcript = JSON.parse(JSON.stringify(session.entries.map(e => n.value(e))));
const db = JSON.parse(JSON.stringify(n.value(dump)));
return { transcript, db, problems: session.problems };
return { transcript, db, auditIndex, problems: session.problems };
}
function write(dir, result) {
fs.mkdirSync(dir, { recursive: true });
@@ -85,12 +88,14 @@ function describeTranscript(transcript) {
}
if (check) {
write(OUT, result);
const frozenDb = JSON.parse(fs.readFileSync(path.join(BASELINE, 'db.json'), 'utf8'));
const expected = {
transcript: JSON.parse(fs.readFileSync(path.join(BASELINE, 'transcript.json'), 'utf8')),
db: JSON.parse(fs.readFileSync(path.join(BASELINE, 'db.json'), 'utf8')),
db: { ...frozenDb, schema: ApprovedAuditIndex.expectedMaster(frozenDb.schema) },
};
const t = compare(expected.transcript, result.transcript),
d = compare(expected.db, result.db);
d = compare(expected.db, result.db),
i = compare(ApprovedAuditIndex.definition, result.auditIndex);
const describeDb = p => {
const m = p.match(/^\$\.tables\.([^.]+)\.rows\[(\d+)\]\[(\d+)\](.*)$/);
if (!m) return p;
@@ -100,11 +105,12 @@ function describeTranscript(transcript) {
const text = [
report('请求记录', t, limit, describeTranscript(expected.transcript)),
report('数据库', d, limit, describeDb),
report('批准的审计索引', i, limit),
]
.filter(Boolean)
.join('\n');
if (text) console.log(text);
const failed = t.diffs.length + d.diffs.length > 0;
const failed = t.diffs.length + d.diffs.length + i.diffs.length > 0;
console.log(
`golden ${failed ? 'FAIL' : 'PASS'}:${result.transcript.length} 条记录,${Object.keys(result.db.tables).length} 张表,用时 ${seconds}s(实际结果在 e2e/out/golden/)`,
);
+12 -1
View File
@@ -14,6 +14,7 @@ const { startServer } = require('./lib/server');
const { Session } = require('./lib/client');
const { Normalizer } = require('./lib/normalize');
const { compare, report } = require('./lib/diff');
const ApprovedAuditIndex = require('./lib/approved-audit-index');
const args = process.argv.slice(2),
check = args.includes('--check');
const FIXTURE = args.includes('--fixture')
@@ -178,6 +179,7 @@ async function run() {
unchangedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] === after.hashes[t]).length,
changedOriginalTables: Object.keys(before.hashes).filter(t => before.hashes[t] !== after.hashes[t]),
responses,
...(check ? { auditIndex: ApprovedAuditIndex.inspect(file) } : {}),
};
} finally {
fs.rmSync(dataDir, { recursive: true, force: true });
@@ -189,7 +191,16 @@ async function run() {
const seconds = ((Date.now() - started) / 1000).toFixed(1);
const integrityOk = result.before.integrity.join() === 'ok' && result.after.integrity.join() === 'ok';
if (check) {
const expected = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
const frozen = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
const expected = {
...frozen,
before: { ...frozen.before, schema: ApprovedAuditIndex.expectedLegacySchema(frozen.before.schema) },
after: {
...frozen.after,
schema: ApprovedAuditIndex.expectedLegacySchema(frozen.after.schema, { afterStartup: true }),
},
auditIndex: ApprovedAuditIndex.definition,
};
const d = compare(expected, JSON.parse(JSON.stringify(result)));
const text = report('旧库兼容', d);
if (text) console.log(text);
@@ -0,0 +1,75 @@
'use strict';
const assert = require('node:assert/strict');
const { DatabaseSync } = require('node:sqlite');
const name = 'ix_audit_entity_action_id';
const masterEntry = {
type: 'index',
name,
table: 'audit',
sql: 'CREATE INDEX ix_audit_entity_action_id ON audit(entity,action,id)',
};
const listEntry = { name, unique: 0, columns: ['entity', 'action', 'id'] };
const definition = {
...masterEntry,
unique: 0,
origin: 'c',
partial: 0,
columns: [
{ seqno: 0, cid: 1, name: 'entity', desc: 0, coll: 'BINARY', key: 1 },
{ seqno: 1, cid: 2, name: 'action', desc: 0, coll: 'BINARY', key: 1 },
{ seqno: 2, cid: 0, name: 'id', desc: 0, coll: 'BINARY', key: 1 },
{ seqno: 3, cid: -1, name: null, desc: 0, coll: 'BINARY', key: 0 },
],
};
function insertExpected(entries, entry, follows) {
const i = entries.findIndex(follows);
return entries.toSpliced(i === -1 ? entries.length : i, 0, entry);
}
function expectedMaster(entries) {
const recorded = entries.filter(entry => entry.name === name);
if (recorded.length) {
assert.deepEqual(recorded, [masterEntry], '基线中的批准审计索引定义不符');
return entries;
}
return insertExpected(entries, masterEntry, row => row.type > 'index' || (row.type === 'index' && row.name > name));
}
function expectedLegacySchema(schema, { afterStartup = false } = {}) {
const recorded = Object.entries(schema).flatMap(([table, { indexes }]) =>
indexes.filter(index => index.name === name).map(index => ({ table, ...index })),
);
if (recorded.length) {
assert.deepEqual(recorded, [{ table: masterEntry.table, ...listEntry }], '基线中的批准审计索引定义不符');
return schema;
}
if (!afterStartup) return schema;
const { audit } = schema;
const indexes = insertExpected(audit.indexes, listEntry, row => row.name > name);
return { ...schema, audit: { ...audit, indexes } };
}
function inspect(filename) {
const db = new DatabaseSync(filename, { readOnly: true });
try {
const master = db
.prepare("SELECT type,name,tbl_name AS 'table',sql FROM sqlite_master WHERE type='index' AND name=?")
.get(name);
if (!master) return null;
const flags = db
.prepare('SELECT "unique",origin,partial FROM pragma_index_list(?) WHERE name=?')
.get(master.table, name);
const columns = db
.prepare('SELECT seqno,cid,name,"desc",coll,"key" FROM pragma_index_xinfo(?) ORDER BY seqno')
.all(name)
.map(row => ({ ...row }));
return { ...master, ...flags, columns };
} finally {
db.close();
}
}
module.exports = { definition, expectedMaster, expectedLegacySchema, inspect };