Repository Public
1"""Controlled local website used by SPIDER's acceptance tests.23Usage from a test::45 fixture = await start_fixture() # 127.0.0.1, ephemeral port6 ...crawl fixture.base_url...7 assert fixture.state.hits("/private/secret") == 08 await fixture.close()910or, from synchronous code (Playwright sync API, subprocess-driven tests)::1112 with FixtureThread() as fixture:13 ...1415By hand: ``python tests/fixtures/site/server.py --port 8765``.1617Everything served here is simulated and deterministic; the server never opens18an outbound connection.19"""2021from __future__ import annotations2223import argparse24import asyncio25import gzip26import socket27import sys28import threading29import time30from dataclasses import asdict, dataclass, field31from email.utils import parsedate_to_datetime32from pathlib import Path33from typing import Self34from xml.sax.saxutils import escape as xml_escape3536from aiohttp import web3738_HERE = Path(__file__).resolve().parent39if str(_HERE) not in sys.path:40 sys.path.insert(0, str(_HERE))4142import spider_fixture_assets as assets43import spider_fixture_content as content4445__all__ = [46 "FixtureState",47 "FixtureThread",48 "RequestRecord",49 "RunningFixture",50 "SideEffect",51 "create_app",52 "start_fixture",53]5455STATIC_DIR = _HERE / "static"56MANIFEST_PATH = _HERE / "manifest.json"57CONTROL_PREFIX = "/__fixture/"58CONTROL_HEADER = "X-Fixture-Control"59RECORDED_HEADERS = (60 "User-Agent",61 "If-None-Match",62 "If-Modified-Since",63 "Accept",64 "Accept-Encoding",65 "Accept-Language",66 "Referer",67 "Range",68 "Host",69)70SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}71BIG_MAX_BYTES = 50 * 1024 * 102472STATIC_TYPES = {".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8"}73NO_STORE = {"Cache-Control": "no-store"}747576@dataclass77class RequestRecord:78 seq: int79 method: str80 path: str81 query: dict[str, str]82 path_qs: str83 headers: dict[str, str]84 timestamp: float85 remote: str | None86 status: int | None = None878889@dataclass90class SideEffect:91 seq: int92 method: str93 path: str94 query: dict[str, str]95 content_type: str96 body: str97 timestamp: float9899100@dataclass101class FixtureState:102 """Everything the fixture remembers: request log, side effects, counters."""103104 requests: list[RequestRecord] = field(default_factory=list)105 side_effects: list[SideEffect] = field(default_factory=list)106 variant: int = 0107 rate_limit_hits: dict[str, int] = field(default_factory=dict)108 _seq: int = 0109110 def record(self, request: web.Request) -> RequestRecord:111 self._seq += 1112 record = RequestRecord(113 seq=self._seq,114 method=request.method,115 path=request.path,116 query=dict(request.query),117 path_qs=request.path_qs,118 headers={name: request.headers[name] for name in RECORDED_HEADERS if name in request.headers},119 timestamp=time.time(),120 remote=request.remote,121 )122 self.requests.append(record)123 return record124125 def hits(self, path: str) -> int:126 """Number of requests received for ``path`` (compared with the query string if it has one)."""127 attribute = "path_qs" if "?" in path else "path"128 return sum(1 for record in self.requests if getattr(record, attribute) == path)129130 def paths(self) -> set[str]:131 """Every distinct path requested so far (without query strings)."""132 return {record.path for record in self.requests}133134 def paths_with_query(self) -> set[str]:135 return {record.path_qs for record in self.requests}136137 def bump(self) -> int:138 """Switch /cond/changing to its next variant; returns the new counter."""139 self.variant += 1140 return self.variant141142 def reset(self) -> None:143 """Forget requests, side effects, the 429 counters and the /cond/changing variant."""144 self.requests.clear()145 self.side_effects.clear()146 self.rate_limit_hits.clear()147 self.variant = 0148 self._seq = 0149150 def snapshot(self) -> dict:151 return {152 "requests": [asdict(record) for record in self.requests],153 "side_effects": [asdict(effect) for effect in self.side_effects],154 "variant": self.variant,155 "variant_index": self.variant % len(content.CHANGING_VARIANTS),156 }157158159STATE_KEY: web.AppKey[FixtureState] = web.AppKey("fixture_state", FixtureState)160161162def _html(body: bytes | str, status: int = 200, **headers: str) -> web.Response:163 data = body.encode("utf-8") if isinstance(body, str) else body164 return web.Response(body=data, status=status, content_type="text/html", charset="utf-8", headers={**NO_STORE, **headers})165166167def _error(status: int, title: str, text: str, **headers: str) -> web.Response:168 return _html(content.simple_page(f"{status} {title}", text), status, **headers)169170171def _not_found() -> web.Response:172 return _error(404, "Not Found", "The fixture has no such page.")173174175def _json(payload: object, status: int = 200) -> web.Response:176 return web.json_response(payload, status=status, headers=NO_STORE)177178179# ---------------------------------------------------------------------------180# Control endpoints (disallowed in robots.txt)181# ---------------------------------------------------------------------------182183184async def _control(request: web.Request, state: FixtureState) -> web.Response:185 name = request.path[len(CONTROL_PREFIX) :]186 if name == "requests" and request.method == "GET":187 return _json(state.snapshot())188 if name == "state" and request.method == "GET":189 index = state.variant % len(content.CHANGING_VARIANTS)190 return _json(191 {192 "variant": state.variant,193 "variant_index": index,194 "variant_content": content.CHANGING_VARIANTS[index],195 "requests": len(state.requests),196 "side_effects": len(state.side_effects),197 }198 )199 if name == "manifest" and request.method == "GET":200 return web.Response(body=MANIFEST_PATH.read_bytes(), content_type="application/json", headers=NO_STORE)201 if name == "reset" and request.method == "POST":202 state.reset()203 return _json({"ok": True})204 if name == "bump" and request.method == "POST":205 counter = state.bump()206 return _json({"variant": counter, "variant_index": counter % len(content.CHANGING_VARIANTS)})207 return _json({"error": "unknown control endpoint"}, status=404)208209210async def _side_effect(request: web.Request, state: FixtureState, seq: int) -> web.Response:211 raw = await request.content.read(65536)212 state.side_effects.append(213 SideEffect(214 seq=seq,215 method=request.method,216 path=request.path,217 query=dict(request.query),218 content_type=request.content_type,219 body=raw.decode("utf-8", "replace"),220 timestamp=time.time(),221 )222 )223 return _html(224 content.simple_page(225 "Simulated side effect recorded",226 f"{request.method} {request.path} was recorded by the fixture. Nothing real happened.",227 )228 )229230231# ---------------------------------------------------------------------------232# robots.txt and sitemaps (absolute URLs depend on the request origin)233# ---------------------------------------------------------------------------234235236def _origin(request: web.Request) -> str:237 return f"{request.scheme}://{request.host}"238239240async def _robots(request: web.Request, state: FixtureState) -> web.Response:241 lines = []242 for group in content.ROBOTS_GROUPS:243 lines.append(f"User-agent: {group['user_agent']}")244 lines.extend(f"Disallow: {rule}" for rule in group["disallow"])245 lines.append(f"Crawl-delay: {group['crawl_delay']}")246 lines.append("")247 lines.append(f"Sitemap: {_origin(request)}/sitemap.xml")248 return web.Response(text="\n".join(lines) + "\n", content_type="text/plain", charset="utf-8", headers=NO_STORE)249250251def _urlset(origin: str, paths: list[str]) -> bytes:252 urls = "".join(f" <url><loc>{xml_escape(origin + path)}</loc></url>\n" for path in paths)253 return (254 '<?xml version="1.0" encoding="UTF-8"?>\n'255 f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n{urls}</urlset>\n'256 ).encode()257258259async def _sitemap_index(request: web.Request, state: FixtureState) -> web.Response:260 origin = _origin(request)261 body = (262 '<?xml version="1.0" encoding="UTF-8"?>\n'263 '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'264 f" <sitemap><loc>{origin}/sitemap-pages.xml</loc></sitemap>\n"265 f" <sitemap><loc>{origin}/sitemap-products.xml.gz</loc></sitemap>\n"266 "</sitemapindex>\n"267 )268 return web.Response(body=body.encode(), content_type="application/xml", headers=NO_STORE)269270271async def _sitemap_pages(request: web.Request, state: FixtureState) -> web.Response:272 body = _urlset(_origin(request), content.SITEMAP_PAGES)273 return web.Response(body=body, content_type="application/xml", headers=NO_STORE)274275276async def _sitemap_products(request: web.Request, state: FixtureState) -> web.Response:277 body = gzip.compress(_urlset(_origin(request), content.SITEMAP_PRODUCTS), mtime=0)278 return web.Response(body=body, content_type="application/gzip", headers=NO_STORE)279280281# ---------------------------------------------------------------------------282# Errors and hostile responses283# ---------------------------------------------------------------------------284285286def _status_handler(status: int, title: str):287 async def handler(request: web.Request, state: FixtureState) -> web.Response:288 return _error(status, title, f"Simulated HTTP {status} response.")289290 return handler291292293async def _err_429(request: web.Request, state: FixtureState) -> web.Response:294 client = request.headers.get("X-Fixture-Client") or f"{request.remote}|{request.headers.get('User-Agent', '')}"295 hits = state.rate_limit_hits.get(client, 0) + 1296 state.rate_limit_hits[client] = hits297 if hits <= 2:298 return _error(429, "Too Many Requests", f"Simulated rate limit, attempt {hits} of 2.", **{"Retry-After": "1"})299 return _html(content.simple_page("Rate limit passed", "RATE-LIMIT-PASSED-3382: the third attempt succeeds."))300301302async def _err_slow(request: web.Request, state: FixtureState) -> web.Response:303 try:304 delay_ms = min(max(int(request.query.get("ms", "1000")), 0), 30000)305 except ValueError:306 delay_ms = 1000307 await asyncio.sleep(delay_ms / 1000)308 return _html(content.simple_page("Slow page", f"SLOW-PAGE-DONE: answered after {delay_ms} ms."))309310311async def _err_big(request: web.Request, state: FixtureState) -> web.StreamResponse:312 try:313 megabytes = min(max(int(request.query.get("mb", "50")), 1), 50)314 except ValueError:315 megabytes = 50316 response = web.StreamResponse(headers={"Content-Type": "application/octet-stream", **NO_STORE})317 await response.prepare(request)318 chunk = bytes(64 * 1024)319 try:320 for _ in range(megabytes * 16):321 await response.write(chunk)322 await response.write_eof()323 except (ConnectionError, asyncio.CancelledError):324 pass # the client gave up, which is the expected behaviour of a bounded reader325 return response326327328async def _err_gzip_bomb(request: web.Request, state: FixtureState) -> web.Response:329 body = await asyncio.get_running_loop().run_in_executor(None, assets.gzip_bomb)330 return web.Response(331 body=body, headers={"Content-Type": "text/html; charset=utf-8", "Content-Encoding": "gzip", **NO_STORE}332 )333334335async def _err_bad_encoding(request: web.Request, state: FixtureState) -> web.Response:336 body = (337 '<!doctype html>\n<html lang="fr"><head><title>Encodage incorrect</title></head>'338 f"<body><p>{content.BAD_ENCODING_TEXT}</p></body></html>\n"339 ).encode("latin-1")340 return web.Response(body=body, headers={"Content-Type": "text/html; charset=utf-8", **NO_STORE})341342343async def _err_wrong_mime(request: web.Request, state: FixtureState) -> web.Response:344 body = content.simple_page("Wrong MIME type", "WRONG-MIME-HTML-9015: this HTML document is labelled image/png.")345 return web.Response(body=body, headers={"Content-Type": "image/png", **NO_STORE})346347348async def _err_truncated(request: web.Request, state: FixtureState) -> web.StreamResponse:349 partial = b"<!doctype html>\n<html><head><title>Truncated</title></head><body><p>TRUNCATED-BODY-START: the rest"350 response = web.StreamResponse(headers={"Content-Type": "text/html; charset=utf-8", "Content-Length": "4096"})351 response.force_close()352 await response.prepare(request)353 await response.write(partial)354 if request.transport is not None:355 request.transport.close()356 return response357358359# ---------------------------------------------------------------------------360# Conditional requests361# ---------------------------------------------------------------------------362363364def _etag_matches(header: str | None, etag: str) -> bool:365 if not header:366 return False367 candidates = [item.strip().removeprefix("W/") for item in header.split(",")]368 return "*" in candidates or etag in candidates369370371async def _cond_etag(request: web.Request, state: FixtureState) -> web.Response:372 headers = {"ETag": content.ETAG_VALUE, "Cache-Control": "no-cache"}373 if _etag_matches(request.headers.get("If-None-Match"), content.ETAG_VALUE):374 return web.Response(status=304, headers=headers)375 body = content.simple_page("ETag page", "COND-ETAG-4407: revalidate me with If-None-Match.")376 return web.Response(body=body, content_type="text/html", charset="utf-8", headers=headers)377378379async def _cond_lastmod(request: web.Request, state: FixtureState) -> web.Response:380 headers = {"Last-Modified": content.LAST_MODIFIED, "Cache-Control": "no-cache"}381 since = request.headers.get("If-Modified-Since")382 if since:383 try:384 if parsedate_to_datetime(since) >= parsedate_to_datetime(content.LAST_MODIFIED):385 return web.Response(status=304, headers=headers)386 except (TypeError, ValueError):387 pass388 body = content.simple_page("Last-Modified page", "COND-LASTMOD-5126: revalidate me with If-Modified-Since.")389 return web.Response(body=body, content_type="text/html", charset="utf-8", headers=headers)390391392async def _cond_changing(request: web.Request, state: FixtureState) -> web.Response:393 index = state.variant % len(content.CHANGING_VARIANTS)394 etag = f'"changing-v{index}"'395 headers = {"ETag": etag, "X-Fixture-Variant": str(index), "Cache-Control": "no-cache"}396 if _etag_matches(request.headers.get("If-None-Match"), etag):397 return web.Response(status=304, headers=headers)398 return web.Response(399 body=content.changing_page(state.variant), content_type="text/html", charset="utf-8", headers=headers400 )401402403async def _mobile_ua(request: web.Request, state: FixtureState) -> web.Response:404 agent = request.headers.get("User-Agent", "")405 mobile = any(token in agent for token in content.MOBILE_UA_TOKENS)406 return _html(content.ua_page(mobile), Vary="User-Agent")407408409async def _favicon(request: web.Request, state: FixtureState) -> web.Response:410 return web.Response(body=assets.image_bytes("favicon.png"), content_type="image/png")411412413EXACT_HANDLERS = {414 "/robots.txt": _robots,415 "/sitemap.xml": _sitemap_index,416 "/sitemap-pages.xml": _sitemap_pages,417 "/sitemap-products.xml.gz": _sitemap_products,418 "/favicon.ico": _favicon,419 "/err/403": _status_handler(403, "Forbidden"),420 "/err/404": _status_handler(404, "Not Found"),421 "/err/410": _status_handler(410, "Gone"),422 "/err/500": _status_handler(500, "Internal Server Error"),423 "/err/429": _err_429,424 "/err/slow": _err_slow,425 "/err/big": _err_big,426 "/err/gzip-bomb": _err_gzip_bomb,427 "/err/bad-encoding": _err_bad_encoding,428 "/err/wrong-mime": _err_wrong_mime,429 "/err/truncated": _err_truncated,430 "/cond/etag": _cond_etag,431 "/cond/lastmod": _cond_lastmod,432 "/cond/changing": _cond_changing,433 "/mobile/ua": _mobile_ua,434}435436437def _trap(request: web.Request) -> web.Response:438 path = request.path439 if path == "/trap/pages":440 try:441 page = max(1, int(request.query.get("page", "1")))442 except ValueError:443 return _not_found()444 return _html(content.trap_pages(page))445 if path == "/trap/facets":446 return _html(content.trap_facets(request.query))447 parts = path.split("/")448 if len(parts) == 5 and parts[2] == "calendar" and parts[3].isdigit() and parts[4].isdigit():449 year, month = int(parts[3]), int(parts[4])450 if 1 <= month <= 12 and 1 <= year <= 99999:451 return _html(content.trap_calendar(year, month))452 return _not_found()453454455def _static_file(name: str) -> web.Response:456 target = STATIC_DIR / name457 if "/" in name or target.suffix not in STATIC_TYPES or not target.is_file():458 return _not_found()459 return web.Response(body=target.read_bytes(), headers={"Content-Type": STATIC_TYPES[target.suffix], **NO_STORE})460461462async def _dispatch(request: web.Request) -> web.StreamResponse:463 state = request.app[STATE_KEY]464 path = request.path465 if path.startswith(CONTROL_PREFIX) and request.headers.get(CONTROL_HEADER) == "1":466 return await _control(request, state) # the test harness itself: not logged467468 record = state.record(request)469 response = await _respond(request, state, record)470 record.status = response.status471 return response472473474async def _respond(request: web.Request, state: FixtureState, record: RequestRecord) -> web.StreamResponse:475 path = request.path476 if path.startswith(CONTROL_PREFIX):477 return await _control(request, state)478 if request.method not in SAFE_METHODS:479 return await _side_effect(request, state, record.seq)480 handler = EXACT_HANDLERS.get(path)481 if handler is not None:482 return await handler(request, state)483 redirect = content.REDIRECTS.get(path)484 if redirect is not None:485 status, location = redirect486 return web.Response(status=status, headers={"Location": location, **NO_STORE})487 if path.startswith("/trap/"):488 return _trap(request)489 if path.startswith("/img/"):490 data = assets.image_bytes(path[len("/img/") :])491 return web.Response(body=data, content_type="image/png") if data else _not_found()492 if path.startswith("/docs/"):493 builder = assets.DOCUMENTS.get(path[len("/docs/") :])494 return web.Response(body=builder(), content_type="application/pdf") if builder else _not_found()495 if path.startswith("/static/"):496 return _static_file(path[len("/static/") :])497 page = content.PAGES.get(content.page_key(path, request.query))498 if page is None and path.startswith("/spa/") and not path.startswith("/spa/api/"):499 page = content.PAGES["/spa/"] # client-side routes all receive the application shell500 if page is None:501 return _not_found()502 return web.Response(body=page.body, headers={"Content-Type": page.content_type, **NO_STORE})503504505def create_app(state: FixtureState | None = None) -> web.Application:506 """Build the fixture application. Pass a ``FixtureState`` to inspect it from the test."""507 app = web.Application()508 app[STATE_KEY] = state if state is not None else FixtureState()509 app.router.add_route("*", "/{tail:.*}", _dispatch)510 return app511512513@dataclass514class RunningFixture:515 host: str516 port: int517 state: FixtureState518 _runner: web.AppRunner519520 @property521 def base_url(self) -> str:522 return f"http://{self.host}:{self.port}"523524 def url(self, path: str) -> str:525 return self.base_url + path526527 async def close(self) -> None:528 await self._runner.cleanup()529530 async def __aenter__(self) -> Self:531 return self532533 async def __aexit__(self, *exc_info: object) -> None:534 await self.close()535536537async def start_fixture(538 host: str = "127.0.0.1", port: int = 0, state: FixtureState | None = None539) -> RunningFixture:540 """Start the site on ``host:port`` (0 = ephemeral port) inside the running event loop."""541 app = create_app(state)542 runner = web.AppRunner(app, access_log=None, shutdown_timeout=0.2)543 await runner.setup()544 sock = socket.socket(socket.AF_INET6 if ":" in host else socket.AF_INET, socket.SOCK_STREAM)545 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)546 sock.bind((host, port))547 site = web.SockSite(runner, sock)548 await site.start()549 return RunningFixture(host=host, port=sock.getsockname()[1], state=app[STATE_KEY], _runner=runner)550551552class FixtureThread:553 """Run the fixture in a background thread, for synchronous tests.554555 ``state`` is only mutated by the server thread; reading it from the test556 thread between requests is safe.557 """558559 def __init__(self, host: str = "127.0.0.1", port: int = 0, state: FixtureState | None = None) -> None:560 self._host, self._port = host, port561 self.state = state if state is not None else FixtureState()562 self._loop = asyncio.new_event_loop()563 self._thread = threading.Thread(target=self._loop.run_forever, name="spider-fixture-site", daemon=True)564 self._fixture: RunningFixture | None = None565566 def start(self) -> Self:567 self._thread.start()568 future = asyncio.run_coroutine_threadsafe(start_fixture(self._host, self._port, self.state), self._loop)569 self._fixture = future.result(timeout=10)570 return self571572 @property573 def port(self) -> int:574 assert self._fixture is not None, "fixture not started"575 return self._fixture.port576577 @property578 def base_url(self) -> str:579 assert self._fixture is not None, "fixture not started"580 return self._fixture.base_url581582 def url(self, path: str) -> str:583 return self.base_url + path584585 def close(self) -> None:586 if self._fixture is not None:587 asyncio.run_coroutine_threadsafe(self._fixture.close(), self._loop).result(timeout=10)588 self._fixture = None589 self._loop.call_soon_threadsafe(self._loop.stop)590 self._thread.join(timeout=10)591 self._loop.close()592593 def __enter__(self) -> Self:594 return self.start()595596 def __exit__(self, *exc_info: object) -> None:597 self.close()598599600def main(argv: list[str] | None = None) -> None:601 parser = argparse.ArgumentParser(description="Run the SPIDER fixture website.")602 parser.add_argument("--host", default="127.0.0.1")603 parser.add_argument("--port", type=int, default=8765)604 args = parser.parse_args(argv)605606 async def serve() -> None:607 fixture = await start_fixture(args.host, args.port)608 print(f"SPIDER fixture site listening on {fixture.base_url} (Ctrl+C to stop)", flush=True)609 try:610 await asyncio.Event().wait()611 finally:612 await fixture.close()613614 try:615 asyncio.run(serve())616 except KeyboardInterrupt:617 pass618619620if __name__ == "__main__":621 main()622