104 lines
6.3 KiB
JavaScript
104 lines
6.3 KiB
JavaScript
/** Read-only preview bridge. Kept outside codex_pcb so approved jobs retain their source fingerprint. */
|
|
import { readFile, readdir, stat, realpath, mkdir, writeFile, rename } from 'node:fs/promises';
|
|
import { resolve, sep } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { execFile } from 'node:child_process';
|
|
import { promisify } from 'node:util';
|
|
import { createHash } from 'node:crypto';
|
|
const exec = promisify(execFile);
|
|
const captureScript = fileURLToPath(new URL('./capture-preview.py', import.meta.url));
|
|
const validTask = /^pcb-[0-9a-f]{24}$/;
|
|
const kindOf = name => /schematic|sch[-_.]|原理图/i.test(name) ? 'schematic' : /render|assembly|assembled|3d|三维/i.test(name) ? '3d' : /pcb|layout|routing|routed|copper|布线|布局/i.test(name) ? 'layout' : null;
|
|
|
|
async function exportedFrame(directory, requested) {
|
|
const base = await realpath(directory).catch(() => null);
|
|
if (!base || base !== resolve(directory)) return null;
|
|
const candidates = [];
|
|
let visited = 0;
|
|
async function walk(folder, depth) {
|
|
if (depth > 3) return;
|
|
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
|
if (++visited > 2000) return;
|
|
const path = resolve(folder, entry.name);
|
|
if (entry.isDirectory()) await walk(path, depth + 1);
|
|
if (!entry.isFile() || !/\.(png|jpe?g)$/i.test(entry.name)) continue;
|
|
const kind = kindOf(entry.name);
|
|
if (!kind || (requested !== 'auto' && requested !== kind)) continue;
|
|
const info = await stat(path);
|
|
if (info.size > 0 && info.size <= 8 * 1024 * 1024) candidates.push({ path, kind, at: info.mtimeMs });
|
|
}
|
|
}
|
|
await walk(base, 0);
|
|
candidates.sort((a, b) => b.at - a.at);
|
|
for (const item of candidates.slice(0, 5)) {
|
|
// Recheck real path and file stability; never serve a link outside this task.
|
|
const path = await realpath(item.path);
|
|
if (!path.startsWith(base + sep)) continue;
|
|
const before = await stat(path), bytes = await readFile(path), after = await stat(path);
|
|
if (before.mtimeMs !== after.mtimeMs || bytes.length !== after.size) continue;
|
|
const png = bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]));
|
|
const jpg = bytes[0] === 255 && bytes[1] === 216 && bytes.at(-2) === 255 && bytes.at(-1) === 217;
|
|
if (!png && !jpg) continue;
|
|
return { kind: item.kind, capturedAt: after.mtimeMs, source: 'export', image: `data:image/${png ? 'png' : 'jpeg'};base64,${bytes.toString('base64')}` };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function createPreviewHandler({ runtime = process.env.PCB_SESSION_ROOT || '/home/wpz/auto_pcb_2/persistent-runtime', capture = async tid => {
|
|
const { stdout } = await exec('python3', [captureScript, tid], { timeout: 6500, maxBuffer: 12 * 1024 * 1024 });
|
|
return JSON.parse(stdout);
|
|
} } = {}) {
|
|
const cache = new Map(), pending = new Map(), captureAfter = new Map();
|
|
let capturing = false;
|
|
async function preview(tid, kind) {
|
|
// Canonicalize the configured root so OS aliases such as macOS /tmp do
|
|
// not look like task-owned symlinks to exportedFrame's containment check.
|
|
const runtimeRoot = await realpath(runtime);
|
|
const task = JSON.parse(await readFile(resolve(runtimeRoot, 'tasks', tid, 'state.json'), 'utf8'));
|
|
let frame = null, reason = 'waiting_for_canvas';
|
|
const savedPath = resolve(runtimeRoot, 'web-previews', `${tid}.json`);
|
|
if (task.approval && task.eda_session && task.state === 'running' && !capturing && Date.now() >= (captureAfter.get(tid) || 0)) {
|
|
capturing = true;
|
|
if (captureAfter.size > 100) captureAfter.delete(captureAfter.keys().next().value);
|
|
captureAfter.set(tid, Date.now() + 5000);
|
|
try {
|
|
const value = await capture(tid);
|
|
reason = value.reason || '';
|
|
if (value.available && ['schematic', 'layout', '3d'].includes(value.kind) && /^data:image\/png;base64,/.test(value.image)) {
|
|
frame = { kind: value.kind, capturedAt: Date.now(), source: 'canvas', image: value.image };
|
|
await mkdir(resolve(runtimeRoot, 'web-previews'), { recursive: true });
|
|
await writeFile(savedPath + '.tmp', JSON.stringify(frame));
|
|
await rename(savedPath + '.tmp', savedPath);
|
|
}
|
|
} catch { reason = 'canvas_unavailable'; captureAfter.set(tid, Date.now() + 30000); }
|
|
finally { capturing = false; }
|
|
} else if (capturing) reason = 'eda_busy';
|
|
if (!frame) frame = await readFile(savedPath, 'utf8').then(JSON.parse).catch(() => null);
|
|
if (frame && kind !== 'auto' && frame.kind !== kind) frame = null;
|
|
const exported = await exportedFrame(resolve(runtimeRoot, 'tasks', tid, 'workspace', 'artifacts'), kind).catch(() => null);
|
|
if (exported && (!frame || exported.capturedAt > frame.capturedAt)) frame = exported;
|
|
return { taskId: tid, frame, reason, refreshSeconds: 5 };
|
|
}
|
|
return async function handle(req, res, path, searchParams) {
|
|
const tid = path, kind = searchParams.get('kind') || 'auto';
|
|
const reply = (code, body) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(JSON.stringify(body)); };
|
|
if (req.method !== 'GET') return reply(405, { message: '预览只支持读取' });
|
|
if (!validTask.test(tid) || !['auto', 'schematic', 'layout', '3d'].includes(kind)) return reply(400, { message: '无效的预览请求' });
|
|
const key = `${tid}/${kind}`;
|
|
try {
|
|
let entry = cache.get(key);
|
|
if (!entry || Date.now() - entry.at > 5000) {
|
|
if (!pending.has(key)) pending.set(key, preview(tid, kind).then(value => {
|
|
if (cache.size >= 12) cache.delete(cache.keys().next().value);
|
|
const body = JSON.stringify(value);
|
|
const result = { value, body, etag: '"' + createHash('sha256').update(body).digest('hex') + '"', at: Date.now() }; cache.set(key, result); return result;
|
|
}).finally(() => pending.delete(key)));
|
|
entry = await pending.get(key);
|
|
}
|
|
const headers = { 'content-type': 'application/json', 'cache-control': 'no-cache', 'x-content-type-options': 'nosniff', etag: entry.etag };
|
|
if (req.headers?.['if-none-match'] === entry.etag) { res.writeHead(304, headers); res.end(); return; }
|
|
res.writeHead(200, headers); res.end(entry.body);
|
|
} catch (error) { reply(error.code === 'ENOENT' ? 404 : 503, { message: '画面暂不可用,稍后自动重试' }); }
|
|
};
|
|
}
|