Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01VDJVpPiGiWjJP1yVvvGhzQ
This commit is contained in:
+10
-17
@@ -1,34 +1,27 @@
|
||||
// 定錨存檔:COST_MODEL_DATA_DIR/anchors.json(新檔案,不進 Git)。
|
||||
// 定錨存檔:anchors.json(存在 COST_MODEL_DATA_DIR/leadboard.db 的 documents 表;STORAGE_BACKEND=json 時是同名檔案,不進 Git)。
|
||||
// 快照一旦存下就不改;之後只會新增下一次定錨、記錄最高點與調動生效月份。
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { bindFile } from './storage.js';
|
||||
import { HALVES, anchoredCoda, anchoredInvoice, buildSnapshot, detectChanges, detectTransfers, halves } from './anchor-calc.js';
|
||||
|
||||
const emptyYear = () => ({ anchors: [], peaks: {}, transfers: {}, log: [], undone: [], peakResets: [], version: 0 });
|
||||
|
||||
export function createAnchorStore(path) {
|
||||
export function createAnchorStore(source) {
|
||||
const file = bindFile(source);
|
||||
let state = null;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
async function load() {
|
||||
if (state) return state;
|
||||
if (!path) return (state = { version: 1, years: {} });
|
||||
try {
|
||||
state = JSON.parse(await readFile(path, 'utf8'));
|
||||
if (!state || typeof state !== 'object' || !state.years) state = { version: 1, years: {} };
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
state = { version: 1, years: {} };
|
||||
}
|
||||
if (!file) return (state = { version: 1, years: {} });
|
||||
const text = file.read();
|
||||
state = text === null ? null : JSON.parse(text);
|
||||
if (!state || typeof state !== 'object' || !state.years) state = { version: 1, years: {} };
|
||||
return state;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!path) return;
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const temporary = `${path}.${process.pid}.tmp`;
|
||||
await writeFile(temporary, `${JSON.stringify(state)}\n`, { mode: 0o600 });
|
||||
await rename(temporary, path);
|
||||
if (!file) return;
|
||||
file.write(`${JSON.stringify(state)}\n`);
|
||||
}
|
||||
|
||||
// 所有寫入排隊執行,避免同時寫檔。
|
||||
|
||||
Reference in New Issue
Block a user