CI / build (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
156 lines
8.1 KiB
JavaScript
156 lines
8.1 KiB
JavaScript
// 把資料夾裡的 JSON 檔搬進 leadboard.db(可以重跑)。
|
||
// node import-json.js [--dir /app/data] [--db /app/data/leadboard.db] [--dry-run] [--verify-only] [--force]
|
||
// 規則:
|
||
// - 檔案內容原樣存進 documents(不重新排版、不改順序),再讀回來逐筆核對。
|
||
// - 重跑安全:DB 裡已經有、內容相同的略過;DB 裡已經有、內容不同的「不覆蓋」(那可能是上線後的新資料),
|
||
// 列為衝突並以非 0 結束;確定要用 JSON 蓋掉才加 --force。
|
||
// - 任何一個檔案不是合法 JSON,整批都不寫入。
|
||
// - 不會刪除或修改 JSON 檔。
|
||
import { readFileSync, readdirSync } from 'node:fs';
|
||
import { resolve } from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
import { isDeepStrictEqual } from 'node:util';
|
||
import { openDatabase } from './db.js';
|
||
import { sha256 } from './storage.js';
|
||
|
||
// 要搬的檔案:資料夾第一層的 *.json(含 month-overrides-<年>.json)和 archives/*.json。暫存檔(*.tmp)不算。
|
||
const TOP_LEVEL = /^[A-Za-z0-9][A-Za-z0-9._-]*\.json$/;
|
||
const ARCHIVE = /^\d{4}\.json$/;
|
||
|
||
export function discover(dir) {
|
||
const names = [];
|
||
const entries = (path) => { try { return readdirSync(path, { withFileTypes: true }); } catch (error) { if (error.code === 'ENOENT') return []; throw error; } };
|
||
for (const entry of entries(dir)) if (entry.isFile() && TOP_LEVEL.test(entry.name)) names.push(entry.name);
|
||
for (const entry of entries(resolve(dir, 'archives'))) if (entry.isFile() && ARCHIVE.test(entry.name)) names.push(`archives/${entry.name}`);
|
||
return names.sort();
|
||
}
|
||
|
||
// 「筆」:最上層是陣列就每個元素一筆;是物件就每個欄位一筆,欄位的值若是陣列或物件,再往下算一層(例如 grants 裡每個人、history 每一則)。
|
||
export function records(value) {
|
||
const out = [];
|
||
const add = (key, item) => out.push([key, item]);
|
||
const expand = (prefix, item) => {
|
||
if (Array.isArray(item)) item.forEach((entry, index) => add(`${prefix}[${index}]`, entry));
|
||
else if (item && typeof item === 'object') for (const [key, entry] of Object.entries(item)) add(`${prefix}.${key}`, entry);
|
||
else add(prefix, item);
|
||
};
|
||
if (Array.isArray(value)) value.forEach((entry, index) => add(`[${index}]`, entry));
|
||
else if (value && typeof value === 'object') for (const [key, entry] of Object.entries(value)) expand(key, entry);
|
||
else add('(value)', value);
|
||
return out;
|
||
}
|
||
|
||
// 逐筆核對兩份已解析的資料;回傳筆數與不一致的位置。
|
||
export function compareRecords(expected, actual) {
|
||
const left = new Map(records(expected));
|
||
const right = new Map(records(actual));
|
||
const bad = [];
|
||
for (const [key, item] of left) if (!right.has(key) || !isDeepStrictEqual(item, right.get(key))) bad.push(key);
|
||
for (const key of right.keys()) if (!left.has(key)) bad.push(key);
|
||
return { count: left.size, bad };
|
||
}
|
||
|
||
function readSources(dir, names) {
|
||
const sources = [];
|
||
const problems = [];
|
||
for (const name of names) {
|
||
const text = readFileSync(resolve(dir, name), 'utf8');
|
||
try { sources.push({ name, text, data: JSON.parse(text) }); } catch (error) { problems.push(`${name}:不是合法的 JSON(${error.message})`); }
|
||
}
|
||
return { sources, problems };
|
||
}
|
||
|
||
// mode: 'import'(預設)|'dry-run'|'verify'。回傳 { ok, files, imported, unchanged, conflicts, records, problems }。
|
||
export function importJson({ dir, db, mode = 'import', force = false, now = () => new Date().toISOString() }) {
|
||
const startedAt = now();
|
||
const names = discover(dir);
|
||
const { sources, problems } = readSources(dir, names);
|
||
const select = db.prepare('SELECT body, sha256, bytes FROM documents WHERE name = ?');
|
||
const files = [];
|
||
let imported = 0, unchanged = 0, conflicts = 0, checked = 0;
|
||
const writes = [];
|
||
|
||
for (const source of sources) {
|
||
const row = select.get(source.name);
|
||
const file = { name: source.name, bytes: Buffer.byteLength(source.text, 'utf8'), records: records(source.data).length, status: '' };
|
||
if (!row) file.status = mode === 'verify' ? '資料庫沒有' : '新增';
|
||
else if (row.body === source.text) file.status = '相同';
|
||
else file.status = mode !== 'verify' && force ? '覆蓋' : '內容不同';
|
||
if (file.status === '新增' || file.status === '覆蓋') writes.push(source);
|
||
if (file.status === '內容不同') conflicts += 1;
|
||
if (file.status === '資料庫沒有') conflicts += 1;
|
||
if (file.status === '相同') unchanged += 1;
|
||
files.push(file);
|
||
}
|
||
|
||
if (mode === 'import' && !problems.length && writes.length) {
|
||
const upsert = db.prepare(`INSERT INTO documents (name, body, sha256, bytes, updated_at) VALUES (?, ?, ?, ?, ?)
|
||
ON CONFLICT(name) DO UPDATE SET body = excluded.body, sha256 = excluded.sha256, bytes = excluded.bytes, updated_at = excluded.updated_at`);
|
||
db.exec('BEGIN IMMEDIATE');
|
||
try {
|
||
for (const source of writes) upsert.run(source.name, source.text, sha256(source.text), Buffer.byteLength(source.text, 'utf8'), now());
|
||
db.exec('COMMIT');
|
||
} catch (error) { db.exec('ROLLBACK'); throw error; }
|
||
imported = writes.length;
|
||
}
|
||
|
||
// 核對:把剛剛(或先前)存進資料庫的內容讀回來,跟檔案逐筆比。
|
||
if (mode !== 'dry-run' && !problems.length) {
|
||
for (const file of files) {
|
||
const source = sources.find(item => item.name === file.name);
|
||
const row = select.get(file.name);
|
||
if (!row) continue;
|
||
if (row.body !== source.text) continue; // 內容不同/未覆蓋:已列為衝突,不是搬運錯誤
|
||
let stored;
|
||
try { stored = JSON.parse(row.body); } catch { stored = undefined; }
|
||
const compared = compareRecords(source.data, stored);
|
||
checked += compared.count;
|
||
file.checked = compared.count;
|
||
if (compared.bad.length || row.sha256 !== sha256(source.text) || row.bytes !== file.bytes) {
|
||
file.status = '核對失敗';
|
||
file.bad = compared.bad.slice(0, 20);
|
||
conflicts += 1;
|
||
}
|
||
}
|
||
}
|
||
|
||
const ok = !problems.length && !conflicts;
|
||
const summary = { ok, mode, dir, files, imported, unchanged, conflicts, records: checked, problems };
|
||
if (mode !== 'dry-run') {
|
||
db.prepare(`INSERT INTO import_log (started_at, finished_at, source_dir, mode, imported, unchanged, conflicts, records_checked, ok, detail)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(startedAt, now(), dir, force ? `${mode}+force` : mode, imported, unchanged, conflicts, checked, ok ? 1 : 0,
|
||
JSON.stringify({ files: files.map(({ name, status, records: count }) => ({ name, status, records: count })), problems }));
|
||
}
|
||
return summary;
|
||
}
|
||
|
||
export function formatReport(result) {
|
||
const lines = [`資料夾:${result.dir}(模式:${result.mode})`];
|
||
for (const file of result.files) {
|
||
lines.push(` ${file.status.padEnd(6, ' ')} ${file.name}(${file.bytes} bytes,${file.records} 筆${file.checked !== undefined ? `,已核對 ${file.checked} 筆` : ''})${file.bad ? ` 不一致:${file.bad.join(', ')}` : ''}`);
|
||
}
|
||
for (const problem of result.problems) lines.push(` 錯誤 ${problem}`);
|
||
lines.push(`新增或覆蓋 ${result.imported}、相同 ${result.unchanged}、衝突 ${result.conflicts}、核對 ${result.records} 筆 → ${result.ok ? '全部一致' : '有問題,請看上面'}`);
|
||
return lines.join('\n');
|
||
}
|
||
|
||
function main(argv) {
|
||
const args = new Map();
|
||
for (let index = 0; index < argv.length; index += 1) {
|
||
if (!argv[index].startsWith('--')) continue;
|
||
const key = argv[index].slice(2);
|
||
args.set(key, ['dir', 'db'].includes(key) ? argv[++index] : true);
|
||
}
|
||
const dir = resolve(args.get('dir') || process.env.COST_MODEL_DATA_DIR || '/app/data');
|
||
const dbPath = resolve(args.get('db') || resolve(dir, 'leadboard.db'));
|
||
const mode = args.get('dry-run') ? 'dry-run' : args.get('verify-only') ? 'verify' : 'import';
|
||
const db = openDatabase(dbPath);
|
||
try {
|
||
const result = importJson({ dir, db, mode, force: Boolean(args.get('force')) });
|
||
console.log(formatReport(result));
|
||
process.exitCode = result.ok ? 0 : 1;
|
||
} finally { db.close(); }
|
||
}
|
||
|
||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(process.argv.slice(2));
|