server.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. """Loopback-only read-only HTTP server for the local board viewer."""
  2. from __future__ import annotations
  3. import gzip
  4. import json
  5. import mimetypes
  6. import re
  7. from http import HTTPStatus
  8. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  9. from pathlib import Path
  10. from urllib.parse import unquote, urlsplit
  11. from .assets import AssetIntegrityError, AssetValidationResult, validate_generated_assets, validate_generated_bundle
  12. ROOT = Path(__file__).resolve().parents[3]
  13. WEB_FILES = {
  14. "/": "index.html",
  15. "/index.html": "index.html",
  16. "/app.css": "app.css",
  17. "/app.js": "app.js",
  18. "/board-logic.mjs": "board-logic.mjs",
  19. "/cpld-arch-data.mjs": "cpld-arch-data.mjs",
  20. "/wasm-engine.mjs": "wasm-engine.mjs",
  21. "/board-accel.wasm": "board-accel.wasm",
  22. }
  23. GENERATED_FILES = {
  24. "/generated/board-data.json": "board-data.json",
  25. "/generated/board-mask-edge.svg": "board-mask-edge.svg",
  26. "/generated/board-silkscreen.svg": "board-silkscreen.svg",
  27. "/generated/board-copper.svg": "board-copper.svg",
  28. "/generated/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  29. "/generated/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  30. "/generated/board-copper-back.svg": "board-copper-back.svg",
  31. }
  32. GENERATED_V1_1_FILES = {
  33. "/generated-v1_1/board-data.json": "board-data.json",
  34. "/generated-v1_1/board-mask-edge.svg": "board-mask-edge.svg",
  35. "/generated-v1_1/board-silkscreen.svg": "board-silkscreen.svg",
  36. "/generated-v1_1/board-copper.svg": "board-copper.svg",
  37. "/generated-v1_1/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  38. "/generated-v1_1/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  39. "/generated-v1_1/board-copper-back.svg": "board-copper-back.svg",
  40. }
  41. GENERATED_V2_0_FILES = {
  42. "/generated-v2_0/board-data.json": "board-data.json",
  43. "/generated-v2_0/board-mask-edge.svg": "board-mask-edge.svg",
  44. "/generated-v2_0/board-silkscreen.svg": "board-silkscreen.svg",
  45. "/generated-v2_0/board-copper.svg": "board-copper.svg",
  46. "/generated-v2_0/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  47. "/generated-v2_0/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  48. "/generated-v2_0/board-copper-back.svg": "board-copper-back.svg",
  49. }
  50. GENERATED_V2_0_FAN_FILES = {
  51. "/generated-v2_0_fan/board-data.json": "board-data.json",
  52. "/generated-v2_0_fan/board-mask-edge.svg": "board-mask-edge.svg",
  53. "/generated-v2_0_fan/board-silkscreen.svg": "board-silkscreen.svg",
  54. "/generated-v2_0_fan/board-copper.svg": "board-copper.svg",
  55. "/generated-v2_0_fan/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  56. "/generated-v2_0_fan/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  57. "/generated-v2_0_fan/board-copper-back.svg": "board-copper-back.svg",
  58. }
  59. SCHEMATIC_FILES = {
  60. "/schematics/FCB_FPGA+MCU0611.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
  61. "/schematics/v1.1.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
  62. "/schematics/fcb_v1_1.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
  63. "/schematics/fcb_fpga_mcu_v2_0.pdf": "reference/original/schematics/fcb_fpga+mcu_v2_0_0902.pdf",
  64. "/schematics/fcb_v2_0.pdf": "reference/original/schematics/fcb_fpga+mcu_v2_0_0902.pdf",
  65. "/schematics/6400_v2_0_electrical.pdf": "reference/original/schematics/6400高温罩电气图V2.0.pdf",
  66. "/schematics/6400高温罩电气图V2.0.pdf": "reference/original/schematics/6400高温罩电气图V2.0.pdf",
  67. "/schematics/8000_v1_2_electrical.pdf": "reference/original/schematics/8000高温罩电气图V1.2.pdf",
  68. "/schematics/8000高温罩电气图V1.2.pdf": "reference/original/schematics/8000高温罩电气图V1.2.pdf",
  69. }
  70. DOC_FILES = {
  71. "/docs/FCB_FAN_V2_0_ANALYSIS.md": "docs/evidence/FCB_FAN_V2_0_ANALYSIS.md",
  72. "/docs/6400-v2-electrical-alignment.md": "docs/evidence/6400-v2-electrical-alignment.md",
  73. }
  74. PHOTO_ASSET = re.compile(r"^board-photo\.(?:png|jpg|jpeg|webp)$")
  75. class BoardViewerServer(ThreadingHTTPServer):
  76. daemon_threads = True
  77. allow_reuse_address = True
  78. def _runtime_payload(result: AssetValidationResult) -> dict[str, object]:
  79. return {
  80. "status": result.status,
  81. "assetErrors": result.asset_errors,
  82. "staleSources": result.stale_sources,
  83. "recommendationsEnabled": result.recommendations_enabled,
  84. "adcCopyEnabled": result.adc_copy_enabled,
  85. "generatedAt": result.build_info.get("generated_at"),
  86. "counts": result.build_info.get("counts"),
  87. }
  88. def _request_path(raw_path: str) -> str | None:
  89. path = unquote(urlsplit(raw_path).path)
  90. if "\x00" in path or "\\" in path:
  91. return None
  92. parts = path.split("/")
  93. if any(part in {".", ".."} for part in parts):
  94. return None
  95. return path
  96. def create_server(
  97. web_root: Path | str,
  98. generated_dir: Path | str,
  99. *,
  100. host: str = "127.0.0.1",
  101. port: int = 8765,
  102. allow_remote: bool = False,
  103. repository_root: Path | str = ROOT,
  104. ) -> BoardViewerServer:
  105. if not allow_remote and host != "127.0.0.1":
  106. raise ValueError("board viewer server must bind exactly to 127.0.0.1")
  107. web = Path(web_root).resolve()
  108. generated = Path(generated_dir).resolve()
  109. repository = Path(repository_root).resolve()
  110. for filename in set(WEB_FILES.values()):
  111. if not (web / filename).is_file():
  112. raise AssetIntegrityError(f"missing web asset: {filename}")
  113. validate_generated_bundle(generated, repository_root=repository)
  114. generated_files = dict(GENERATED_FILES)
  115. board_data = json.loads((generated / "board-data.json").read_text(encoding="utf-8"))
  116. photo_overlay = board_data.get("photo_overlay")
  117. if isinstance(photo_overlay, dict):
  118. photo_asset = str(photo_overlay.get("asset") or "")
  119. if not PHOTO_ASSET.fullmatch(photo_asset):
  120. raise AssetIntegrityError(f"unsafe photo asset name: {photo_asset}")
  121. generated_files[f"/generated/{photo_asset}"] = photo_asset
  122. v1_1_dir = generated.parent / "generated-v1_1"
  123. if not v1_1_dir.is_dir():
  124. v1_1_dir = repository / "tools" / "board-viewer" / "generated-v1_1"
  125. v1_1_files: dict[str, Path] = {}
  126. if v1_1_dir.is_dir():
  127. for url_path, rel_name in GENERATED_V1_1_FILES.items():
  128. candidate = v1_1_dir / rel_name
  129. if candidate.is_file():
  130. v1_1_files[url_path] = candidate
  131. v2_0_dir = generated.parent / "generated-v2_0"
  132. if not v2_0_dir.is_dir():
  133. v2_0_dir = repository / "tools" / "board-viewer" / "generated-v2_0"
  134. v2_0_files: dict[str, Path] = {}
  135. if v2_0_dir.is_dir():
  136. for url_path, rel_name in GENERATED_V2_0_FILES.items():
  137. candidate = v2_0_dir / rel_name
  138. if candidate.is_file():
  139. v2_0_files[url_path] = candidate
  140. v2_0_fan_dir = generated.parent / "generated-v2_0_fan"
  141. if not v2_0_fan_dir.is_dir():
  142. v2_0_fan_dir = repository / "tools" / "board-viewer" / "generated-v2_0_fan"
  143. v2_0_fan_files: dict[str, Path] = {}
  144. if v2_0_fan_dir.is_dir():
  145. for url_path, rel_name in GENERATED_V2_0_FAN_FILES.items():
  146. candidate = v2_0_fan_dir / rel_name
  147. if candidate.is_file():
  148. v2_0_fan_files[url_path] = candidate
  149. schematic_map: dict[str, Path] = {}
  150. for url_path, rel_path in SCHEMATIC_FILES.items():
  151. candidate = repository / rel_path
  152. if candidate.is_file():
  153. schematic_map[url_path] = candidate
  154. doc_map: dict[str, Path] = {}
  155. for url_path, rel_path in DOC_FILES.items():
  156. candidate = repository / rel_path
  157. if candidate.is_file():
  158. doc_map[url_path] = candidate
  159. asset_cache: dict[Path, tuple[int, int, bytes, bytes | None]] = {}
  160. status_cache: dict[str, tuple[int, bytes, int]] = {}
  161. COMPRESSIBLE_SUFFIXES = {".html", ".css", ".js", ".mjs", ".json", ".svg", ".md", ".wasm"}
  162. class Handler(BaseHTTPRequestHandler):
  163. server_version = "BoardViewer/1.0"
  164. sys_version = ""
  165. def log_message(self, format: str, *args: object) -> None:
  166. print(f"[{self.client_address[0]}] {self.command} {self.path}", flush=True)
  167. def _security_headers(self) -> None:
  168. self.send_header("X-Content-Type-Options", "nosniff")
  169. self.send_header("Referrer-Policy", "no-referrer")
  170. self.send_header("Cross-Origin-Resource-Policy", "same-origin")
  171. self.send_header(
  172. "Content-Security-Policy",
  173. "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; "
  174. "connect-src 'self'; object-src 'self'; base-uri 'none'; frame-ancestors 'self'; form-action 'none'",
  175. )
  176. self.send_header("Cache-Control", "no-store")
  177. def _accepts_gzip(self) -> bool:
  178. accept_enc = self.headers.get("Accept-Encoding") or ""
  179. return "gzip" in accept_enc.lower()
  180. def _send_bytes(
  181. self,
  182. payload: bytes,
  183. content_type: str,
  184. *,
  185. status: int = 200,
  186. head: bool = False,
  187. gzipped_payload: bytes | None = None,
  188. ) -> None:
  189. use_gzip = gzipped_payload is not None and self._accepts_gzip()
  190. out_bytes = gzipped_payload if use_gzip else payload
  191. self.send_response(status)
  192. self._security_headers()
  193. self.send_header("Content-Type", content_type)
  194. if gzipped_payload is not None:
  195. self.send_header("Vary", "Accept-Encoding")
  196. if use_gzip:
  197. self.send_header("Content-Encoding", "gzip")
  198. self.send_header("Content-Length", str(len(out_bytes)))
  199. self.end_headers()
  200. if not head:
  201. self.wfile.write(out_bytes)
  202. def _send_not_found(self, *, head: bool = False) -> None:
  203. self._send_bytes(b"Not Found\n", "text/plain; charset=utf-8", status=HTTPStatus.NOT_FOUND, head=head)
  204. def _serve(self, *, head: bool = False) -> None:
  205. url_parts = urlsplit(self.path)
  206. path = _request_path(url_parts.path)
  207. if path is None:
  208. self._send_not_found(head=head)
  209. return
  210. if path == "/api/status":
  211. query_str = url_parts.query or ""
  212. target_bundle = generated
  213. ver = "v1_2"
  214. if "version=v2_0_fan" in query_str and v2_0_fan_dir.is_dir():
  215. target_bundle = v2_0_fan_dir
  216. ver = "v2_0_fan"
  217. elif "version=v2_0" in query_str and v2_0_dir.is_dir():
  218. target_bundle = v2_0_dir
  219. ver = "v2_0"
  220. elif "version=v1_1" in query_str and v1_1_dir.is_dir():
  221. target_bundle = v1_1_dir
  222. ver = "v1_1"
  223. try:
  224. result = validate_generated_assets(target_bundle, repository_root=repository)
  225. payload = _runtime_payload(result)
  226. payload["version"] = ver
  227. payload["accelEngine"] = "rust-wasm-v1"
  228. status = HTTPStatus.OK
  229. except AssetIntegrityError as exc:
  230. payload = {
  231. "status": "invalid_assets",
  232. "assetErrors": [str(exc)],
  233. "staleSources": [],
  234. "recommendationsEnabled": False,
  235. "adcCopyEnabled": False,
  236. "message": str(exc),
  237. "version": ver,
  238. }
  239. status = HTTPStatus.SERVICE_UNAVAILABLE
  240. body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
  241. self._send_bytes(body, "application/json; charset=utf-8", status=status, head=head)
  242. return
  243. if path in WEB_FILES:
  244. file_path = web / WEB_FILES[path]
  245. elif path in generated_files:
  246. file_path = generated / generated_files[path]
  247. elif path in v2_0_files:
  248. file_path = v2_0_files[path]
  249. elif path in v2_0_fan_files:
  250. file_path = v2_0_fan_files[path]
  251. elif path in v1_1_files:
  252. file_path = v1_1_files[path]
  253. elif path in schematic_map:
  254. file_path = schematic_map[path]
  255. elif path in doc_map:
  256. file_path = doc_map[path]
  257. else:
  258. self._send_not_found(head=head)
  259. return
  260. try:
  261. st = file_path.stat()
  262. cached = asset_cache.get(file_path)
  263. if cached is not None and cached[0] == st.st_mtime_ns and cached[1] == st.st_size:
  264. body, gz_body = cached[2], cached[3]
  265. else:
  266. body = file_path.read_bytes()
  267. gz_body = (
  268. gzip.compress(body, compresslevel=6)
  269. if file_path.suffix in COMPRESSIBLE_SUFFIXES and len(body) > 512
  270. else None
  271. )
  272. asset_cache[file_path] = (st.st_mtime_ns, st.st_size, body, gz_body)
  273. except OSError:
  274. self._send_not_found(head=head)
  275. return
  276. content_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
  277. if file_path.suffix == ".pdf":
  278. content_type = "application/pdf"
  279. elif file_path.suffix == ".wasm":
  280. content_type = "application/wasm"
  281. elif file_path.suffix in {".js", ".mjs"}:
  282. content_type = "text/javascript"
  283. elif file_path.suffix == ".md":
  284. content_type = "text/markdown"
  285. if file_path.suffix in {".html", ".css", ".js", ".mjs", ".json", ".svg", ".md"}:
  286. content_type += "; charset=utf-8"
  287. self._send_bytes(body, content_type, head=head, gzipped_payload=gz_body)
  288. def do_GET(self) -> None: # noqa: N802
  289. self._serve(head=False)
  290. def do_HEAD(self) -> None: # noqa: N802
  291. self._serve(head=True)
  292. def _reject_mutation(self) -> None:
  293. payload = b"Method Not Allowed\n"
  294. self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
  295. self._security_headers()
  296. self.send_header("Allow", "GET, HEAD")
  297. self.send_header("Content-Type", "text/plain; charset=utf-8")
  298. self.send_header("Content-Length", str(len(payload)))
  299. self.end_headers()
  300. self.wfile.write(payload)
  301. do_POST = _reject_mutation # noqa: N815
  302. do_PUT = _reject_mutation # noqa: N815
  303. do_PATCH = _reject_mutation # noqa: N815
  304. do_DELETE = _reject_mutation # noqa: N815
  305. return BoardViewerServer((host, port), Handler)