Fix CAD Factory dashboard on Windows
This commit is contained in:
1 parent
a6e63ae91d
commit
449418d00f
2 files changed
+71
-11
No files matched your search
+59
-9
@@ -4,11 +4,13 @@ import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from hashlib import sha256
|
||||
from http.client import HTTPConnection, HTTPException
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer as HTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -47,23 +49,37 @@ def parse_card(path, text, updated):
|
||||
return card
|
||||
|
||||
|
||||
def is_link_or_reparse(info):
|
||||
return stat.S_ISLNK(info.st_mode) or bool(
|
||||
getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT
|
||||
)
|
||||
|
||||
|
||||
def read_cards(root):
|
||||
folder = root / "changes"
|
||||
if folder.is_symlink():
|
||||
raise OSError("changes must not be a symlink")
|
||||
cards, skipped = [], 0
|
||||
if not folder.exists():
|
||||
try:
|
||||
folder_info = folder.lstat()
|
||||
except FileNotFoundError:
|
||||
return {"cards": cards, "skipped": skipped}
|
||||
if is_link_or_reparse(folder_info) or not stat.S_ISDIR(folder_info.st_mode):
|
||||
raise OSError("changes must be a regular directory")
|
||||
for path in sorted(folder.iterdir()):
|
||||
if path.suffix != ".md" or path.name.startswith("."):
|
||||
continue
|
||||
try:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
before = path.lstat()
|
||||
if is_link_or_reparse(before) or not stat.S_ISREG(before.st_mode):
|
||||
raise OSError("not a regular card")
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||
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())
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_CARD_BYTES:
|
||||
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:
|
||||
@@ -79,9 +95,23 @@ class OpenCodeUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def opencode_executable():
|
||||
if os.name != "nt":
|
||||
return "opencode"
|
||||
native = shutil.which("opencode.exe")
|
||||
if native:
|
||||
return native
|
||||
shim = shutil.which("opencode.cmd")
|
||||
if shim:
|
||||
npm_exe = Path(shim).parent / "node_modules" / "@opencode" / "cli" / "bin" / "opencode.exe"
|
||||
if npm_exe.is_file():
|
||||
return str(npm_exe)
|
||||
raise OpenCodeUnavailable
|
||||
|
||||
|
||||
def opencode_get(root, path):
|
||||
try:
|
||||
result = subprocess.run(["opencode", "api", "get", path], cwd=root,
|
||||
result = subprocess.run([opencode_executable(), "api", "get", path], cwd=root,
|
||||
capture_output=True, check=True, timeout=4)
|
||||
return json.loads(result.stdout)["data"]
|
||||
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError) as exc:
|
||||
@@ -154,7 +184,8 @@ ASSETS = {
|
||||
|
||||
|
||||
def project_identity(root):
|
||||
return {"service": "cad-factory-dashboard", "project": sha256(os.fsencode(root)).hexdigest()}
|
||||
return {"service": "cad-factory-dashboard", "protocol": 2,
|
||||
"project": sha256(os.fsencode(root)).hexdigest()}
|
||||
|
||||
|
||||
def dashboard_state(root, port):
|
||||
@@ -167,6 +198,17 @@ def dashboard_state(root, port):
|
||||
return "matching"
|
||||
except ConnectionRefusedError:
|
||||
return "free"
|
||||
except TimeoutError:
|
||||
# Windows can time out rather than refuse an unused loopback port.
|
||||
if os.name == "nt":
|
||||
with socket.socket() as probe:
|
||||
probe.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
||||
try:
|
||||
probe.bind(("127.0.0.1", port))
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
return "free"
|
||||
except (OSError, HTTPException, ValueError):
|
||||
pass
|
||||
finally:
|
||||
@@ -174,6 +216,14 @@ def dashboard_state(root, port):
|
||||
return "occupied"
|
||||
|
||||
|
||||
class ThreadingHTTPServer(HTTPServer):
|
||||
def server_bind(self):
|
||||
if os.name == "nt":
|
||||
self.allow_reuse_address = False
|
||||
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
|
||||
super().server_bind()
|
||||
|
||||
|
||||
def launch_dashboard(root, port, cards_only):
|
||||
command = [sys.executable, "-I", str(HERE / "serve.py"), "--root", str(root), "--port", str(port)]
|
||||
if cards_only:
|
||||
|
||||
+12
-2
@@ -24,8 +24,13 @@ class DashboardTest(unittest.TestCase):
|
||||
self.changes.mkdir()
|
||||
body = "# CF-001 — Посадочное место\n- **Текущее состояние:** `проверка`\n"
|
||||
card = self.changes / "CF-001.md"
|
||||
card.write_text(body, encoding="utf-8")
|
||||
(self.changes / "foreign.md").symlink_to(card)
|
||||
card.write_bytes(body.encode("utf-8"))
|
||||
try:
|
||||
(self.changes / "foreign.md").symlink_to(card)
|
||||
except OSError as exc:
|
||||
if getattr(exc, "winerror", None) != 1314:
|
||||
raise
|
||||
(self.changes / "foreign.md").mkdir()
|
||||
(self.changes / "bad.md").write_bytes(b"\xff")
|
||||
(self.changes / "large.md").write_bytes(b" " * (256 * 1024 + 1))
|
||||
result = read_cards(self.root)
|
||||
@@ -98,6 +103,8 @@ class DashboardTest(unittest.TestCase):
|
||||
self.assertEqual(json.load(response), {"state": "disabled", "agents": []})
|
||||
|
||||
def test_http_routes_do_not_serve_files_or_accept_foreign_hosts(self):
|
||||
self.changes.mkdir()
|
||||
(self.changes / "CF-001.md").write_text("# CF-001\n", encoding="utf-8")
|
||||
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
server.root = self.root
|
||||
server.activity = False
|
||||
@@ -106,6 +113,9 @@ class DashboardTest(unittest.TestCase):
|
||||
self.addCleanup(thread.join)
|
||||
self.addCleanup(server.shutdown)
|
||||
url = f"http://127.0.0.1:{server.server_port}"
|
||||
with urlopen(url + "/api/cards", timeout=2) as response:
|
||||
card, = json.load(response)["cards"]
|
||||
self.assertEqual(card["id"], "CF-001")
|
||||
with urlopen(url + "/api/activity", timeout=2) as response:
|
||||
self.assertEqual(json.load(response), {"state": "disabled", "agents": []})
|
||||
for request, expected in [
|
||||
|
||||
Reference in new issue
Block a user