vibe-sketcherDocumentation

Source code for vibesketcher.document.draft_session

"""Atomic review receipts and complete-document undo for a live document store."""

from __future__ import annotations

import copy
import secrets
import time
from dataclasses import dataclass, field
from typing import Any, Literal

from vibesketcher.document.drafts import DraftConflict, DraftRefused, digest, encoded, prepare
from vibesketcher.document.io import with_edit
from vibesketcher.document.model import Document
from vibesketcher.server.store import NotFound, Store

Action = Literal["apply", "undo", "redo"]


[docs] @dataclass class Receipt: document: str source: Document candidate: Document review: dict[str, Any] expires: float size: int phase: str = "review" expected: str = "" retries: dict[str, tuple[str, dict[str, Any]]] = field(default_factory=dict)
[docs] class DraftSession: """Session-local SDK service; pass the server Store to share its atomic lock. Receipts expire after 30 minutes, on document close or on process restart. No live receipt is evicted to make room for another one. """ def __init__(self, store: Store | None = None) -> None: self.store = store if store is not None else Store() self._receipts: dict[str, Receipt] = {} def _prune(self) -> None: now = time.monotonic() self._receipts = { k: v for k, v in self._receipts.items() if v.expires > now and v.document in self.store._entries }
[docs] def review( self, identifier: str, proposal: dict[str, Any], *, revision: int, source_digest: str ) -> dict[str, Any]: with self.store._lock: entry = self.store._entries.get(identifier) if entry is None: raise NotFound(identifier) source = entry.document.model_copy(deep=True) if source.revision != revision or digest(source) != source_digest: raise DraftConflict("The proposal source changed; review again.") review = prepare(source, proposal) candidate = Document.model_validate(review["candidate"]) size = ( len(encoded(review)) + len(encoded(source.model_dump(mode="json"))) + len(encoded(candidate.model_dump(mode="json"))) ) with self.store._lock: self._prune() current = self.store._entries.get(identifier) if current is None or digest(current.document) != source_digest: raise DraftConflict("The proposal source changed during preparation.") if ( len(self._receipts) >= 64 or sum(r.size for r in self._receipts.values()) + size > 128 * 2**20 ): raise DraftRefused( "Draft receipt capacity exhausted; discard an unused review or wait for expiry." ) token = secrets.token_urlsafe(24) review["receipt"] = token review["expires_in_seconds"] = 1800 self._receipts[token] = Receipt( identifier, source, candidate, copy.deepcopy(review), time.monotonic() + 1800, size, expected=digest(source), ) return review
[docs] def inspect(self, identifier: str, token: str) -> dict[str, Any]: with self.store._lock: receipt = self._get(identifier, token) return { **copy.deepcopy(receipt.review), "phase": receipt.phase, "expires_in_seconds": max(0, int(receipt.expires - time.monotonic())), }
def _get(self, identifier: str, token: str) -> Receipt: self._prune() item = self._receipts.get(token) if item is None or item.document != identifier: raise DraftConflict( "Review receipt is missing, expired or belongs to another document." ) return item
[docs] def discard(self, identifier: str, token: str) -> None: with self.store._lock: item = self._get(identifier, token) if item.phase != "review": raise DraftRefused("Applied receipts back undo history and remain until expiry.") del self._receipts[token]
[docs] def transact( self, identifier: str, token: str, action: Action, *, key: str, revision: int, source_digest: str, client: str = "sdk", actor: Literal["human", "agent"] = "agent", ) -> dict[str, Any]: if not key or len(key) > 128: raise DraftRefused("Use an idempotency key of 1 to 128 characters.") request = encoded( [identifier, token, action, revision, source_digest, client, actor] ).decode() with self.store._lock: receipt = self._get(identifier, token) if any( other.document == identifier and other is not receipt and key in other.retries for other in self._receipts.values() ): raise DraftConflict("Idempotency key was used for another review.") if key in receipt.retries: previous, answer = receipt.retries[key] if previous != request: raise DraftConflict("Idempotency key was used for different content.") return {**answer, "replayed": True} if len(receipt.retries) >= 128: raise DraftRefused("Transaction receipt reached its 128-operation limit.") allowed = {"apply": "review", "undo": "applied", "redo": "undone"} if action not in allowed or receipt.phase != allowed[action]: raise DraftConflict( "This transaction is not available in the receipt's current state." ) entry = self.store._entries[identifier] current = entry.document if current.revision != revision or digest(current) != source_digest: raise DraftConflict("The document changed; the transaction was not applied.") if digest(current, content=action != "apply") != receipt.expected: raise DraftConflict("Document content changed outside this transaction.") saved = receipt.source if action == "undo" else receipt.candidate restored = saved.model_copy(deep=True) restored.revision = current.revision restored.provenance = current.provenance.model_copy(deep=True) restored = with_edit( restored, actor=actor, client=client, summary=f"{action.capitalize()} reviewed drawing revision {current.revision + 1}", ) restored.revision += 1 entry.document = restored entry.warnings = list(receipt.review["warnings"]) if action != "undo" else [] receipt.phase = "undone" if action == "undo" else "applied" receipt.expected = digest(restored, content=True) answer = { "receipt": token, "action": action, "applied_revision": restored.revision, "applied_digest": digest(restored), "replayed": False, } receipt.retries[key] = request, answer return dict(answer)