import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import { compare } from '../lib/diff.js'; import { dumpDatabase } from '../lib/db-dump.js'; export function readOnlyPost(endpoint) { if (endpoint === '/api/material-pools/quote') return '料池报价'; if (endpoint === '/api/recoveries/quote') return '回收报价'; if (/^\/api\/recoveries\/[^/]+\/quote$/.test(endpoint)) return '更正回收报价'; if (/^\/api\/orders\/[^/]+\/after-sale-preview$/.test(endpoint)) return '订单售后预览'; return ''; } // 浏览器可能在报价同时保存另一笔单。取当时的 SQLite 一致性副本,在独占副本上 // 重放已经由 UI 实际发出的报价,核对全部表。业务用例在同一输入条件下另行比对两版报价。副本与请求头只保存在本次临时环境。 export class ReadOnlyChecks { constructor(dir) { this.dir = dir; this.samples = new Map(); } begin(kind, req) { if (!kind || this.samples.has(kind)) return; const dir = fs.mkdtempSync(path.join(this.dir, 'quote-')); const db = new DatabaseSync(path.join(this.dir, 'ledger.sqlite'), { readOnly: true }); try { db.prepare('VACUUM INTO ?').run(path.join(dir, 'ledger.sqlite')); } finally { db.close(); } return { dir, kind, path: new URL(req.url()).pathname, data: req.postData(), headers: req.allHeaders() }; } finish(sample, res) { if (sample && res.status() === 200 && !this.samples.has(sample.kind)) { this.samples.set(sample.kind, sample); } } async verify(launch, clockStart) { for (const sample of this.samples.values()) { const server = launch({ dataDir: sample.dir, clockStart }); try { const { base } = await server.ready(); const filename = path.join(sample.dir, 'ledger.sqlite'); const before = dumpDatabase(filename); const headers = await sample.headers; const res = await fetch(base + sample.path, { method: 'POST', headers: { origin: base, 'content-type': 'application/json', 'x-requested-with': headers['x-requested-with'], cookie: headers.cookie, ...(headers['x-ledger-user'] ? { 'x-ledger-user': headers['x-ledger-user'] } : {}), }, body: sample.data, }); assert.equal(res.status, 200, sample.kind + ' 重放失败'); await res.arrayBuffer(); const difference = compare(before, dumpDatabase(filename)).diffs[0]; assert.ok(!difference, sample.kind + ' 改写数据库 ' + difference?.path); } finally { await server.stop(); } } return Array.from(this.samples.keys()); } }