Add CAD fit checks and revision previews

This commit is contained in:
gagushin committed 2026-11-29 08:23:24 +04:00
1 parent b4ef20db39
commit 78d33d01a6
18 files changed
+250 -23

No files matched your search

+68 -19
View File
@@ -22,6 +22,12 @@ HERE = Path(__file__).resolve().parent
DEFAULT_PORT = 8765
PORT_ATTEMPTS = 8
MAX_CARD_BYTES = 256 * 1024
MAX_PREVIEW_BYTES = 8 * 1024 * 1024
PREVIEW_NAME = re.compile(
r"(?P<card>[A-Za-z0-9][A-Za-z0-9_-]{0,79})\."
r"(?P<revision>[A-Za-z0-9][A-Za-z0-9_-]{0,79})-(?:overview|detail)\.png"
)
PREVIEW_LINE = re.compile(r"^!\[([^\]\r\n]+)\]\(([^()\s]+)\)$")
AGENTS = {"cad-factory", "cad-analysis", "cad-modeling", "cad-verification"}
SESSION_ID = re.compile(r"ses[A-Za-z0-9_-]+")
FIELDS = {
@@ -46,6 +52,17 @@ def parse_card(path, text, updated):
if match[1].lstrip().startswith("**") and not match[1].rstrip().endswith("**"):
value = value.removeprefix("**").lstrip()
card[key] = value.strip("`*").strip()
previews = {}
for line in text.splitlines():
image = PREVIEW_LINE.fullmatch(line.strip())
if image is None:
continue
name = PREVIEW_NAME.fullmatch(image[2])
if name and name["card"] == path.stem:
previews[image[2]] = {"file": image[2], "caption": image[1],
"revision": name["revision"]}
if previews:
card["previews"] = list(previews.values())
return card
@@ -55,6 +72,30 @@ def is_link_or_reparse(info):
)
def read_regular_file(path, limit):
parent = path.parent.lstat()
if is_link_or_reparse(parent) or not stat.S_ISDIR(parent.st_mode):
raise OSError("not a regular directory")
before = path.lstat()
if is_link_or_reparse(before) or not stat.S_ISREG(before.st_mode):
raise OSError("not a regular file")
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
with os.fdopen(os.open(path, flags), "rb") as file:
info = os.fstat(file.fileno())
current = path.lstat()
current_parent = path.parent.lstat()
if (is_link_or_reparse(current_parent) or not os.path.samestat(parent, current_parent)
or is_link_or_reparse(current) or not os.path.samestat(before, current)
or not os.path.samestat(current, info) or not stat.S_ISREG(info.st_mode)
or info.st_size > limit):
raise OSError("not a readable file")
data = file.read(limit + 1)
if len(data) > limit:
raise OSError("file grew past the limit")
return data, info.st_mtime
def read_cards(root):
folder = root / "changes"
cards, skipped = [], 0
@@ -68,27 +109,28 @@ def read_cards(root):
if path.suffix != ".md" or path.name.startswith("."):
continue
try:
before = path.lstat()
if is_link_or_reparse(before) or not stat.S_ISREG(before.st_mode):
raise OSError("not a regular card")
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
fd = os.open(path, flags)
with os.fdopen(fd, "rb") as file:
info = os.fstat(file.fileno())
current = path.lstat()
if (is_link_or_reparse(current) or not os.path.samestat(before, current)
or not os.path.samestat(current, info) or not stat.S_ISREG(info.st_mode)
or info.st_size > MAX_CARD_BYTES):
raise OSError("not a readable card")
data = file.read(MAX_CARD_BYTES + 1)
if len(data) > MAX_CARD_BYTES:
raise OSError("card grew past the limit")
cards.append(parse_card(path, data.decode("utf-8-sig"), info.st_mtime))
data, updated = read_regular_file(path, MAX_CARD_BYTES)
cards.append(parse_card(path, data.decode("utf-8-sig"), updated))
except (OSError, UnicodeError):
skipped += 1
return {"cards": sorted(cards, key=lambda card: (-card["updated"], card["id"])),
"skipped": skipped}
"skipped": skipped}
def read_preview(root, filename):
name = PREVIEW_NAME.fullmatch(filename)
if not name:
raise OSError("invalid preview name")
folder = root / "changes"
card_path = folder / f"{name['card']}.md"
data, updated = read_regular_file(card_path, MAX_CARD_BYTES)
card = parse_card(card_path, data.decode("utf-8-sig"), updated)
if not any(preview["file"] == filename for preview in card.get("previews", [])):
raise OSError("preview is not listed on the card")
data, _ = read_regular_file(folder / filename, MAX_PREVIEW_BYTES)
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
raise OSError("not a PNG preview")
return data
class OpenCodeUnavailable(Exception):
@@ -200,7 +242,7 @@ def install_dashboard(root):
def project_identity(root):
return {"service": "cad-factory-dashboard", "protocol": 2,
return {"service": "cad-factory-dashboard", "protocol": 3,
"project": sha256(os.fsencode(root)).hexdigest()}
@@ -313,6 +355,13 @@ class Handler(BaseHTTPRequestHandler):
self.json_reply(200, read_cards(self.server.root))
except OSError:
self.json_reply(503, {"error": "cannot read changes"})
elif self.path.startswith("/api/previews/"):
try:
data = read_preview(self.server.root, self.path.removeprefix("/api/previews/"))
except (OSError, UnicodeError):
self.json_reply(404, {"error": "preview not found"})
else:
self.reply(200, "image/png", data)
elif self.path == "/api/activity":
if not self.server.activity:
self.json_reply(200, {"state": "disabled", "agents": []})