vibe-sketcherDocumentation

Source code for vibesketcher.server.guest_loading

"""REST routes for reproducible guest loading into periodic hosts (#203).

A preview reads the current document and changes nothing; applying is
checked against the document revision (and optionally the previewed host
digest) and recorded as an edit; an applied loading has an undo route that
refuses when the loaded model changed since.
"""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, ConfigDict, Field, ValidationError

from vibesketcher.document.model import Document
from vibesketcher.server.documents import (
    DocumentResponse,
    RevisionRequest,
    _response,
    _with_edit,
)
from vibesketcher.server.store import Conflict, Entry, NotFound, Store


[docs] class LoadingPreviewRequest(BaseModel): model_config = ConfigDict(extra="forbid") loading: dict[str, Any]
[docs] class LoadingRequest(RevisionRequest): loading: dict[str, Any] source_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
[docs] class LoadingUndoRequest(RevisionRequest): structure: str
def _errors(error: ValidationError) -> list[str]: return [f"{'.'.join(str(x) for x in e['loc'])}: {e['msg']}" for e in error.errors()]
[docs] def router(store: Store) -> APIRouter: routes = APIRouter( prefix="/api/documents/{identifier}/periodic/guests", tags=["periodic guests"] ) def entry_or_404(identifier: str) -> Entry: try: return store.get(identifier) except NotFound: raise HTTPException(404, f"no document {identifier!r}") from None def check(entry: Entry, revision: int) -> None: if revision != entry.document.revision: raise HTTPException(409, {"revision": entry.document.revision}) def commit(entry: Entry, document: Document, request: RevisionRequest, summary: str) -> Any: try: replaced = store.replace( entry.id, _with_edit(document, request, summary), expected=request.revision, warnings=entry.warnings, ) except Conflict as error: raise HTTPException(409, {"message": str(error), "revision": error.current}) from None return _response(replaced) @routes.post("/preview") def loading_preview(identifier: str, request: LoadingPreviewRequest) -> dict[str, Any]: """Counts, rejections, refusals, parent identities and the loaded model; no change.""" from vibesketcher.document.guest_loading import parse_loading, preview entry = entry_or_404(identifier) try: loading = parse_loading(request.loading) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None found = {s.id: s for s in entry.document.periodic_structures} if loading.source not in found: raise HTTPException(404, "periodic structure not found") try: result = preview(found[loading.source], loading, entry.document) except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None return {"revision": entry.document.revision, **result} @routes.post("") def loading_apply(identifier: str, request: LoadingRequest) -> DocumentResponse: """Add the previewed loaded model; refused while the preview has refusals.""" from vibesketcher.document.guest_loading import apply, parse_loading entry = entry_or_404(identifier) check(entry, request.revision) try: loading = parse_loading(request.loading) document = apply(entry.document, loading, source_sha256=request.source_sha256) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None except ValueError as error: raise HTTPException(422, {"errors": [str(error)]}) from None made = document.periodic_structures[-1].id response: DocumentResponse = commit( entry, document, request, f"Loaded guests into {made} from {loading.source}" ) return response @routes.post("/undo") def loading_undo(identifier: str, request: LoadingUndoRequest) -> DocumentResponse: """Remove a loaded model again while it is unchanged.""" from vibesketcher.document.guest_loading import undo entry = entry_or_404(identifier) check(entry, request.revision) try: document = undo(entry.document, request.structure) except ValueError as error: raise HTTPException(409, {"errors": [str(error)]}) from None response: DocumentResponse = commit( entry, document, request, f"Undid the guest loading of {request.structure}" ) return response return routes