Coverage for app / routers / documents.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""Render a structured document to PDF — for svc-core, never the browser. 

2 

3svc-core calls this with a document it has *stored*: a ```document fence from 

4a chat message, or a skill run's report outputs. It never forwards content a 

5client posted, so a PDF is always a rendering of something on record. The 

6document is validated again here (``StoredDocument``), however it was 

7produced. No model is involved, and nothing is fetched: the images it shows 

8are the copies stored when it was made (``documents.images``), each drawn only 

9when its bytes hash to the id the fence names. 

10""" 

11 

12from functools import partial 

13 

14from fastapi import APIRouter 

15from fastapi.concurrency import run_in_threadpool 

16from fastapi.responses import Response 

17from pydantic import BaseModel, Field 

18 

19from app.documents.images import load_for_pdf 

20from app.documents.pdf import DrawnVisual, render_pdf 

21from app.documents.spec import StoredDocument 

22from app.util import safe_json 

23from app.util.time import UTCDateTime 

24 

25router = APIRouter(prefix="/documents", tags=["documents"]) 

26 

27 

28class RenderPdfRequest(BaseModel): 

29 document: StoredDocument 

30 #: Provenance printed on every page — what produced the document. 

31 footer: str | None = Field(default=None, max_length=300) 

32 #: When the content was produced; defaults to now. 

33 generated_at: UTCDateTime | None = None 

34 

35 

36#: The response header saying what the PDF drew: each visual fence of the 

37#: document's body, in order, as ``{"kind", "drawn"}`` (a scenario run's 

38#: export reads it; the PDF's own text is subset-encoded and says nothing). 

39VISUALS_HEADER = "X-Document-Visuals" 

40 

41 

42@router.post("/pdf", response_class=Response) 

43async def render_document_pdf(body: RenderPdfRequest) -> Response: 

44 images = await run_in_threadpool(load_for_pdf, body.document) 

45 drawn: list[DrawnVisual] = [] 

46 data = await run_in_threadpool( 

47 partial( 

48 render_pdf, 

49 body.document, 

50 images=images, 

51 footer=body.footer, 

52 generated_at=body.generated_at, 

53 drawn=drawn, 

54 ) 

55 ) 

56 return Response( 

57 content=data, 

58 media_type="application/pdf", 

59 headers={ 

60 VISUALS_HEADER: safe_json.dumps( 

61 [{"kind": v.kind, "drawn": v.drawn} for v in drawn] 

62 ) 

63 }, 

64 )