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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
python_object_runtime.py · 3.8 KB · 118 lines
| 1 | """Minimal Python object runtime adapter. |
| 2 | |
| 3 | This loader is intentionally small and direct so the public ASGI server can |
| 4 | execute simple objects while the hardened runtime is extracted. It is not a |
| 5 | production sandbox. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import os |
| 11 | import re |
| 12 | import traceback |
| 13 | from pathlib import Path |
| 14 | from types import ModuleType |
| 15 | from typing import Any |
| 16 | |
| 17 | import object_logs |
| 18 | import object_state |
| 19 | from object_versions import DEFAULT_DATA_DIR |
| 20 | |
| 21 | |
| 22 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 23 | |
| 24 | |
| 25 | class PythonObjectRuntimeError(Exception): |
| 26 | """Base exception for the minimal Python object runtime.""" |
| 27 | |
| 28 | |
| 29 | class ObjectLoadError(PythonObjectRuntimeError): |
| 30 | """Raised when an object source file cannot be loaded.""" |
| 31 | |
| 32 | |
| 33 | class MethodNotSupportedError(PythonObjectRuntimeError): |
| 34 | """Raised when an object does not expose the requested method.""" |
| 35 | |
| 36 | |
| 37 | class ObjectMethodExecutionError(PythonObjectRuntimeError): |
| 38 | """Raised when an object method fails.""" |
| 39 | |
| 40 | |
| 41 | class PythonObjectRuntime: |
| 42 | """Load Python object files for direct execution.""" |
| 43 | |
| 44 | def __init__(self, base_dir: Path | str | None = None): |
| 45 | self.base_dir = Path(base_dir) if base_dir is not None else None |
| 46 | |
| 47 | def load_object(self, path: Path, object_id: str | None = None) -> "PythonObject": |
| 48 | return PythonObject(path=path, object_id=object_id, base_dir=self._base_dir()) |
| 49 | |
| 50 | def _base_dir(self) -> Path: |
| 51 | if self.base_dir is not None: |
| 52 | return self.base_dir |
| 53 | return Path(os.environ.get(DATA_DIR_ENV, DEFAULT_DATA_DIR)) |
| 54 | |
| 55 | |
| 56 | class PythonObject: |
| 57 | """Executable wrapper around a loaded Python object module.""" |
| 58 | |
| 59 | def __init__(self, path: Path, object_id: str | None = None, base_dir: Path | str = DEFAULT_DATA_DIR): |
| 60 | self.path = Path(path) |
| 61 | self.object_id = object_id or self.path.stem |
| 62 | self.state_manager = object_state.ObjectStateManager(self.object_id, base_dir=base_dir) |
| 63 | self.logger = object_logs.ObjectLogger(self.object_id, base_dir=base_dir) |
| 64 | self.module = _load_module(self.path, self.object_id) |
| 65 | self.module._logger = self.logger |
| 66 | self.module._state_manager = self.state_manager |
| 67 | |
| 68 | def execute(self, method: str, payload: dict[str, Any]) -> Any: |
| 69 | method_name = method.upper() |
| 70 | method_func = getattr(self.module, method_name, None) |
| 71 | |
| 72 | if not callable(method_func): |
| 73 | raise MethodNotSupportedError( |
| 74 | f"Method {method_name} not supported by object {self.object_id}. " |
| 75 | f"Available methods: {_available_methods(self.module)}" |
| 76 | ) |
| 77 | |
| 78 | try: |
| 79 | return method_func(payload) |
| 80 | except Exception as exc: |
| 81 | raise ObjectMethodExecutionError( |
| 82 | f"{method_name} failed for object {self.object_id}: " |
| 83 | f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}" |
| 84 | ) from exc |
| 85 | |
| 86 | |
| 87 | def _load_module(path: Path, object_id: str) -> ModuleType: |
| 88 | if not path.exists() or not path.is_file(): |
| 89 | raise ObjectLoadError(f"Object source not found: {path}") |
| 90 | |
| 91 | module_name = f"_dbbasic_object_{_safe_module_part(object_id)}" |
| 92 | module = ModuleType(module_name) |
| 93 | module.__file__ = str(path) |
| 94 | module.__package__ = "" |
| 95 | |
| 96 | try: |
| 97 | source = path.read_text() |
| 98 | code = compile(source, str(path), "exec") |
| 99 | exec(code, module.__dict__) |
| 100 | except Exception as exc: |
| 101 | raise ObjectLoadError( |
| 102 | f"Failed to load object {object_id} from {path}: " |
| 103 | f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}" |
| 104 | ) from exc |
| 105 | |
| 106 | return module |
| 107 | |
| 108 | |
| 109 | def _available_methods(module: ModuleType) -> list[str]: |
| 110 | methods = [] |
| 111 | for name in ["GET", "POST", "PUT", "DELETE"]: |
| 112 | if callable(getattr(module, name, None)): |
| 113 | methods.append(name) |
| 114 | return methods |
| 115 | |
| 116 | |
| 117 | def _safe_module_part(value: str) -> str: |
| 118 | return re.sub(r"[^A-Za-z0-9_]", "_", value) |