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.
python_object_runtime.py · 6.4 KB · 167 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 | sandbox: it runs admin/system/package objects only. User-namespace objects |
| 6 | (``u_<uid>_*``) are refused here and run through ``object_sandbox``. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import os |
| 12 | import re |
| 13 | import traceback |
| 14 | from pathlib import Path |
| 15 | from types import ModuleType |
| 16 | from typing import Any |
| 17 | |
| 18 | import object_logs |
| 19 | import object_runtime_helpers |
| 20 | import object_schedule |
| 21 | import object_state |
| 22 | from object_versions import DEFAULT_DATA_DIR |
| 23 | |
| 24 | |
| 25 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 26 | |
| 27 | |
| 28 | class PythonObjectRuntimeError(Exception): |
| 29 | """Base exception for the minimal Python object runtime.""" |
| 30 | |
| 31 | |
| 32 | class ObjectLoadError(PythonObjectRuntimeError): |
| 33 | """Raised when an object source file cannot be loaded.""" |
| 34 | |
| 35 | |
| 36 | class MethodNotSupportedError(PythonObjectRuntimeError): |
| 37 | """Raised when an object does not expose the requested method.""" |
| 38 | |
| 39 | |
| 40 | class ObjectMethodExecutionError(PythonObjectRuntimeError): |
| 41 | """Raised when an object method fails.""" |
| 42 | |
| 43 | |
| 44 | class PythonObjectRuntime: |
| 45 | """Load Python object files for direct execution.""" |
| 46 | |
| 47 | def __init__(self, base_dir: Path | str | None = None): |
| 48 | self.base_dir = Path(base_dir) if base_dir is not None else None |
| 49 | |
| 50 | def load_object(self, path: Path, object_id: str | None = None) -> "PythonObject": |
| 51 | return PythonObject(path=path, object_id=object_id, base_dir=self._base_dir()) |
| 52 | |
| 53 | def _base_dir(self) -> Path: |
| 54 | if self.base_dir is not None: |
| 55 | return self.base_dir |
| 56 | return Path(os.environ.get(DATA_DIR_ENV, DEFAULT_DATA_DIR)) |
| 57 | |
| 58 | |
| 59 | class PythonObject: |
| 60 | """Executable wrapper around a loaded Python object module.""" |
| 61 | |
| 62 | def __init__(self, path: Path, object_id: str | None = None, base_dir: Path | str = DEFAULT_DATA_DIR): |
| 63 | self.path = Path(path) |
| 64 | self.object_id = object_id or self.path.stem |
| 65 | import object_sandbox # lazy: object_sandbox imports this module's callers |
| 66 | |
| 67 | if object_sandbox.is_user_code(self.object_id, self.path): |
| 68 | # Fail closed: every caller that can reach a user object routes it |
| 69 | # to object_sandbox first; anything that still gets here (a new |
| 70 | # call site, a hand-built path) is refused, never run in-process. |
| 71 | raise ObjectLoadError( |
| 72 | f"User object {self.object_id} runs only in the user-code sandbox, " |
| 73 | "never in the server process (docs/runtime-contract.md \"User Object Isolation\")." |
| 74 | ) |
| 75 | self.state_manager = object_state.ObjectStateManager(self.object_id, base_dir=base_dir) |
| 76 | self.logger = object_logs.ObjectLogger(self.object_id, base_dir=base_dir) |
| 77 | self.file_manager = object_runtime_helpers.ObjectFileStore(self.object_id, base_dir=base_dir) |
| 78 | self.composer = object_runtime_helpers.ObjectComposer(self.object_id, base_dir=base_dir) |
| 79 | self.module = _load_module(self.path, self.object_id) |
| 80 | self.module._logger = self.logger |
| 81 | self.module._state_manager = self.state_manager |
| 82 | self.module._files = self.file_manager |
| 83 | self.module._runtime = self.composer |
| 84 | self.module._schedule, self.module._unschedule = object_schedule.helpers( |
| 85 | self.object_id, self.module, base_dir |
| 86 | ) |
| 87 | |
| 88 | def execute(self, method: str, payload: dict[str, Any]) -> Any: |
| 89 | method_name = method.upper() |
| 90 | method_func = getattr(self.module, method_name, None) |
| 91 | |
| 92 | if not callable(method_func): |
| 93 | raise MethodNotSupportedError( |
| 94 | f"Method {method_name} not supported by object {self.object_id}. " |
| 95 | f"Available methods: {_available_methods(self.module)}" |
| 96 | ) |
| 97 | |
| 98 | try: |
| 99 | with object_runtime_helpers.execution_frame(self.object_id): |
| 100 | return method_func(payload) |
| 101 | except object_runtime_helpers.CompositionDepthError: |
| 102 | raise |
| 103 | except Exception as exc: |
| 104 | raise ObjectMethodExecutionError( |
| 105 | f"{method_name} failed for object {self.object_id}: " |
| 106 | f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}" |
| 107 | ) from exc |
| 108 | |
| 109 | |
| 110 | def execute_named(self, method: str, payload: dict[str, Any]) -> Any: |
| 111 | """Run a method scheduled by name (object_schedule): exactly that |
| 112 | function, never upper-cased, called with no arguments when its |
| 113 | signature allows. Only the daemon's scheduler pass calls this; HTTP |
| 114 | and composition reach only the verb methods through execute().""" |
| 115 | import object_sandbox |
| 116 | |
| 117 | if not isinstance(method, str) or not object_sandbox.SCHEDULED_METHOD_RE.fullmatch(method): |
| 118 | raise MethodNotSupportedError(f"{method!r} is not a schedulable method name") |
| 119 | method_func = getattr(self.module, method, None) |
| 120 | if not callable(method_func): |
| 121 | raise MethodNotSupportedError( |
| 122 | f"Method {method} not found in object {self.object_id}" |
| 123 | ) |
| 124 | try: |
| 125 | with object_runtime_helpers.execution_frame(self.object_id): |
| 126 | return object_sandbox.call_scheduled(method_func, payload) |
| 127 | except object_runtime_helpers.CompositionDepthError: |
| 128 | raise |
| 129 | except Exception as exc: |
| 130 | raise ObjectMethodExecutionError( |
| 131 | f"{method} failed for object {self.object_id}: " |
| 132 | f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}" |
| 133 | ) from exc |
| 134 | |
| 135 | |
| 136 | def _load_module(path: Path, object_id: str) -> ModuleType: |
| 137 | if not path.exists() or not path.is_file(): |
| 138 | raise ObjectLoadError(f"Object source not found: {path}") |
| 139 | |
| 140 | module_name = f"_dbbasic_object_{_safe_module_part(object_id)}" |
| 141 | module = ModuleType(module_name) |
| 142 | module.__file__ = str(path) |
| 143 | module.__package__ = "" |
| 144 | |
| 145 | try: |
| 146 | source = path.read_text() |
| 147 | code = compile(source, str(path), "exec") |
| 148 | exec(code, module.__dict__) |
| 149 | except Exception as exc: |
| 150 | raise ObjectLoadError( |
| 151 | f"Failed to load object {object_id} from {path}: " |
| 152 | f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}" |
| 153 | ) from exc |
| 154 | |
| 155 | return module |
| 156 | |
| 157 | |
| 158 | def _available_methods(module: ModuleType) -> list[str]: |
| 159 | methods = [] |
| 160 | for name in ["GET", "POST", "PUT", "DELETE"]: |
| 161 | if callable(getattr(module, name, None)): |
| 162 | methods.append(name) |
| 163 | return methods |
| 164 | |
| 165 | |
| 166 | def _safe_module_part(value: str) -> str: |
| 167 | return re.sub(r"[^A-Za-z0-9_]", "_", value) |