vibe-sketcherDocumentation

Source code for vibesketcher.server.build_review

"""REST routes for previewing, applying and undoing periodic builds (#201).

``POST /api/documents/{id}/periodic/build`` keeps adding a structure directly.
These routes put the same recipes behind the reviewed contract of the other
builder forms: ``.../periodic/build/preview`` reads the current document and
changes nothing; ``.../periodic/build/apply`` adds the previewed structure,
checked against the document revision, the recipe digest and optionally the
input digest; ``.../periodic/build/undo`` removes it again while it is
unchanged and nothing refers to it. Refusals carry the stable codes of
:data:`vibesketcher.document.build_review.CODES`.
"""

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

_SHA256 = r"^[0-9a-f]{64}$"


[docs] class BuildPreviewRequest(BaseModel): """A preview reads the current document; the answer names its revision.""" model_config = ConfigDict(extra="forbid") recipe: dict[str, Any] #: Also return the full derived structure as ``derived``. structure: bool = False
[docs] class BuildApplyRequest(RevisionRequest): recipe: dict[str, Any] recipe_sha256: str = Field(pattern=_SHA256) inputs_sha256: str | None = Field(default=None, pattern=_SHA256)
[docs] class BuildUndoRequest(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/build", tags=["periodic build review"] ) 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, {"code": "build.stale_revision", "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 build_preview(identifier: str, request: BuildPreviewRequest) -> dict[str, Any]: """Summary, coded refusals, notices and digests of a build; the document is unchanged.""" from vibesketcher.document.build_review import preview_build from vibesketcher.document.solid_build import parse_recipe entry = entry_or_404(identifier) try: recipe = parse_recipe(request.recipe) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None return preview_build(entry.document, recipe, structure=request.structure) @routes.post("/apply") def build_apply(identifier: str, request: BuildApplyRequest) -> DocumentResponse: """Add a previewed build; refused when the revision, recipe or inputs moved.""" from vibesketcher.document.build_review import BuildReviewRefused, apply_build from vibesketcher.document.solid_build import parse_recipe entry = entry_or_404(identifier) check(entry, request.revision) try: recipe = parse_recipe(request.recipe) document = apply_build( entry.document, recipe, recipe_sha256=request.recipe_sha256, revision=request.revision, inputs_sha256=request.inputs_sha256, ) except ValidationError as error: raise HTTPException(422, {"errors": _errors(error)}) from None except BuildReviewRefused as error: raise HTTPException(422, {"errors": [str(error)], "code": error.code}) from None response: DocumentResponse = commit( entry, document, request, f"Built periodic {recipe.kind} {recipe.identifier}" ) return response @routes.post("/undo") def build_undo(identifier: str, request: BuildUndoRequest) -> DocumentResponse: """Remove a reviewed build again while it is unchanged and unused.""" from vibesketcher.document.build_review import BuildReviewRefused, undo_build entry = entry_or_404(identifier) check(entry, request.revision) try: document = undo_build(entry.document, request.structure) except BuildReviewRefused as error: raise HTTPException(409, {"errors": [str(error)], "code": error.code}) from None response: DocumentResponse = commit( entry, document, request, f"Undid the build of {request.structure}" ) return response return routes