import { appendFile, mkdir, readFile, readdir, stat, copyFile, writeFile, rename, } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; import { dirname, join } from 'node:path'; import type { CronMissedRecord, CronRunRecord } from './types.js'; import { withStoreLock } from './lock.js'; /** A damaged line must not hide all other runs. Preserve the file and report its location. */ const cache = new Map(); const folded = new WeakMap< object, { all: CronRunRecord[]; active: CronRunRecord[] } >(); async function records(file: string): Promise { let raw: string; let key: string; try { const info = await stat(file, { bigint: true }); key = `${info.ino}:${info.size}:${info.mtimeNs}`; if (cache.get(file)?.key === key) return cache.get(file)!.rows; raw = await readFile(file, 'utf8'); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') { cache.delete(file); return []; } throw error; } const rows = raw.split('\n').flatMap((line, index) => { if (!line.trim()) return []; try { return [JSON.parse(line)]; } catch { console.error( `[cron-runner] 损坏的日志行,保留原件:${file}:${index + 1}`, ); return []; } }); if (cache.size >= 256) cache.delete(cache.keys().next().value!); cache.set(file, { key, rows }); return rows; } async function append(file: string, record: unknown): Promise { await mkdir(dirname(file), { recursive: true }); await withStoreLock(dirname(file), async () => { // A leading separator also isolates an incomplete final line left by a crash. await appendFile(file, `\n${JSON.stringify(record)}\n`, 'utf8'); }); } export async function appendRun( runsDir: string, record: CronRunRecord, ): Promise { const file = join(runsDir, `${record.taskId}.jsonl`); await append(file, record); if ( record.status !== 'queued' && record.status !== 'running' && (await stat(file)).size > 4 * 1024 * 1024 ) await compactRunLog(runsDir, record.taskId); } /** Preserve the full raw journal before compacting old terminal payloads. IDs, * counters and plan identities stay hot for durable deduplication/recovery. */ export async function compactRunLog( runsDir: string, taskId: string, ): Promise { await withStoreLock(runsDir, async () => { const all = await recentRuns(runsDir, taskId, Infinity); const old = all .filter((r) => !['queued', 'running'].includes(r.status)) .slice(100); if (!old.some((r) => r.result !== undefined || r.snapshot !== undefined)) return; const file = join(runsDir, `${taskId}.jsonl`); const archive = join(runsDir, 'archive', `${taskId}-${randomUUID()}.jsonl`); await mkdir(dirname(archive), { recursive: true }); await copyFile(file, archive); const ids = new Set(old.map((r) => r.id)); const rows = all.map((r) => { if (!ids.has(r.id)) return r; const { result, snapshot, ...rest } = r; return { ...rest, planId: r.planId ?? snapshot?.planId, archiveFile: r.archiveFile ?? archive, }; }); const tmp = `${file}.${randomUUID()}.tmp`; await writeFile(tmp, rows.map((r) => JSON.stringify(r)).join('\n') + '\n'); await rename(tmp, file); }); } export async function recentRuns( runsDir: string, taskId: string, limit = 5, activeOnly = false, ): Promise { const rows = await records(join(runsDir, `${taskId}.jsonl`)); const prior = folded.get(rows); if (prior) return (activeOnly ? prior.active : prior.all) .slice(0, limit) .map((r) => ({ ...r })); const byId = new Map(); const reads = new Map(); for (const record of rows) { if (!record || typeof record.id !== 'string') continue; if (record.event === 'read') { reads.set(record.id, record.readAt); continue; } if (!record.status || !record.startedAt) continue; const previous = byId.get(record.id); if ( previous && !['running', 'queued'].includes(previous.status) && ['running', 'queued'].includes(record.status) ) { // Legacy versions marked read by appending a stale full record. Terminal state is monotonic. if (record.readAt) reads.set(record.id, record.readAt); continue; } byId.set(record.id, { ...byId.get(record.id), ...record }); } const all = [...byId.values()] .map((record) => reads.has(record.id) ? { ...record, readAt: reads.get(record.id) } : record, ) .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt)); const active = all.filter( (r) => r.status === 'queued' || r.status === 'running', ); folded.set(rows, { all, active }); return (activeOnly ? active : all).slice(0, limit).map((r) => ({ ...r })); } export async function markRunsRead( runsDir: string, taskId?: string, ): Promise { const ids = taskId ? [taskId] : await listRunTaskIds(runsDir); for (const id of ids) for (const run of await recentRuns(runsDir, id, Infinity)) { // Reading a running record must not mark a future result as read. if (!run.readAt && run.status !== 'running' && run.status !== 'queued') { await append(join(runsDir, `${id}.jsonl`), { event: 'read', id: run.id, readAt: new Date().toISOString(), }); } } } export async function listRunTaskIds(runsDir: string): Promise { try { return (await readdir(runsDir)) .filter((n) => n.endsWith('.jsonl')) .map((n) => n.slice(0, -6)); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; } } export async function appendMissed( file: string, record: CronMissedRecord, ): Promise { await append(file, record); } export async function listMissed( file: string, limit = 20, ): Promise { const bySlot = new Map(); const reads = new Set(); for (const parsed of await records(file)) { if (!parsed || typeof parsed.id !== 'string') continue; if (parsed.event === 'read') { reads.add(parsed.id); continue; } if (!parsed.taskId || !parsed.scheduledFor) continue; bySlot.set(`${parsed.taskId}:${parsed.scheduledFor}`, { ...parsed, reason: parsed.reason ?? 'offline', missedCount: parsed.missedCount ?? 1, }); } return [...bySlot.values()] .map((r) => (reads.has(r.id) ? { ...r, readAt: r.readAt ?? 'read' } : r)) .sort((a, b) => Date.parse(b.detectedAt) - Date.parse(a.detectedAt)) .slice(0, limit); } export async function markMissedRead( file: string, taskId?: string, ): Promise { for (const record of await listMissed(file, Infinity)) if (!record.readAt && (!taskId || record.taskId === taskId)) { await append(file, { event: 'read', id: record.id, readAt: new Date().toISOString(), }); } }