markdotserver 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,741 @@
1
+ # SPDX-FileCopyrightText: 2026 Alexey Agafonov
2
+ # SPDX-License-Identifier: MIT
3
+ """HTTP routes for the read-only documentation viewer.
4
+
5
+ Every route resolves paths through :class:`~markdotserver.filesystem.Filesystem`,
6
+ so traversal, hidden names, unsupported files and symlink escapes are rejected in
7
+ one place. Blocking filesystem work, Markdown rendering and Graphviz subprocesses
8
+ run in worker threads rather than on the event loop.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import html
15
+ import logging
16
+ import os
17
+ import unicodedata
18
+ from collections.abc import Iterator
19
+ from dataclasses import dataclass
20
+ from functools import partial
21
+ from pathlib import Path, PurePosixPath
22
+ from typing import Any, Literal
23
+ from urllib.parse import quote
24
+
25
+ from fastapi import APIRouter, HTTPException, Request
26
+ from fastapi.responses import (
27
+ HTMLResponse,
28
+ JSONResponse,
29
+ PlainTextResponse,
30
+ RedirectResponse,
31
+ Response,
32
+ StreamingResponse,
33
+ )
34
+
35
+ from markdotserver.filesystem import (
36
+ SOURCE_KINDS,
37
+ Entry,
38
+ FileKind,
39
+ UnsupportedFile,
40
+ is_asset,
41
+ is_document,
42
+ is_source,
43
+ )
44
+ from markdotserver.graphviz_renderer import GraphvizError
45
+ from markdotserver.markdown_renderer import Heading
46
+
47
+ __all__ = [
48
+ "SECURITY_HEADERS",
49
+ "DocumentView",
50
+ "encode_path",
51
+ "error_response",
52
+ "router",
53
+ ]
54
+
55
+ router = APIRouter()
56
+
57
+ _LOGGER = logging.getLogger("markdotserver")
58
+
59
+ #: Applied to every response the application generates. The page markup contains
60
+ #: no inline scripts and no inline style blocks, so neither ``script-src`` nor
61
+ #: ``style-src`` needs ``'unsafe-inline'``.
62
+ _CONTENT_SECURITY_POLICY = (
63
+ "default-src 'self'; "
64
+ "script-src 'self'; "
65
+ "style-src 'self'; "
66
+ "img-src 'self' data:; "
67
+ "font-src 'self'; "
68
+ "connect-src 'self'; "
69
+ "form-action 'none'; "
70
+ "frame-ancestors 'none'; "
71
+ "base-uri 'none'; "
72
+ "object-src 'none'"
73
+ )
74
+
75
+ SECURITY_HEADERS = {
76
+ "X-Content-Type-Options": "nosniff",
77
+ "Referrer-Policy": "no-referrer",
78
+ "X-Frame-Options": "DENY",
79
+ "Content-Security-Policy": _CONTENT_SECURITY_POLICY,
80
+ "Permissions-Policy": (
81
+ "camera=(), microphone=(), geolocation=(), interest-cohort=()"
82
+ ),
83
+ }
84
+
85
+ #: ``/`` and ``/view/`` answer differently for fragment requests, so caches
86
+ #: (and embedders who relax ``no-store``) must key on that header.
87
+ _DYNAMIC_HEADERS = {
88
+ **SECURITY_HEADERS,
89
+ "Cache-Control": "no-store",
90
+ "Vary": "X-Fragment",
91
+ }
92
+
93
+ #: Graphviz SVG is displayed in an opaque origin: no scripts, no same-origin
94
+ #: access, inline presentation styles still allowed. It is only ever loaded
95
+ #: through ``<img>`` or ``fetch``, never framed, so framing is refused too.
96
+ _SVG_HEADERS = {
97
+ "Content-Security-Policy": (
98
+ "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; sandbox"
99
+ ),
100
+ "X-Content-Type-Options": "nosniff",
101
+ "Referrer-Policy": "no-referrer",
102
+ "X-Frame-Options": "DENY",
103
+ "Cache-Control": "no-cache",
104
+ }
105
+
106
+ _ASSET_HEADERS = {**SECURITY_HEADERS, "Cache-Control": "no-cache"}
107
+
108
+ #: Generated once per process and never changes, so it can be cached by the
109
+ #: browser instead of being inlined into every page.
110
+ _STYLESHEET_HEADERS = {
111
+ **SECURITY_HEADERS,
112
+ "Cache-Control": "public, max-age=3600",
113
+ }
114
+
115
+ _IMAGE_MEDIA_TYPES = {
116
+ ".gif": "image/gif",
117
+ ".jpeg": "image/jpeg",
118
+ ".jpg": "image/jpeg",
119
+ ".png": "image/png",
120
+ ".svg": "image/svg+xml",
121
+ ".webp": "image/webp",
122
+ }
123
+
124
+ _STATUS_TITLES = {
125
+ 400: "Bad request",
126
+ 403: "Permission denied",
127
+ 404: "Not found",
128
+ 413: "Content too large",
129
+ 415: "Unsupported media type",
130
+ 422: "Unable to render document",
131
+ 500: "Server error",
132
+ 503: "Graphviz is unavailable",
133
+ 504: "Graphviz rendering timed out",
134
+ }
135
+
136
+ _SOURCE_KIND_VALUES = frozenset(kind.value for kind in SOURCE_KINDS)
137
+
138
+
139
+ @dataclass(frozen=True, slots=True)
140
+ class DocumentView:
141
+ """The data the document partial needs for one content-pane response."""
142
+
143
+ kind: str
144
+ mode: str = "rendered"
145
+ path: str = ""
146
+ html: str = ""
147
+ text: str = ""
148
+ source: str = ""
149
+ error: str = ""
150
+ entries: tuple[Entry, ...] = ()
151
+ lossy_decode: bool = False
152
+
153
+ @property
154
+ def source_available(self) -> bool:
155
+ return self.kind in _SOURCE_KIND_VALUES
156
+
157
+
158
+ def encode_path(path: str) -> str:
159
+ """Percent-encode each POSIX path component for use in a URL."""
160
+ return "/".join(quote(part, safe="") for part in path.split("/") if part)
161
+
162
+
163
+ def _wants_fragment(request: Request) -> bool:
164
+ return request.headers.get("X-Fragment", "").strip().lower() == "true"
165
+
166
+
167
+ def _etag_matches(if_none_match: str | None, etag: str) -> bool:
168
+ """Return whether an ``If-None-Match`` header covers the current ETag.
169
+
170
+ RFC 9110 §13.1.2 compares the comma-separated entity-tags weakly, so a
171
+ client holding the same representation under a weak validator
172
+ (``W/"..."``) or among a list of validators still gets a ``304`` and no
173
+ Graphviz subprocess runs. ``*`` matches any current representation.
174
+ """
175
+ if not if_none_match:
176
+ return False
177
+ for candidate in if_none_match.split(","):
178
+ candidate = candidate.strip()
179
+ if candidate == "*":
180
+ return True
181
+ if candidate.startswith("W/"):
182
+ candidate = candidate[2:].strip()
183
+ if candidate == etag:
184
+ return True
185
+ return False
186
+
187
+
188
+ def _ascii_fallback(stem: str) -> str:
189
+ """Return a printable-ASCII approximation of a filename stem.
190
+
191
+ Accents are decomposed rather than dropped, so ``café`` falls back to
192
+ ``cafe`` for clients that ignore ``filename*``.
193
+ """
194
+ decomposed = unicodedata.normalize("NFKD", stem)
195
+ ascii_only = decomposed.encode("ascii", "ignore").decode("ascii")
196
+ cleaned = "".join(
197
+ char if char.isalnum() or char in "-_." else "_" for char in ascii_only
198
+ ).strip("._")
199
+ return cleaned or "diagram"
200
+
201
+
202
+ def _content_disposition(path: str) -> str:
203
+ """Build an RFC 6266 attachment header that survives non-ASCII names.
204
+
205
+ Percent-escapes inside a plain ``filename`` parameter are not decoded by
206
+ browsers, so the raw UTF-8 name has to travel in ``filename*``.
207
+ """
208
+ stem = PurePosixPath(path).stem or "diagram"
209
+ fallback = quote(_ascii_fallback(stem), safe="")
210
+ extended = quote(f"{stem}.svg", safe="")
211
+ return f"attachment; filename=\"{fallback}.svg\"; filename*=UTF-8''{extended}"
212
+
213
+
214
+ def _base_context(request: Request) -> dict[str, object]:
215
+ return {"request": request}
216
+
217
+
218
+ def _render(request: Request, template_name: str, context: dict[str, object]) -> str:
219
+ template = request.app.state.templates.get_template(template_name)
220
+ return str(template.render({**_base_context(request), **context}))
221
+
222
+
223
+ def _html(
224
+ request: Request,
225
+ template_name: str,
226
+ context: dict[str, object],
227
+ *,
228
+ status_code: int = 200,
229
+ headers: dict[str, str] | None = None,
230
+ ) -> HTMLResponse:
231
+ return HTMLResponse(
232
+ _render(request, template_name, context),
233
+ status_code=status_code,
234
+ headers=headers or dict(_DYNAMIC_HEADERS),
235
+ )
236
+
237
+
238
+ def _page_context(
239
+ *,
240
+ tree: tuple[Entry, ...],
241
+ path: str,
242
+ document: DocumentView,
243
+ headings: tuple[Heading, ...] = (),
244
+ ) -> dict[str, object]:
245
+ return {
246
+ "tree": tree,
247
+ "path": path,
248
+ "selected": path,
249
+ "document": document,
250
+ "headings": headings,
251
+ "mode": document.mode,
252
+ "kind": document.kind,
253
+ "source_available": document.source_available,
254
+ "document_error": bool(document.error),
255
+ "oob": False,
256
+ }
257
+
258
+
259
+ def _page(
260
+ request: Request,
261
+ context: dict[str, object],
262
+ *,
263
+ status_code: int = 200,
264
+ ) -> HTMLResponse:
265
+ return _html(request, "index.html", context, status_code=status_code)
266
+
267
+
268
+ def _fragment(
269
+ request: Request,
270
+ context: dict[str, object],
271
+ *,
272
+ status_code: int = 200,
273
+ ) -> HTMLResponse:
274
+ body = "".join(
275
+ (
276
+ _render(request, "partials/document.html", context),
277
+ _render(request, "partials/toolbar.html", {**context, "oob": True}),
278
+ _render(request, "partials/headings.html", {**context, "oob": True}),
279
+ )
280
+ )
281
+ return HTMLResponse(body, status_code=status_code, headers=dict(_DYNAMIC_HEADERS))
282
+
283
+
284
+ async def _safe_tree(request: Request, *, fresh: bool = False) -> tuple[Entry, ...]:
285
+ """Build the sidebar tree, degrading to an empty tree rather than failing.
286
+
287
+ An error page must never depend on the work that just failed, so any problem
288
+ at all here yields an empty tree instead of a second exception.
289
+ """
290
+ try:
291
+ return await asyncio.to_thread(
292
+ request.app.state.filesystem.build_tree, fresh=fresh
293
+ )
294
+ except Exception:
295
+ _LOGGER.warning("could not build the directory tree", exc_info=True)
296
+ return ()
297
+
298
+
299
+ async def _off_loop(request: Request, func: Any, /, *args: Any, **kwargs: Any) -> Any:
300
+ """Run blocking rendering work on the dedicated bounded executor.
301
+
302
+ Markdown rendering and Graphviz subprocesses are the slow paths. Keeping them
303
+ off the default ``asyncio.to_thread`` pool means a handful of expensive
304
+ documents cannot starve cheap routes such as ``/health``.
305
+ """
306
+ loop = asyncio.get_running_loop()
307
+ executor = getattr(request.app.state, "render_executor", None)
308
+ return await loop.run_in_executor(executor, partial(func, *args, **kwargs))
309
+
310
+
311
+ async def _inspect(
312
+ request: Request,
313
+ raw_path: str,
314
+ *,
315
+ expect: Literal["file", "directory"] | None = "file",
316
+ ) -> tuple[Path, str, FileKind]:
317
+ """Resolve a request path exactly once and return its canonical details."""
318
+ return await asyncio.to_thread(
319
+ request.app.state.filesystem.inspect, raw_path, expect=expect
320
+ )
321
+
322
+
323
+ async def _read(
324
+ request: Request, resolved: Path, relative: str, *, max_bytes: int
325
+ ) -> str:
326
+ return await asyncio.to_thread(
327
+ request.app.state.filesystem.read_resolved,
328
+ resolved,
329
+ raw_path=relative,
330
+ max_bytes=max_bytes,
331
+ )
332
+
333
+
334
+ async def _build_document(
335
+ request: Request,
336
+ raw_path: str,
337
+ mode: str,
338
+ ) -> tuple[DocumentView, tuple[Heading, ...]]:
339
+ state = request.app.state
340
+ resolved, relative, kind = await _inspect(request, raw_path, expect=None)
341
+
342
+ if kind is FileKind.DIRECTORY:
343
+ if mode == "source":
344
+ raise HTTPException(
345
+ status_code=415,
346
+ detail=f"source view is not available for {relative}",
347
+ )
348
+ if request.method == "HEAD":
349
+ # The body is discarded, so skip the listing entirely.
350
+ return (
351
+ DocumentView(kind=kind.value, mode="rendered", path=relative),
352
+ (),
353
+ )
354
+ entries = await asyncio.to_thread(state.filesystem.list_directory, relative)
355
+ return (
356
+ DocumentView(
357
+ kind=kind.value,
358
+ mode="rendered",
359
+ path=relative,
360
+ entries=tuple(entries),
361
+ ),
362
+ (),
363
+ )
364
+
365
+ if not is_document(kind):
366
+ raise UnsupportedFile(f"not a viewable file: {raw_path}")
367
+
368
+ if mode == "source":
369
+ if not is_source(kind):
370
+ raise HTTPException(
371
+ status_code=415,
372
+ detail=f"source view is not available for {relative}",
373
+ )
374
+ if request.method == "HEAD":
375
+ return (
376
+ DocumentView(kind=kind.value, mode="source", path=relative),
377
+ (),
378
+ )
379
+ source = await _read(
380
+ request, resolved, relative, max_bytes=state.config.max_text_file_bytes
381
+ )
382
+ return (
383
+ DocumentView(
384
+ kind=kind.value,
385
+ mode="source",
386
+ path=relative,
387
+ source=source,
388
+ lossy_decode="\ufffd" in source,
389
+ ),
390
+ (),
391
+ )
392
+
393
+ if request.method == "HEAD":
394
+ # A HEAD view would read the file, render Markdown and even probe
395
+ # Graphviz only for the server to throw the body away. Validate the
396
+ # path (above) and stop there.
397
+ return DocumentView(kind=kind.value, mode="rendered", path=relative), ()
398
+
399
+ if kind is FileKind.MARKDOWN:
400
+ text = await _read(
401
+ request, resolved, relative, max_bytes=state.config.max_text_file_bytes
402
+ )
403
+ result = await _off_loop(
404
+ request,
405
+ state.markdown_renderer.render,
406
+ text,
407
+ source_path=relative,
408
+ )
409
+ return (
410
+ DocumentView(
411
+ kind=kind.value,
412
+ mode="rendered",
413
+ path=relative,
414
+ html=result.html,
415
+ lossy_decode="\ufffd" in text,
416
+ ),
417
+ result.headings,
418
+ )
419
+
420
+ if kind is FileKind.GRAPHVIZ:
421
+ # Use the Graphviz limit, not the text limit: the same file is read
422
+ # again by /api/svg, and the two must agree or a document between the
423
+ # limits renders a page but then fails to produce its image.
424
+ source = await _read(
425
+ request,
426
+ resolved,
427
+ relative,
428
+ max_bytes=state.config.max_graphviz_source_bytes,
429
+ )
430
+ try:
431
+ # The renderer memoises on a digest of the source, so this probe and
432
+ # the <img src="/api/svg/..."> request share one subprocess.
433
+ await _off_loop(request, state.graphviz.render_svg, source)
434
+ except GraphvizError as exc:
435
+ return (
436
+ DocumentView(
437
+ kind=kind.value,
438
+ mode="rendered",
439
+ path=relative,
440
+ error=str(exc),
441
+ lossy_decode="\ufffd" in source,
442
+ ),
443
+ (),
444
+ )
445
+ return (
446
+ DocumentView(
447
+ kind=kind.value,
448
+ mode="rendered",
449
+ path=relative,
450
+ lossy_decode="\ufffd" in source,
451
+ ),
452
+ (),
453
+ )
454
+
455
+ if kind is FileKind.TEXT:
456
+ text = await _read(
457
+ request, resolved, relative, max_bytes=state.config.max_text_file_bytes
458
+ )
459
+ return (
460
+ DocumentView(
461
+ kind=kind.value,
462
+ mode="rendered",
463
+ path=relative,
464
+ text=text,
465
+ lossy_decode="\ufffd" in text,
466
+ ),
467
+ (),
468
+ )
469
+
470
+ # SVG and raster images are displayed through the asset route.
471
+ return DocumentView(kind=kind.value, mode="rendered", path=relative), ()
472
+
473
+
474
+ @router.api_route("/", methods=["GET", "HEAD"], response_class=HTMLResponse)
475
+ async def home(request: Request) -> Response:
476
+ """Redirect to the default document, or show the welcome page."""
477
+ filesystem = request.app.state.filesystem
478
+ default = await asyncio.to_thread(filesystem.default_document)
479
+ if default is not None:
480
+ return RedirectResponse(
481
+ f"/view/{encode_path(default)}",
482
+ status_code=307,
483
+ headers=dict(_DYNAMIC_HEADERS),
484
+ )
485
+
486
+ tree = await _safe_tree(request)
487
+ document = DocumentView(kind="welcome", mode="rendered")
488
+ context = _page_context(tree=tree, path="", document=document)
489
+ if _wants_fragment(request):
490
+ return _fragment(request, context)
491
+ return _page(request, context)
492
+
493
+
494
+ @router.api_route(
495
+ "/view/{path:path}", methods=["GET", "HEAD"], response_class=HTMLResponse
496
+ )
497
+ async def view(request: Request, path: str, mode: str = "rendered") -> Response:
498
+ """Render a document as a complete page or an HTML fragment."""
499
+ if mode not in ("rendered", "source"):
500
+ raise HTTPException(status_code=400, detail=f"invalid view mode: {mode}")
501
+
502
+ document, headings = await _build_document(request, path, mode)
503
+ tree = await _safe_tree(request)
504
+ context = _page_context(
505
+ tree=tree,
506
+ path=document.path,
507
+ document=document,
508
+ headings=headings,
509
+ )
510
+ if _wants_fragment(request):
511
+ return _fragment(request, context)
512
+ return _page(request, context)
513
+
514
+
515
+ @router.api_route("/api/tree", methods=["GET", "HEAD"])
516
+ async def tree_json(request: Request) -> Response:
517
+ tree = await _safe_tree(request)
518
+ return JSONResponse(
519
+ {"tree": [entry.to_dict() for entry in tree]},
520
+ headers=dict(_DYNAMIC_HEADERS),
521
+ )
522
+
523
+
524
+ @router.api_route(
525
+ "/api/tree/html", methods=["GET", "HEAD"], response_class=HTMLResponse
526
+ )
527
+ async def tree_html(request: Request, path: str = "") -> Response:
528
+ # This is the interface's explicit Refresh control, so it must bypass the
529
+ # tree cache and show files created since the last scan.
530
+ tree = await _safe_tree(request, fresh=True)
531
+ return _html(
532
+ request,
533
+ "partials/directory_tree.html",
534
+ {"tree": tree, "path": path, "selected": path, "oob": False},
535
+ )
536
+
537
+
538
+ @router.api_route("/api/headings/{path:path}", methods=["GET", "HEAD"])
539
+ async def headings_json(request: Request, path: str) -> Response:
540
+ state = request.app.state
541
+ resolved, relative, kind = await _inspect(request, path)
542
+ if kind is not FileKind.MARKDOWN:
543
+ return JSONResponse({"headings": []}, headers=dict(_DYNAMIC_HEADERS))
544
+
545
+ text = await _read(
546
+ request, resolved, relative, max_bytes=state.config.max_text_file_bytes
547
+ )
548
+ headings = await _off_loop(
549
+ request,
550
+ state.markdown_renderer.parse_headings,
551
+ text,
552
+ source_path=relative,
553
+ )
554
+ return JSONResponse(
555
+ {"headings": [heading.to_dict() for heading in headings]},
556
+ headers=dict(_DYNAMIC_HEADERS),
557
+ )
558
+
559
+
560
+ @router.api_route(
561
+ "/api/render/{path:path}", methods=["GET", "HEAD"], response_class=HTMLResponse
562
+ )
563
+ async def render_fragment(request: Request, path: str) -> Response:
564
+ document, headings = await _build_document(request, path, "rendered")
565
+ context = _page_context(
566
+ tree=(),
567
+ path=document.path,
568
+ document=document,
569
+ headings=headings,
570
+ )
571
+ return _html(request, "partials/document.html", context)
572
+
573
+
574
+ @router.api_route("/api/svg/{path:path}", methods=["GET", "HEAD"])
575
+ async def svg(request: Request, path: str, download: str = "0") -> Response:
576
+ state = request.app.state
577
+ resolved, relative, kind = await _inspect(request, path)
578
+ if kind is not FileKind.GRAPHVIZ:
579
+ raise UnsupportedFile(f"not a Graphviz document: {path}")
580
+
581
+ source = await _read(
582
+ request,
583
+ resolved,
584
+ relative,
585
+ max_bytes=state.config.max_graphviz_source_bytes,
586
+ )
587
+
588
+ # The render cache is keyed on this digest, so a matching If-None-Match
589
+ # means the client already holds exactly what a render would produce.
590
+ etag = f'"{state.graphviz.cache_key(source)}"'
591
+ headers = dict(_SVG_HEADERS)
592
+ headers["ETag"] = etag
593
+ if _etag_matches(request.headers.get("if-none-match"), etag):
594
+ return Response(status_code=304, headers=headers)
595
+ if request.method == "HEAD":
596
+ response = Response(
597
+ status_code=200, media_type="image/svg+xml", headers=headers
598
+ )
599
+ # Starlette stamps an empty-body 200 with ``Content-Length: 0``. A HEAD
600
+ # response should describe the entity a GET would return, or nothing:
601
+ # zero bytes would mislead caches and link checkers.
602
+ if "content-length" in response.headers:
603
+ del response.headers["content-length"]
604
+ return response
605
+
606
+ svg_bytes = await _off_loop(request, state.graphviz.render_svg, source)
607
+
608
+ if download == "1":
609
+ headers["Content-Disposition"] = _content_disposition(relative)
610
+ return Response(content=svg_bytes, media_type="image/svg+xml", headers=headers)
611
+
612
+
613
+ @router.api_route(
614
+ "/api/source/{path:path}", methods=["GET", "HEAD"], response_class=PlainTextResponse
615
+ )
616
+ async def source(request: Request, path: str) -> Response:
617
+ state = request.app.state
618
+ resolved, relative, kind = await _inspect(request, path)
619
+ if not is_source(kind):
620
+ raise HTTPException(
621
+ status_code=415,
622
+ detail=f"source view is not available for {relative}",
623
+ )
624
+ text = await _read(
625
+ request, resolved, relative, max_bytes=state.config.max_text_file_bytes
626
+ )
627
+ return PlainTextResponse(text, headers=dict(_DYNAMIC_HEADERS))
628
+
629
+
630
+ _ASSET_CHUNK_BYTES = 65_536
631
+
632
+
633
+ def _stream_descriptor(descriptor: int, size: int) -> Iterator[bytes]:
634
+ """Yield exactly ``size`` bytes of an open descriptor, then close it.
635
+
636
+ The response's ``Content-Length`` was taken from ``fstat`` at open time, so
637
+ the stream must match it even if the file grows or shrinks underneath: extra
638
+ bytes are not sent, and a truncated file ends the body early rather than
639
+ blocking.
640
+ """
641
+ remaining = size
642
+ with os.fdopen(descriptor, "rb") as stream:
643
+ while remaining > 0:
644
+ chunk = stream.read(min(_ASSET_CHUNK_BYTES, remaining))
645
+ if not chunk:
646
+ break
647
+ remaining -= len(chunk)
648
+ yield chunk
649
+
650
+
651
+ @router.api_route("/assets/{path:path}", methods=["GET", "HEAD"])
652
+ async def asset(request: Request, path: str) -> Response:
653
+ # Assets are served from a descriptor opened with O_NOFOLLOW rather than by
654
+ # re-opening the path, so the final component cannot be swapped for a
655
+ # symlink between resolving and reading.
656
+ resolved, relative, kind = await _inspect(request, path)
657
+ if not is_asset(kind):
658
+ raise UnsupportedFile(f"not a servable asset: {path}")
659
+
660
+ media_type = _IMAGE_MEDIA_TYPES.get(PurePosixPath(relative).suffix.lower())
661
+ if media_type is None:
662
+ raise UnsupportedFile(f"unsupported asset type: {path}")
663
+ headers = dict(_SVG_HEADERS if kind is FileKind.SVG else _ASSET_HEADERS)
664
+
665
+ descriptor, size = await asyncio.to_thread(
666
+ request.app.state.filesystem.open_asset, resolved, raw_path=relative
667
+ )
668
+ headers["Content-Length"] = str(size)
669
+ if request.method == "HEAD":
670
+ os.close(descriptor)
671
+ return Response(status_code=200, media_type=media_type, headers=headers)
672
+ try:
673
+ return StreamingResponse(
674
+ _stream_descriptor(descriptor, size),
675
+ media_type=media_type,
676
+ headers=headers,
677
+ )
678
+ except BaseException:
679
+ # The response owns the descriptor only once it is constructed.
680
+ os.close(descriptor)
681
+ raise
682
+
683
+
684
+ @router.api_route("/pygments.css", methods=["GET", "HEAD"], response_class=Response)
685
+ async def pygments_stylesheet(request: Request) -> Response:
686
+ """Serve the syntax-highlighting stylesheet as one cacheable asset."""
687
+ return Response(
688
+ content=request.app.state.pygments_stylesheet,
689
+ media_type="text/css; charset=utf-8",
690
+ headers=dict(_STYLESHEET_HEADERS),
691
+ )
692
+
693
+
694
+ @router.api_route("/favicon.ico", methods=["GET", "HEAD"])
695
+ async def favicon() -> Response:
696
+ """Browsers request this unconditionally; answer cheaply, not a 404 page."""
697
+ return Response(status_code=204, headers=dict(_DYNAMIC_HEADERS))
698
+
699
+
700
+ @router.api_route("/health", methods=["GET", "HEAD"])
701
+ async def health() -> Response:
702
+ return JSONResponse({"status": "ok"}, headers=dict(_DYNAMIC_HEADERS))
703
+
704
+
705
+ def _plain_error(status_code: int, title: str, message: str) -> Response:
706
+ """A template-free error body, used when rendering the error page fails."""
707
+ body = (
708
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">'
709
+ f"<title>{html.escape(title)}</title></head><body>"
710
+ f"<h1>{html.escape(title)}</h1>"
711
+ f"<p>HTTP {int(status_code)}</p>"
712
+ f"<p>{html.escape(message)}</p>"
713
+ "</body></html>"
714
+ )
715
+ return HTMLResponse(body, status_code=status_code, headers=dict(_DYNAMIC_HEADERS))
716
+
717
+
718
+ async def error_response(request: Request, status_code: int, message: str) -> Response:
719
+ """Render a safe error page, or an error fragment for fragment requests."""
720
+ title = _STATUS_TITLES.get(status_code, "Request failed")
721
+ try:
722
+ path = str(request.path_params.get("path", ""))
723
+ except Exception: # noqa: BLE001 - path_params may be absent while routing
724
+ path = ""
725
+ document = DocumentView(kind="error", mode="error", path=path, error=message)
726
+ tree = await _safe_tree(request)
727
+ context = _page_context(tree=tree, path=path, document=document)
728
+ context.update(
729
+ {
730
+ "error_message": message,
731
+ "error_title": title,
732
+ "status_code": status_code,
733
+ }
734
+ )
735
+ try:
736
+ if _wants_fragment(request):
737
+ return _fragment(request, context, status_code=status_code)
738
+ return _page(request, context, status_code=status_code)
739
+ except Exception:
740
+ _LOGGER.exception("could not render the error page for %s", request.url.path)
741
+ return _plain_error(status_code, title, message)