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.
runtime_modes.py · 1.9 KB · 53 lines
| 1 | """Run one object method in each execution mode: in-process, warm pool, spawn.""" |
| 2 | import asyncio |
| 3 | |
| 4 | import object_execution |
| 5 | import object_worker_pool |
| 6 | from object_execution import ObjectExecutionRequest |
| 7 | from python_object_runtime import PythonObjectRuntime |
| 8 | |
| 9 | MODES = ["in_process", "pool", "spawn"] |
| 10 | |
| 11 | |
| 12 | def configure(monkeypatch, tmp_path): |
| 13 | data_dir = tmp_path / "data" |
| 14 | root = tmp_path / "objects" |
| 15 | root.mkdir(parents=True, exist_ok=True) |
| 16 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 17 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root)) |
| 18 | monkeypatch.delenv("DBBASIC_OVERRIDES_DIR", raising=False) |
| 19 | monkeypatch.delenv("DBBASIC_MAX_OBJECT_FILE_BYTES", raising=False) |
| 20 | return data_dir, root |
| 21 | |
| 22 | |
| 23 | def write_object(root, object_id, source): |
| 24 | """Write an object source where resolve_object_id will find it.""" |
| 25 | if object_id.startswith("u_"): |
| 26 | _, uid, name = object_id.split("_", 2) |
| 27 | path = root / "users" / uid / f"{name}.py" |
| 28 | else: |
| 29 | category, _, name = object_id.partition("_") |
| 30 | path = root / category / f"{name}.py" if name else root / f"{object_id}.py" |
| 31 | path.parent.mkdir(parents=True, exist_ok=True) |
| 32 | path.write_text(source) |
| 33 | return path |
| 34 | |
| 35 | |
| 36 | def run_object(mode, root, object_id, method="GET", payload=None): |
| 37 | """Return the ObjectExecutionResult for one call in the given mode.""" |
| 38 | request = ObjectExecutionRequest(object_id, method=method, payload=payload or {}) |
| 39 | if mode == "in_process": |
| 40 | return object_execution.execute_object(PythonObjectRuntime(), request, [root]) |
| 41 | if mode == "spawn": |
| 42 | return object_execution.execute_python_object_subprocess( |
| 43 | request, [root], timeout_seconds=60 |
| 44 | ) |
| 45 | |
| 46 | async def scenario(): |
| 47 | pool = object_worker_pool.WorkerPool(size=1) |
| 48 | try: |
| 49 | return await pool.execute(request, timeout_seconds=60, roots=[root]) |
| 50 | finally: |
| 51 | await pool.shutdown() |
| 52 | |
| 53 | return asyncio.run(scenario()) |