askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_source.py · 8.2 KB · 251 lines
| 1 | """Source file operations for DBBASIC objects. |
| 2 | |
| 3 | This module connects object ID resolution with source version storage. It does |
| 4 | not reload runtime objects or enforce HTTP permissions; those belong in the |
| 5 | server/runtime layers that call this code. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import ast |
| 11 | from pathlib import Path |
| 12 | from typing import Iterable |
| 13 | |
| 14 | HTTP_METHOD_NAMES = ("GET", "POST", "PUT", "DELETE") |
| 15 | |
| 16 | from object_namespace import ( |
| 17 | get_object_roots, |
| 18 | object_id_from_path, |
| 19 | parse_user_object_id, |
| 20 | resolve_object_id, |
| 21 | validate_object_id, |
| 22 | ) |
| 23 | import object_user_quotas |
| 24 | from object_versions import InvalidObjectIdError, VersionManager, VersionNotFoundError |
| 25 | |
| 26 | |
| 27 | class ObjectSourceError(Exception): |
| 28 | """Base exception for object source operations.""" |
| 29 | |
| 30 | |
| 31 | class ObjectSourceNotFoundError(ObjectSourceError): |
| 32 | """Raised when an object ID does not resolve to a source file.""" |
| 33 | |
| 34 | |
| 35 | class ObjectQuotaExceededError(ObjectSourceError): |
| 36 | """A user already owns as many objects as the quota allows.""" |
| 37 | |
| 38 | |
| 39 | class ObjectSourceExistsError(ObjectSourceError): |
| 40 | """Raised when an object source already exists.""" |
| 41 | |
| 42 | |
| 43 | def get_object_source(object_id: str, roots: Iterable[Path] | None = None) -> str: |
| 44 | """Read source text for an existing object.""" |
| 45 | source_path = _resolve_existing_source(object_id, roots) |
| 46 | return source_path.read_text() |
| 47 | |
| 48 | |
| 49 | def source_method_report(code: str) -> tuple[list[str], list[str]]: |
| 50 | """Return (executable HTTP methods, authoring warnings) for object source. |
| 51 | |
| 52 | Detection is static (AST), so it runs safely at write time and lets the |
| 53 | create/update responses tell authors — human or AI — that a saved object |
| 54 | cannot execute, instead of leaving that discovery to the first request. |
| 55 | """ |
| 56 | try: |
| 57 | tree = ast.parse(code) |
| 58 | except SyntaxError as exc: |
| 59 | return [], [f"Source has a Python syntax error: {exc.msg} (line {exc.lineno})"] |
| 60 | |
| 61 | methods = sorted( |
| 62 | { |
| 63 | node.name |
| 64 | for node in tree.body |
| 65 | if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) |
| 66 | and node.name in HTTP_METHOD_NAMES |
| 67 | } |
| 68 | ) |
| 69 | if not methods: |
| 70 | return [], [ |
| 71 | "Source defines no HTTP methods; the object cannot execute. " |
| 72 | "Define GET(request), POST(request), PUT(request), or DELETE(request) " |
| 73 | "at module top level (see docs/object-authoring.md)." |
| 74 | ] |
| 75 | return methods, [] |
| 76 | |
| 77 | |
| 78 | def create_object_source( |
| 79 | object_id: str, |
| 80 | code: str, |
| 81 | author: str, |
| 82 | message: str, |
| 83 | roots: Iterable[Path] | None = None, |
| 84 | version_manager: VersionManager | None = None, |
| 85 | correlation_id: str | None = None, |
| 86 | ) -> int: |
| 87 | """Create a new source file, save its first version, and return its version ID.""" |
| 88 | source_path = _resolve_new_source_path(object_id, roots) |
| 89 | _check_user_object_quota(object_id, roots) |
| 90 | manager = version_manager or VersionManager() |
| 91 | |
| 92 | version_id = manager.save_version( |
| 93 | object_id=object_id, |
| 94 | content=code, |
| 95 | author=author, |
| 96 | message=message, |
| 97 | correlation_id=correlation_id, |
| 98 | ) |
| 99 | source_path.parent.mkdir(parents=True, exist_ok=True) |
| 100 | _write_source(source_path, code) |
| 101 | return version_id |
| 102 | |
| 103 | |
| 104 | def update_object_source( |
| 105 | object_id: str, |
| 106 | new_code: str, |
| 107 | author: str, |
| 108 | message: str, |
| 109 | roots: Iterable[Path] | None = None, |
| 110 | version_manager: VersionManager | None = None, |
| 111 | correlation_id: str | None = None, |
| 112 | ) -> int: |
| 113 | """Save a new source version and write it to the object file.""" |
| 114 | source_path = _resolve_existing_source(object_id, roots) |
| 115 | manager = version_manager or VersionManager() |
| 116 | |
| 117 | version_id = manager.save_version( |
| 118 | object_id=object_id, |
| 119 | content=new_code, |
| 120 | author=author, |
| 121 | message=message, |
| 122 | correlation_id=correlation_id, |
| 123 | ) |
| 124 | _write_source(source_path, new_code) |
| 125 | return version_id |
| 126 | |
| 127 | |
| 128 | def rollback_object_source( |
| 129 | object_id: str, |
| 130 | to_version: int, |
| 131 | author: str, |
| 132 | message: str, |
| 133 | roots: Iterable[Path] | None = None, |
| 134 | version_manager: VersionManager | None = None, |
| 135 | correlation_id: str | None = None, |
| 136 | ) -> int: |
| 137 | """Rollback source by creating a new version and writing its content.""" |
| 138 | source_path = _resolve_existing_source(object_id, roots) |
| 139 | manager = version_manager or VersionManager() |
| 140 | |
| 141 | new_version_id = manager.rollback( |
| 142 | object_id=object_id, |
| 143 | to_version=to_version, |
| 144 | author=author, |
| 145 | message=message, |
| 146 | correlation_id=correlation_id, |
| 147 | ) |
| 148 | new_version = manager.get_version(object_id, new_version_id) |
| 149 | if new_version is None: |
| 150 | raise VersionNotFoundError(f"Version {new_version_id} not found for object {object_id}") |
| 151 | |
| 152 | _write_source(source_path, new_version["content"]) |
| 153 | return new_version_id |
| 154 | |
| 155 | |
| 156 | def destroy_object_source( |
| 157 | object_id: str, |
| 158 | roots: Iterable[Path] | None = None, |
| 159 | version_manager: VersionManager | None = None, |
| 160 | author: str = "api", |
| 161 | message: str = "Destroyed via API", |
| 162 | correlation_id: str | None = None, |
| 163 | ) -> int: |
| 164 | """Remove an object's source file, keeping its versions, and return the last version ID. |
| 165 | |
| 166 | The current file content is saved as a version first when no version holds |
| 167 | it, so the destroyed object can always be restored from history. State and |
| 168 | logs are left alone: recreating the object picks them up again. |
| 169 | """ |
| 170 | source_path = _resolve_existing_source(object_id, roots) |
| 171 | manager = version_manager or VersionManager() |
| 172 | |
| 173 | current = source_path.read_text() |
| 174 | latest = manager.get_version(object_id) |
| 175 | if latest is None or latest["content"] != current: |
| 176 | version_id = manager.save_version( |
| 177 | object_id=object_id, |
| 178 | content=current, |
| 179 | author=author, |
| 180 | message=message, |
| 181 | correlation_id=correlation_id, |
| 182 | ) |
| 183 | else: |
| 184 | version_id = int(latest["version_id"]) |
| 185 | |
| 186 | source_path.unlink() |
| 187 | return version_id |
| 188 | |
| 189 | |
| 190 | def _resolve_existing_source(object_id: str, roots: Iterable[Path] | None) -> Path: |
| 191 | if not validate_object_id(object_id): |
| 192 | raise InvalidObjectIdError(f"Invalid object ID: {object_id}") |
| 193 | |
| 194 | source_path = resolve_object_id(object_id, roots=roots) |
| 195 | if source_path is None: |
| 196 | raise ObjectSourceNotFoundError(f"Object source not found: {object_id}") |
| 197 | return source_path |
| 198 | |
| 199 | |
| 200 | def _check_user_object_quota(object_id: str, roots: Iterable[Path] | None) -> None: |
| 201 | parsed = parse_user_object_id(object_id) |
| 202 | if parsed is None: |
| 203 | return |
| 204 | search_roots = list(roots) if roots is not None else get_object_roots() |
| 205 | names = set() |
| 206 | for root in search_roots: |
| 207 | user_dir = Path(root) / "users" / str(parsed[0]) |
| 208 | if user_dir.is_dir(): |
| 209 | names.update(p.name for p in user_dir.glob("*.py")) |
| 210 | try: |
| 211 | object_user_quotas.check_object_count(parsed[0], len(names)) |
| 212 | except object_user_quotas.UserQuotaExceededError as exc: |
| 213 | raise ObjectQuotaExceededError(str(exc)) from exc |
| 214 | |
| 215 | |
| 216 | def _resolve_new_source_path(object_id: str, roots: Iterable[Path] | None) -> Path: |
| 217 | if not validate_object_id(object_id): |
| 218 | raise InvalidObjectIdError(f"Invalid object ID: {object_id}") |
| 219 | |
| 220 | search_roots = list(roots) if roots is not None else get_object_roots() |
| 221 | if not search_roots: |
| 222 | raise InvalidObjectIdError("No object source root configured") |
| 223 | |
| 224 | if resolve_object_id(object_id, roots=search_roots) is not None: |
| 225 | raise ObjectSourceExistsError(f"Object source already exists: {object_id}") |
| 226 | |
| 227 | root = search_roots[0] |
| 228 | parsed_user = parse_user_object_id(object_id) |
| 229 | if parsed_user: |
| 230 | user_id, name = parsed_user |
| 231 | source_path = root / "users" / str(user_id) / f"{name}.py" |
| 232 | elif "_" in object_id: |
| 233 | category, name = object_id.split("_", 1) |
| 234 | source_path = root / category / f"{name}.py" |
| 235 | else: |
| 236 | source_path = root / f"{object_id}.py" |
| 237 | |
| 238 | try: |
| 239 | derived_object_id = object_id_from_path(source_path, root) |
| 240 | except ValueError as exc: |
| 241 | raise InvalidObjectIdError(f"Invalid object ID: {object_id}") |
| 242 | if derived_object_id != object_id: |
| 243 | raise InvalidObjectIdError(f"Invalid object ID: {object_id}") |
| 244 | |
| 245 | return source_path |
| 246 | |
| 247 | |
| 248 | def _write_source(source_path: Path, content: str) -> None: |
| 249 | temp_path = source_path.with_name(f".{source_path.name}.tmp") |
| 250 | temp_path.write_text(content) |
| 251 | temp_path.replace(source_path) |