233 lines
9.6 KiB
Python
233 lines
9.6 KiB
Python
"""Task-scoped, read-only canvas snapshots served by the existing PCB API."""
|
|
import asyncio
|
|
import base64
|
|
from collections import OrderedDict
|
|
from dataclasses import dataclass
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import re
|
|
import time
|
|
|
|
from . import eda, storage
|
|
|
|
|
|
KINDS = {'schematic', 'layout', '3d'}
|
|
MAX_IMAGE_BYTES = 8 * 1024 * 1024
|
|
PNG = b'\x89PNG\r\n\x1a\n'
|
|
CAPTURE_CODE = r'''const doc = await eda.dmt_SelectControl.getCurrentDocumentInfo();
|
|
if (!doc || ![1,3,12,15].includes(doc.documentType)) return {available:false};
|
|
const image = await eda.dmt_EditorControl.getCurrentRenderedAreaImage(doc.tabId);
|
|
if (!image || !image.size || image.size > 8*1024*1024) return {available:false};
|
|
const data = await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(image);});
|
|
return {available:true,kind:doc.documentType===1?'schematic':doc.documentType===15?'3d':'layout',image:data};'''
|
|
|
|
|
|
async def capture_canvas(task):
|
|
session = task.get('eda_session')
|
|
if (not task.get('approval') or task.get('state') != 'running'
|
|
or not isinstance(session, str) or not re.fullmatch(r'[0-9a-f-]{36}', session)):
|
|
return {'available': False, 'reason': 'waiting_for_canvas'}
|
|
# Never queue behind generation, acquire its exact same process/host locks.
|
|
if eda.EDA_LOCK.locked():
|
|
return {'available': False, 'reason': 'eda_busy'}
|
|
async with eda.EDA_LOCK:
|
|
path = Path.home() / '.local/state/ai-pcb-eda/locks/host.lock'
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with path.open('a+') as fd:
|
|
try:
|
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError:
|
|
return {'available': False, 'reason': 'eda_busy'}
|
|
try:
|
|
# Reuse native transport, executable and DISPLAY/XDG settings.
|
|
value = await eda.cli(['invoke', '--session', session, '--ext-uuid', 'eda',
|
|
'--code-file', '-', '--timeout', '3000'], CAPTURE_CODE, timeout=5)
|
|
return value if isinstance(value, dict) else {'available': False, 'reason': 'canvas_unavailable'}
|
|
finally:
|
|
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
|
|
|
|
def image_mime(raw):
|
|
if raw.startswith(PNG):
|
|
return 'png'
|
|
if raw.startswith(b'\xff\xd8') and raw.endswith(b'\xff\xd9'):
|
|
return 'jpeg'
|
|
return None
|
|
|
|
|
|
def valid_frame(frame):
|
|
if (not isinstance(frame, dict) or not isinstance(frame.get('kind'), str)
|
|
or frame['kind'] not in KINDS or not isinstance(frame.get('source'), str)
|
|
or frame['source'] not in {'canvas', 'export'}):
|
|
return None
|
|
at, image = frame.get('capturedAt'), frame.get('image')
|
|
if (not isinstance(at, (int, float)) or not math.isfinite(at)
|
|
or not isinstance(image, str) or len(image) > 4 * ((MAX_IMAGE_BYTES + 2) // 3) + 32):
|
|
return None
|
|
try:
|
|
header, encoded = image.split(',', 1)
|
|
raw = base64.b64decode(encoded, validate=True)
|
|
mime = image_mime(raw)
|
|
if (not 0 < len(raw) <= MAX_IMAGE_BYTES or not mime
|
|
or header != f'data:image/{mime};base64'):
|
|
return None
|
|
except ValueError:
|
|
return None
|
|
return {key: frame[key] for key in ('kind', 'image', 'capturedAt', 'source')}
|
|
|
|
|
|
def exported_frame(directory, requested):
|
|
# Canonicalize the runtime before calling this; reject task-owned symlinks.
|
|
if not directory.is_dir() or directory.resolve() != directory:
|
|
return None
|
|
candidates, visited = [], 0
|
|
|
|
def walk(folder, depth):
|
|
nonlocal visited
|
|
if depth > 3:
|
|
return
|
|
for path in folder.iterdir():
|
|
visited += 1
|
|
if visited > 2000:
|
|
return
|
|
if path.is_symlink():
|
|
continue
|
|
if path.is_dir():
|
|
walk(path, depth + 1)
|
|
elif path.is_file() and path.suffix.lower() in {'.png', '.jpg', '.jpeg'}:
|
|
kind = next((kind for pattern, kind in (
|
|
(r'schematic|sch[-_.]|原理图', 'schematic'),
|
|
(r'render|assembly|assembled|3d|三维', '3d'),
|
|
(r'pcb|layout|routing|routed|copper|布线|布局', 'layout'),
|
|
# Older tasks exported these names under artifacts/preview/.
|
|
(r'(^|[-_.])circuit([-_.]|$)', 'schematic'),
|
|
(r'(^|[-_.])placement([-_.]|$)', 'layout'),
|
|
) if re.search(pattern, path.name, re.I)), None)
|
|
if kind and requested in {'auto', kind}:
|
|
info = path.stat()
|
|
if 0 < info.st_size <= MAX_IMAGE_BYTES:
|
|
candidates.append((info.st_mtime_ns, path, kind))
|
|
|
|
walk(directory, 0)
|
|
for _, path, kind in sorted(candidates, key=lambda item: item[0], reverse=True)[:5]:
|
|
try:
|
|
if path.is_symlink() or not path.resolve().is_relative_to(directory):
|
|
continue
|
|
before = path.stat()
|
|
with path.open('rb') as stream:
|
|
raw = stream.read(MAX_IMAGE_BYTES + 1)
|
|
after = path.stat()
|
|
mime = image_mime(raw)
|
|
if (not mime or len(raw) > MAX_IMAGE_BYTES or len(raw) != after.st_size
|
|
or before.st_mtime_ns != after.st_mtime_ns):
|
|
continue
|
|
return {'kind': kind, 'capturedAt': after.st_mtime * 1000, 'source': 'export',
|
|
'image': f'data:image/{mime};base64,' + base64.b64encode(raw).decode()}
|
|
except OSError:
|
|
continue
|
|
return None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Snapshot:
|
|
body: bytes
|
|
etag: str
|
|
|
|
|
|
class PreviewService:
|
|
def __init__(self, *, root=None, capture=None):
|
|
self.root, self.capture = root, capture or capture_canvas
|
|
self.cache, self.pending, self.capture_after = OrderedDict(), {}, OrderedDict()
|
|
self.capturing = False
|
|
|
|
async def snapshot(self, task, kind='auto'):
|
|
key = (task['id'], kind)
|
|
entry = self.cache.get(key)
|
|
if entry and time.monotonic() - entry[0] < 5:
|
|
return entry[1]
|
|
if key not in self.pending:
|
|
self.pending[key] = asyncio.create_task(self._refresh(task, kind, key))
|
|
# A disconnected browser must not cancel another visitor's shared poll.
|
|
return await asyncio.shield(self.pending[key])
|
|
|
|
async def _refresh(self, task, kind, key):
|
|
try:
|
|
value = await self._preview(task, kind)
|
|
body = json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode()
|
|
result = Snapshot(body, '"' + hashlib.sha256(body).hexdigest() + '"')
|
|
self.cache[key] = (time.monotonic(), result)
|
|
self.cache.move_to_end(key)
|
|
while len(self.cache) > 12:
|
|
self.cache.popitem(last=False)
|
|
return result
|
|
finally:
|
|
self.pending.pop(key, None)
|
|
|
|
async def _preview(self, task, kind):
|
|
tid = task['id']
|
|
root = Path(self.root or storage.ROOT).resolve()
|
|
saved = root / 'web-previews' / (tid + '.json')
|
|
frame, reason = None, 'waiting_for_canvas'
|
|
if (task.get('approval') and task.get('eda_session') and task.get('state') == 'running'
|
|
and not self.capturing and time.monotonic() >= self.capture_after.get(tid, 0)):
|
|
self.capturing = True
|
|
self.capture_after[tid] = time.monotonic() + 5
|
|
self.capture_after.move_to_end(tid)
|
|
while len(self.capture_after) > 100:
|
|
self.capture_after.popitem(last=False)
|
|
try:
|
|
value = await self.capture(task)
|
|
reason = value.get('reason') or 'waiting_for_canvas'
|
|
if value.get('available'):
|
|
frame = valid_frame({'kind': value.get('kind'), 'image': value.get('image'),
|
|
'capturedAt': time.time() * 1000, 'source': 'canvas'})
|
|
if frame:
|
|
reason = ''
|
|
try:
|
|
await asyncio.to_thread(storage.write, saved, frame)
|
|
except OSError:
|
|
pass # A cache write failure must not discard a live image.
|
|
except Exception:
|
|
reason = 'canvas_unavailable'
|
|
self.capture_after[tid] = time.monotonic() + 30
|
|
finally:
|
|
self.capturing = False
|
|
elif self.capturing:
|
|
reason = 'eda_busy'
|
|
|
|
def fallback():
|
|
cached = frame
|
|
if not cached:
|
|
try:
|
|
if not saved.is_symlink() and saved.stat().st_size <= MAX_IMAGE_BYTES * 2:
|
|
cached = valid_frame(json.loads(saved.read_text()))
|
|
except (OSError, ValueError):
|
|
pass
|
|
if cached and kind not in {'auto', cached['kind']}:
|
|
cached = None
|
|
try:
|
|
exported = exported_frame(root / 'tasks' / tid / 'workspace' / 'artifacts', kind)
|
|
except OSError:
|
|
exported = None
|
|
if exported and (not cached or exported['capturedAt'] > cached['capturedAt']):
|
|
cached = exported
|
|
return cached
|
|
|
|
frame = await asyncio.to_thread(fallback)
|
|
return {'taskId': tid, 'frame': frame, 'reason': reason, 'refreshSeconds': 5}
|
|
|
|
async def close(self):
|
|
jobs = list(self.pending.values())
|
|
for job in jobs:
|
|
job.cancel()
|
|
await asyncio.gather(*jobs, return_exceptions=True)
|
|
self.pending.clear()
|
|
self.cache.clear()
|
|
self.capture_after.clear()
|
|
|
|
|
|
previews = PreviewService()
|