Repository Public
1"""Tiny local test server for the browser engine tests (127.0.0.1 only, every request is logged).23Static pages live next to this file and are served under /p/<name>. A few endpoints are generated:4tall and wide documents with coloured markers at known offsets, solid-colour images, JSON feeds,5redirects, HTTP statuses, a response that never ends, and /api/side-effect/* endpoints that must never6be reached by the engine (the log proves it).7"""8from __future__ import annotations910import asyncio11import io12import json13from pathlib import Path14from typing import Any1516from aiohttp import web17from PIL import Image1819ROOT = Path(__file__).parent20HEADER_RGB = (200, 0, 0)21FOOTER_RGB = (0, 120, 0)22STICKY_RGB = (250, 200, 0)232425def band_rgb(i: int) -> tuple[int, int, int]:26 return (0, 10 * i + 5, 200)272829def tall_html(height: int, fixed: bool = True) -> str:30 bands = "".join(31 f'<div class="band" style="top:{1000 * i + 300}px;background:rgb{band_rgb(i)}">MARK-{i}</div>'32 for i in range(height // 1000))33 layers = ""34 if fixed:35 layers = '<div id="fixed-header">FIXED-HEADER</div><div id="fixed-footer">FIXED-FOOTER</div>'36 if height >= 8000:37 layers += '<div id="sticky-box"><div id="sticky">STICKY</div></div>'38 return f"""<!doctype html><html><head><meta charset="utf-8"><title>Tall {height}</title>39<meta name="viewport" content="width=device-width, initial-scale=1">40<style>41html,body{{margin:0;padding:0;background:#fff;font:14px/1 sans-serif}}42#doc{{position:relative;height:{height}px}}43.band{{position:absolute;left:0;width:100%;height:100px;color:#fff}}44#fixed-header{{position:fixed;top:0;left:0;right:0;height:60px;background:rgb{HEADER_RGB};color:#fff;z-index:5}}45#fixed-footer{{position:fixed;bottom:0;left:0;right:0;height:40px;background:rgb{FOOTER_RGB};color:#fff;z-index:5}}46#sticky-box{{position:absolute;top:5000px;left:0;width:300px;height:3000px}}47#sticky{{position:sticky;top:60px;height:30px;background:rgb{STICKY_RGB}}}48</style></head><body><div id="doc">{bands}{layers}</div></body></html>"""495051def wide_html(width: int, height: int) -> str:52 marks = "".join(53 f'<div class="m" style="left:{500 * i + 100}px;background:rgb{band_rgb(i)}">W{i}</div>'54 for i in range(width // 500))55 return f"""<!doctype html><html><head><meta charset="utf-8"><title>Wide {width}</title>56<style>html,body{{margin:0;background:#fff}}#doc{{position:relative;width:{width}px;height:{height}px}}57.m{{position:absolute;top:200px;width:100px;height:100px;color:#fff}}</style></head>58<body><div id="doc">{marks}</div></body></html>"""596061class PageServer:62 def __init__(self) -> None:63 self.log: list[dict[str, Any]] = []64 self.port = 065 self._runner: web.AppRunner | None = None66 self._hang = asyncio.Event()6768 # ------------------------------------------------------------------------------------ helpers69 def url(self, path: str, host: str = "127.0.0.1") -> str:70 return f"http://{host}:{self.port}{path}"7172 def hits(self, prefix: str = "", method: str | None = None) -> list[dict[str, Any]]:73 return [r for r in self.log if r["path"].startswith(prefix) and (method is None or r["method"] == method)]7475 def non_get(self) -> list[dict[str, Any]]:76 return [r for r in self.log if r["method"] not in ("GET", "HEAD")]7778 def clear(self) -> None:79 self.log.clear()8081 # ----------------------------------------------------------------------------------- lifecycle82 async def start(self) -> PageServer:83 @web.middleware84 async def log_mw(request: web.Request, handler: Any) -> web.StreamResponse:85 self.log.append({"method": request.method, "path": request.path, "query": request.query_string,86 "host": request.headers.get("Host", ""), "ua": request.headers.get("User-Agent", "")})87 return await handler(request)8889 app = web.Application(middlewares=[log_mw])90 r = app.router91 r.add_get("/p/{name}", self._page)92 r.add_get("/gen/tall", self._tall)93 r.add_get("/gen/wide", self._wide)94 r.add_get("/gen/probe", self._probe)95 r.add_get("/img/{name}", self._img)96 r.add_get("/api/items", self._items)97 r.add_get("/api/hydrate", self._hydrate)98 r.add_get("/status/{code}", self._status)99 r.add_get("/redirect", self._redirect)100 r.add_get("/private/account", self._private)101 r.add_get("/login", self._login)102 r.add_get("/hang", self._hang_forever)103 r.add_get("/download", self._download)104 r.add_get("/ws", self._ws)105 r.add_get("/fake/{tail:.*}", self._fake)106 r.add_route("*", "/api/side-effect/{name}", self._side_effect)107 r.add_route("*", "/{tail:.*}", self._fallback)108 self._runner = web.AppRunner(app, handle_signals=False, access_log=None, shutdown_timeout=0.2)109 await self._runner.setup()110 site = web.TCPSite(self._runner, "127.0.0.1", 0)111 await site.start()112 self.port = site._server.sockets[0].getsockname()[1]113 return self114115 async def stop(self) -> None:116 self._hang.set()117 if self._runner is not None:118 await self._runner.cleanup()119120 # ------------------------------------------------------------------------------------ handlers121 async def _page(self, request: web.Request) -> web.StreamResponse:122 name = request.match_info["name"]123 path = (ROOT / name).resolve()124 if path.parent != ROOT or not path.is_file() or path.suffix not in (".html", ".js", ".css"):125 return web.Response(status=404, text="<h1>Not found</h1><p>No such page.</p>", content_type="text/html")126 ctype = {".html": "text/html", ".js": "application/javascript", ".css": "text/css"}[path.suffix]127 return web.Response(text=path.read_text(encoding="utf-8"), content_type=ctype, charset="utf-8")128129 async def _tall(self, request: web.Request) -> web.StreamResponse:130 html = tall_html(int(request.query.get("h", "20000")), request.query.get("fixed", "1") == "1")131 return web.Response(text=html, content_type="text/html")132133 async def _probe(self, request: web.Request) -> web.StreamResponse:134 """A page that tries to reach another loopback service by image, iframe and script-less fetch."""135 port = int(request.query.get("port", "9"))136 base = f"http://127.0.0.1:{port}"137 html = (f"<!doctype html><title>probe</title><h1>PROBE-PAGE</h1><img src='{base}/img.png' alt=''>"138 f"<iframe src='{base}/frame'></iframe><link rel='stylesheet' href='http://localhost:{port}/a.css'>"139 f"<script src='/static-probe.js'></script><p id='out'></p>"140 f"<script src='data:text/javascript,void 0'></script>")141 return web.Response(text=html, content_type="text/html")142143 async def _wide(self, request: web.Request) -> web.StreamResponse:144 html = wide_html(int(request.query.get("w", "3000")), int(request.query.get("h", "1200")))145 return web.Response(text=html, content_type="text/html")146147 async def _img(self, request: web.Request) -> web.StreamResponse:148 stem = request.match_info["name"].rsplit(".", 1)[0]149 rgb = tuple(int(x) for x in stem.split("-")[:3])150 w, h = int(request.query.get("w", "200")), int(request.query.get("h", "120"))151 buf = io.BytesIO()152 Image.new("RGB", (w, h), rgb).save(buf, "PNG")153 return web.Response(body=buf.getvalue(), content_type="image/png")154155 async def _items(self, request: web.Request) -> web.StreamResponse:156 page = int(request.query.get("page", "1"))157 return web.json_response({"page": page, "items": [f"ITEM-{page}-{i}" for i in range(10)]})158159 async def _hydrate(self, request: web.Request) -> web.StreamResponse:160 await asyncio.sleep(0.25)161 return web.json_response({"title": "HYDRATED-TITLE", "rows": ["ROW-A", "ROW-B", "ROW-C"]})162163 async def _status(self, request: web.Request) -> web.StreamResponse:164 code = int(request.match_info["code"])165 body = f"<html><head><title>Status {code}</title></head><body><h1>Status {code}</h1><p>{'x' * 50}</p></body></html>"166 return web.Response(status=code, text=body, content_type="text/html")167168 async def _redirect(self, request: web.Request) -> web.StreamResponse:169 return web.Response(status=int(request.query.get("code", "302")), headers={"Location": request.query["to"]})170171 async def _private(self, request: web.Request) -> web.StreamResponse:172 return web.Response(status=302, headers={"Location": "/login?next=/private/account"})173174 async def _login(self, request: web.Request) -> web.StreamResponse:175 return web.Response(text=(ROOT / "login.html").read_text(encoding="utf-8"), content_type="text/html")176177 async def _hang_forever(self, request: web.Request) -> web.StreamResponse:178 resp = web.StreamResponse(status=200, headers={"Content-Type": "text/html"})179 await resp.prepare(request)180 await resp.write(b"<!doctype html><html><head><title>Hang</title>")181 try:182 await asyncio.wait_for(self._hang.wait(), 120)183 except TimeoutError:184 pass185 return resp186187 async def _download(self, request: web.Request) -> web.StreamResponse:188 return web.Response(body=b"PK\x03\x04 not really a zip", content_type="application/zip",189 headers={"Content-Disposition": 'attachment; filename="file.zip"'})190191 async def _ws(self, request: web.Request) -> web.StreamResponse:192 ws = web.WebSocketResponse()193 await ws.prepare(request)194 await ws.send_str("HELLO")195 await ws.close()196 return ws197198 async def _fake(self, request: web.Request) -> web.StreamResponse:199 tail = request.match_info["tail"]200 if tail.endswith(".js"):201 return web.Response(text="/* fake third-party script */", content_type="application/javascript")202 return web.Response(text="<html><body style='margin:0;background:#eef'>challenge widget</body></html>",203 content_type="text/html")204205 async def _side_effect(self, request: web.Request) -> web.StreamResponse:206 return web.Response(text=json.dumps({"done": request.match_info["name"]}), content_type="application/json")207208 async def _fallback(self, request: web.Request) -> web.StreamResponse:209 if request.path == "/favicon.ico":210 return web.Response(status=204)211 if request.path.startswith("/p/spa"):212 return web.Response(text=(ROOT / "spa.html").read_text(encoding="utf-8"), content_type="text/html")213 return web.Response(status=404, text="<h1>Not found</h1>", content_type="text/html")214