Coverage for lode / api.py: 87%
200 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
1# lode/api.py
2"""LODE 2.0 — HTTP API.
4Endpoints:
5 GET / web form
6 GET /health liveness probe
7 GET /extract render an artefact (HTML, or RDF via content negotiation)
8 POST /extract same, from an uploaded file
9 GET /build static documentation site, as a ZIP archive
10 POST /build same, from an uploaded file
11"""
13# ==========================================================================
14# 1. IMPORTS
15# ==========================================================================
16from pathlib import Path
17from typing import Optional, Dict, Tuple
18from urllib.parse import urlencode
19import hashlib
20import logging
21import os
22import shutil
23import traceback
24from pathlib import Path
26from fastapi import FastAPI, File, Form, HTTPException, Query, Request, UploadFile
27from fastapi.responses import FileResponse, HTMLResponse, Response
28from fastapi.staticfiles import StaticFiles
29from fastapi.templating import Jinja2Templates
30from starlette.background import BackgroundTask
31from starlette.concurrency import run_in_threadpool
32from starlette.middleware.gzip import GZipMiddleware
33from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
35# Internal modules
36from lode import profiles
37from lode.helpers.formats import SERIALIZATION_FORMATS
38from lode.helpers.html_utils import minify as _minify
39import lode.helpers.spool as spool
40import lode.core as core
41from lode import security
42from lode.exceptions import ArtefactValidationError, BuildCapacityError, LODEError
43from lode.helpers.site_zip import build_zip, slugify
44from lode.helpers.rdf import iri_local_name
45from urllib.parse import quote, urlencode
46from lode.helpers.links import Links
48# ==========================================================================
49# 2. APP SETUP
50# ==========================================================================
51LOG_LEVEL = os.getenv("LODE_LOG_LEVEL", "WARNING").strip().upper()
53logging.basicConfig(
54 level=LOG_LEVEL,
55 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
56)
57# Third-party loggers: silence per-request HTTP noise and URI warnings.
58logging.getLogger("urllib3").setLevel(logging.WARNING)
59logging.getLogger("rdflib").setLevel(logging.ERROR)
60logger = logging.getLogger(__name__)
62# When enabled, error pages include the full traceback (development only).
63DEBUG = os.getenv("LODE_DEBUG", "").strip().lower() in ("1", "true", "yes", "on")
65TAGS_METADATA = [
66 {"name": "extract", "description": "Render a semantic artefact as HTML or serialized RDF."},
67 {"name": "build", "description": "Generate a full static documentation site, delivered as a ZIP."},
68 {"name": "ops", "description": "Operational endpoints: web form and health probe."},
69]
71app = FastAPI(
72 title="LODE 2.0 API",
73 version="0.3.12",
74 description="Live OWL Documentation Environment — extract and document "
75 "RDF/OWL/SKOS semantic artefacts as browsable HTML.",
76 license_info={"name": "ISC"},
77 contact={"name": "OpenCitations", "url": "https://github.com/opencitations/lode"},
78 openapi_tags=TAGS_METADATA,
79)
81# Compress HTML responses on the wire.
82app.add_middleware(GZipMiddleware, minimum_size=1000)
83# Fix "blocked loading mixed active content" on style.css behind a proxy.
84app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
86_PKG_DIR = Path(__file__).resolve().parent
87app.mount("/static", StaticFiles(directory=str(_PKG_DIR / "static")), name="static")
90def _jinja_templates(template_dirs) -> Jinja2Templates:
91 """Build a Jinja environment over a search path of template folders; the first match wins.
93 The produced HTML is beautified (trim_blocks, lstrip_blocks) before it is minified.
94 """
95 built = Jinja2Templates(directory=[str(d) for d in template_dirs])
96 built.env.trim_blocks = True
97 built.env.lstrip_blocks = True
98 return built
100# The base templates: they also hold index.html and error.html, which no format replaces.
101templates = _jinja_templates([_PKG_DIR / "templates"])
103# One environment per search path (that is, per format), built on first use: compiling the
104# templates on every request would be slow. Two threads may build the same one; harmless.
105_format_templates: Dict[Tuple[str, ...], Jinja2Templates] = {}
107def _templates_for(template_dirs) -> Jinja2Templates:
108 """Return the Jinja environment of a search path, built on first use and then reused."""
109 key = tuple(str(d) for d in template_dirs)
110 if key not in _format_templates:
111 _format_templates[key] = _jinja_templates(template_dirs)
112 return _format_templates[key]
114class _WebLinks(Links):
115 """The addresses of the web service: every page is a request to /extract that keeps the view parameters."""
117 def __init__(self, nav_qs: str, read_as: Optional[str] = None, lang: Optional[str] = None):
118 """`nav_qs` is the query string of the current view (see _nav_qs); `read_as` and `lang` its format and language."""
119 self._qs = nav_qs
120 self._read_as = read_as
121 self._lang = lang
123 def visualize(self, iri: str) -> Optional[str]:
124 """Return the request that documents another ontology, read as the same format."""
125 if not self._read_as:
126 return None
127 return "/extract?" + urlencode({"read_as": self._read_as, "url": iri, "lang": self._lang or "en"})
130 def resource(self, iri: str) -> str:
131 """Return the request for the page of a resource."""
132 return f"/extract?{self._qs}&resource={quote(iri, safe='/')}"
134 def export(self, ext: str, iri: Optional[str] = None) -> str:
135 """Return the request that serializes the artefact, or a resource, in the format with extension `ext`."""
136 resource = f"&resource={quote(iri, safe='/')}" if iri else ""
137 return f"/extract?{self._qs}{resource}&format={ext}"
139 def home(self) -> str:
140 """Return the request for the page of the whole artefact."""
141 return f"/extract?{self._qs}"
144# ==========================================================================
145# 6. HTML HELPERS
146# ==========================================================================
148def _nav_qs(read_as: str, url, upload_id, lang, imported, closure, partial_import) -> str:
149 """Build the query string that keeps the current view parameters in navigation links.
151 Exactly one of `upload_id` and `url` is emitted, so a link never mixes the two
152 sources. Boolean options are included only when enabled.
153 """
154 p = {"read_as": read_as, "lang": lang or ""}
155 p["upload_id" if upload_id else "url"] = upload_id or (url or "")
156 if imported:
157 p["imported"] = "true"
158 if closure:
159 p["closure"] = "true"
160 if partial_import:
161 p["partial_import"] = "true"
163 return urlencode(p)
165def _render_view(request, artefact, *, resource, lang, source_url, upload_id, read_as,
166 imported=None, closure=None, partial_import=None):
167 """Render one resource (or the whole artefact) as the minified viewer page.
169 The page is rendered from the viewer contract alone: every address in it comes from
170 _WebLinks, which keeps the current source and options in the query string.
171 The body is minified after rendering, so Content-Length is recomputed:
172 keeping the old value would truncate the response.
173 """
174 links = _WebLinks(_nav_qs(read_as, source_url, upload_id, lang, imported, closure, partial_import),
175 read_as, lang)
176 data = artefact.viewer.view(resource_uri=resource, language=lang, links=links)
177 resp = _templates_for(artefact.viewer.template_dirs()).TemplateResponse(request, "page.html", dict(data))
178 resp.body = _minify(resp.body.decode("utf-8")).encode("utf-8")
179 resp.headers["content-length"] = str(len(resp.body))
180 return resp
183# ==========================================================================
184# 7. READER RESOLUTION
185# ==========================================================================
186def _url_token(url, read_as, imported, closure, partial_import) -> str:
187 """Return the stable cache key for a URL and its load options.
189 Every option that changes the loaded graph is part of the key, so two
190 requests share a cached copy only if they would produce the same result.
191 """
192 key =f"{url}|{read_as}|{imported}|{closure}|{partial_import}".encode()
193 return "url_" + hashlib.sha256(key).hexdigest()[:32]
196def _load_url(url, read_as, imported, closure, partial_import, warnings, use_cache=True):
197 """Load an artefact from a URL, through the disk cache when allowed.
199 The URL is validated first (SSRF protection). Only the main document is
200 cached: modules (imports, closure) are re-applied on every hit, so the cache
201 never goes stale on remote ontologies. Blocking: network and disk I/O.
202 """
203 # Enforce http(s)://host up front: a non-URL value (local path, file://, ...)
204 # must never reach the loader and be opened as a local file.
205 security.check_url_safe(url)
206 spool.prune()
207 token = _url_token(url, read_as, imported, closure, partial_import)
208 path = spool.get_path(token)
209 if use_cache and os.path.exists(path):
210 # cache hit: rebuild from the saved Turtle
211 return core.read(path, read_as, imported=imported, closure=closure,
212 partial_import=partial_import, warnings=warnings, source_name=url)
213 if not use_cache:
214 # cache=false: drop the stale copy so the fresh fetch replaces it
215 try:
216 os.unlink(path)
217 except OSError:
218 pass
219 # cache miss (or forced refresh): fetch and process the URL
220 artefact = core.read(url, read_as, imported=imported, closure=closure,
221 partial_import=partial_import, warnings=warnings)
222 # persist ONLY the main document: modules are re-applied on every hit.
223 try:
224 main = artefact.main_graph()
225 with open(path, "wb") as f:
226 f.write(main.serialize(format="turtle").encode("utf-8"))
227 except OSError:
228 pass
229 return artefact
231def _resolve_artefact(read_as: str, url, upload_id, imported, closure, partial_import, warnings,
232 use_cache=True):
233 """Read an artefact from an uploaded file or from a URL.
235 Raises ArtefactValidationError when the upload has expired or when neither
236 source is given. Uploads win over URLs and are never re-fetched.
237 """
238 if upload_id:
239 # Uploads are not re-fetched, so the cache flag does not apply to them.
240 path = spool.get_path(upload_id)
241 if not os.path.exists(path):
242 raise ArtefactValidationError("Upload expired, please re-upload",
243 context={"upload_id": upload_id})
244 return core.read(path, read_as, imported=imported, closure=closure,
245 partial_import=partial_import, warnings=warnings)
246 if url:
247 return _load_url(url, read_as, imported, closure, partial_import, warnings, use_cache=use_cache)
248 raise ArtefactValidationError("Missing 'url' or 'upload_id'")
251async def _read_validated_upload(file: UploadFile) -> bytes:
252 """Run every upload check in one place, then return the raw bytes."""
253 security.check_extension(file.filename)
254 content = await security.read_upload_capped(file)
255 security.check_is_text(content)
256 security.check_safe_xml(content.decode("utf-8-sig"))
257 return content
260# ==========================================================================
261# 8. ZIP RESPONSE
262# ==========================================================================
263def _zip_response(artefact, slug: str, lang: Optional[str] = None) -> FileResponse:
264 """Build the static site as a ZIP and return it as a download.
266 Blocking and disk-heavy: callers must keep it off the event loop. The build
267 directory is removed once the response has been sent. A service at capacity
268 becomes a 503 with Retry-After, so clients know when to come back.
269 """
270 try:
271 zip_path, workdir = build_zip(artefact, slug, lang)
272 except BuildCapacityError as exc:
273 raise HTTPException(503, str(exc), headers={"Retry-After": str(exc.retry_after)})
274 return FileResponse(
275 zip_path,
276 media_type="application/zip",
277 filename=f"{slug}-lode.zip",
278 background=BackgroundTask(shutil.rmtree, workdir, True),
279 )
282# ==========================================================================
283# 9. ERROR RENDERING
284# ==========================================================================
285def _error_payload(exc: Exception) -> dict:
286 """Build the dict used by error.html for any exception.
288 The traceback is included only for non-LODE errors and only when LODE_DEBUG
289 is set: it is always logged server-side and never shown to users otherwise.
290 """
291 is_lode = isinstance(exc, LODEError)
292 return {
293 "type": type(exc).__name__,
294 "message": str(exc),
295 "context": exc.context if is_lode else {},
296 "request_id": exc.request_id if is_lode else None,
297 # Never leak the traceback to the user in production: it is always logged
298 # server-side; it is only surfaced in the page when LODE_DEBUG is set.
299 "traceback": traceback.format_exc() if (not is_lode and DEBUG) else None,
300 }
303@app.exception_handler(LODEError)
304async def lode_error_handler(request: Request, exc: LODEError):
305 """Show a domain error (LODEError) as an HTML page with HTTP 400."""
306 logger.error(f"{type(exc).__name__}: {exc}")
307 return templates.TemplateResponse(
308 "error.html", {"request": request, "error": _error_payload(exc)}, status_code=400
309 )
312@app.exception_handler(Exception)
313async def unexpected_error_handler(request: Request, exc: Exception):
314 """Show an unhandled exception as an HTML page with HTTP 500.
316 The full traceback goes to the server log; the page shows it only in debug mode.
317 """
318 logger.exception("Unexpected error")
319 return templates.TemplateResponse(
320 "error.html", {"request": request, "error": _error_payload(exc)}, status_code=500
321 )
324# ==========================================================================
325# 10. MIDDLEWARE
326# ==========================================================================
327@app.middleware("http")
328async def limit_upload_size(request: Request, call_next):
329 """Reject oversized POST bodies early, before reading them, when the client
330 declares a Content-Length. (Chunked bodies omit it: those are still capped
331 in read_upload_capped; the hard limit belongs at the reverse proxy.)"""
332 if request.method == "POST":
333 declared = request.headers.get("content-length")
334 if declared and declared.isdigit() and int(declared) > security.MAX_BYTES:
335 exc = ArtefactValidationError(
336 "File too large",
337 context={"bytes": int(declared), "max": security.MAX_BYTES},
338 )
339 return templates.TemplateResponse(
340 "error.html", {"request": request, "error": _error_payload(exc)},
341 status_code=400,
342 )
343 return await call_next(request)
346# ==========================================================================
347# 11. ROUTES — pages
348# ==========================================================================
349@app.get("/", response_class=HTMLResponse, tags=["ops"], summary="Web input form")
350async def input_web_interface(request: Request):
351 """Serve the HTML input form, the entry point of the web interface."""
352 return templates.TemplateResponse(request, "index.html", {
353 "formats": profiles.names(),
354 "enabled_formats": profiles.names(enabled_only=True),
355 })
358@app.get("/health", tags=["ops"], summary="Liveness probe")
359async def health_check():
360 """Return 200 with a fixed body. Used by Docker/K8s readiness checks."""
361 return {"status": "ok"}
364# ==========================================================================
365# 12. ROUTES — /extract
366# ==========================================================================
367@app.get("/extract", tags=["extract"], summary="Render an artefact as HTML or RDF")
368def extract_get(
369 request: Request,
370 read_as: str = Query(description="Artefact type: the name of a registered format, e.g. 'owl' or 'skos'"),
371 url: Optional[str] = Query(None, description="Public http(s) URL of the artefact"),
372 upload_id: Optional[str] = Query(None, description="Token of a previously uploaded file"),
373 resource: Optional[str] = Query(None, description="IRI of a single resource; omit for the whole ontology"),
374 lang: Optional[str] = Query(None, description="Language tag for labels, e.g. 'en', 'it'"),
375 imported: Optional[bool] = Query(None, description="Also load owl:imports (depth 1)"),
376 closure: Optional[bool] = Query(None, description="Load the full owl:imports closure"),
377 partial_import: Optional[bool] = Query(None, description="Additionally load only explicitly mentioned entities from other ontologies"),
378 format: Optional[str] = Query(None, description="Force a serialization (ttl, rdf, jsonld…) instead of HTML"),
379 warnings: bool = Query(False, description="Collect and show reader warnings"),
380 cache: bool = Query(True, description="Use the disk cache for fetched URLs"),
381):
382 """Render an artefact. Returns HTML by default, or RDF when a serialization
383 is requested via the `format` query or the `Accept` header."""
384 artefact = _resolve_artefact(read_as, url, upload_id, imported, closure, partial_import,
385 warnings, use_cache=cache)
387 # Content negotiation: triples of the loaded artefact only, quads are never negotiable
388 accept = request.headers.get("accept", "text/html")
389 available = SERIALIZATION_FORMATS
390 serial = None
392 if format:
393 fmt_l = format.lower()
394 serial = next((f for f in available if f["ext"] == fmt_l), None)
395 if serial is None:
396 raise HTTPException(406, f"Format '{format}' not available for this request")
397 else:
398 for part in accept.split(","):
399 mime = part.split(";", 1)[0].strip()
400 serial = next((f for f in available if f["mime"] == mime), None)
401 if serial:
402 break
404 if serial:
405 serialized = core.export(artefact, serial["fmt"], resource)
406 if resource:
407 filename = iri_local_name(resource) or "resource"
408 else:
409 filename = (iri_local_name(url) if url else "") or "graph"
411 return Response(content=serialized, media_type=serial["mime"],
412 headers={"Content-Disposition": f'inline; filename="{filename}.{serial["ext"]}"'})
414 logger.info("=== REQUEST SUCCESS ===")
415 return _render_view(request, artefact, resource=resource, lang=lang,
416 source_url=url, upload_id=upload_id, read_as=read_as,
417 imported=imported, closure=closure, partial_import=partial_import)
420@app.post("/extract", response_class=HTMLResponse, tags=["extract"],
421 summary="Render an uploaded artefact as HTML")
422async def extract_post(
423 request: Request,
424 read_as: str = Form(..., description="Artefact type of the uploaded file: a registered format, e.g. 'owl' or 'skos'"),
425 file: UploadFile = File(..., description="The artefact file (ttl, rdf, owl…)"),
426 resource: Optional[str] = Form(None, description="IRI of a single resource; omit for the whole ontology"),
427 lang: Optional[str] = Form(None, description="Language tag for labels, e.g. 'en', 'it'"),
428 imported: Optional[bool] = Form(None, description="Also load owl:imports (depth 1)"),
429 partial_import: Optional[bool] = Form(None, description="Additionally load only explicitly mentioned entities from other ontologies"),
430 closure: Optional[bool] = Form(None, description="Load the full owl:imports closure"),
431 warnings: bool = Form(False, description="Collect and show reader warnings"),
432):
433 """Render an artefact from an uploaded file instead of a URL."""
434 logger.info("=== FILE UPLOAD START ===")
435 logger.info(f"Filename: {file.filename}")
436 logger.info(f"Format: {read_as}")
438 content = await _read_validated_upload(file)
439 token = spool.save(content)
441 artefact = await run_in_threadpool(
442 core.read, spool.get_path(token), read_as,
443 imported=imported, closure=closure, partial_import=partial_import, warnings=warnings,
444 )
445 return _render_view(request, artefact, resource=resource, lang=lang,
446 source_url=None, upload_id=token, read_as=read_as,
447 imported=imported, closure=closure, partial_import=partial_import)
450# ==========================================================================
451# 13. ROUTES — /build
452# ==========================================================================
453@app.get("/build", tags=["build"], summary="Build a static site (ZIP) from a URL")
454def build_get(
455 read_as: str = Query(description="Artefact type: the name of a registered format, e.g. 'owl' or 'skos'"),
456 url: Optional[str] = Query(None, description="Public http(s) URL of the artefact"),
457 upload_id: Optional[str] = Query(None, description="Token of a previously uploaded file"),
458 lang: Optional[str] = Query(None, description="Language tag for labels, e.g. 'en', 'it'"),
459 imported: Optional[bool] = Query(None, description="Also load owl:imports (depth 1)"),
460 closure: Optional[bool] = Query(None, description="Load the full owl:imports closure"),
461 partial_import: Optional[bool] = Query(None, description="Additionally load only explicitly mentioned entities from other ontologies"),
462 warnings: bool = Query(False, description="Collect and show reader warnings"),
463 cache: bool = Query(True, description="Use the disk cache for fetched URLs"),
464):
465 """Static documentation site as a ZIP. Sync on purpose: FastAPI runs
466 non-async endpoints in the threadpool, keeping the event loop free."""
467 artefact = _resolve_artefact(read_as, url, upload_id, imported, closure, partial_import,
468 warnings, use_cache=cache)
469 return _zip_response(artefact, slugify(url), lang)
472@app.post("/build", tags=["build"], summary="Build a static site (ZIP) from an upload")
473async def build_post(
474 read_as: str = Form(..., description="Artefact type of the uploaded file: a registered format, e.g. 'owl' or 'skos'"),
475 file: UploadFile = File(..., description="The artefact file (ttl, rdf, owl…)"),
476 lang: Optional[str] = Form(None, description="Language tag for labels, e.g. 'en', 'it'"),
477 imported: Optional[bool] = Form(None, description="Also load owl:imports (depth 1)"),
478 closure: Optional[bool] = Form(None, description="Load the full owl:imports closure"),
479 partial_import: Optional[bool] = Form(None, description="Additionally load only explicitly mentioned entities from other ontologies"),
480 warnings: bool = Form(False, description="Collect and show reader warnings"),
481):
482 """Build the static site from an uploaded file instead of a URL."""
483 content = await _read_validated_upload(file)
484 token = spool.save(content)
486 artefact = await run_in_threadpool(
487 core.read, spool.get_path(token), read_as,
488 imported=imported, closure=closure, partial_import=partial_import, warnings=warnings,
489 )
490 return await run_in_threadpool(_zip_response, artefact, slugify(file.filename), lang)
493# ==========================================================================
494# 14. ENTRY POINT
495# ==========================================================================
496if __name__ == "__main__":
497 import uvicorn
498 uvicorn.run(app, host="0.0.0.0", port=8000)