|
| 1 | +"""generic api (load-balanced) server for app endpoints. |
| 2 | +
|
| 3 | +serves an asgi app on the port runpod's load balancer routes to |
| 4 | +(PORT env, default 80), with /ping kept healthy for LB health checks. |
| 5 | +
|
| 6 | +two serving modes, chosen at startup: |
| 7 | +
|
| 8 | +deployed mode (rp deploy): |
| 9 | + the build artifact is unpacked at RUNPOD_APP_DIR and |
| 10 | + FLASH_RESOURCE_NAME identifies this resource. the server imports |
| 11 | + the user's module, finds the ApiHandle, and builds the asgi app: |
| 12 | + - class-based api: instantiate the class, run its @init method |
| 13 | + before /ping reports healthy, mount each @get/@post route |
| 14 | + - asgi factory: call the factory, serve what it returns |
| 15 | +
|
| 16 | +live mode (rp dev): |
| 17 | + no artifact. serves /execute, which runs FunctionRequest payloads |
| 18 | + (source per request) via the task runner's execute_request. |
| 19 | +""" |
| 20 | + |
| 21 | +import importlib |
| 22 | +import inspect |
| 23 | +import json |
| 24 | +import logging |
| 25 | +import os |
| 26 | +import sys |
| 27 | +from typing import Any, Optional |
| 28 | + |
| 29 | +log = logging.getLogger("runpod.runtimes.api") |
| 30 | + |
| 31 | +APP_DIR = os.environ.get("RUNPOD_APP_DIR", "/app") |
| 32 | +MANIFEST_NAME = "runpod_manifest.json" |
| 33 | +PORT = int(os.environ.get("PORT", "80")) |
| 34 | + |
| 35 | + |
| 36 | +def _resource_name() -> str: |
| 37 | + return os.environ.get("FLASH_RESOURCE_NAME") or os.environ.get( |
| 38 | + "RUNPOD_RESOURCE_NAME", "" |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +def _is_deployed() -> bool: |
| 43 | + return bool(_resource_name()) and os.path.isfile( |
| 44 | + os.path.join(APP_DIR, MANIFEST_NAME) |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def _load_api_handle(): |
| 49 | + """import the user's module and return the ApiHandle for this resource.""" |
| 50 | + with open(os.path.join(APP_DIR, MANIFEST_NAME)) as f: |
| 51 | + manifest = json.load(f) |
| 52 | + |
| 53 | + name = _resource_name() |
| 54 | + entry = next( |
| 55 | + (r for r in manifest.get("resources", []) if r.get("name") == name), |
| 56 | + None, |
| 57 | + ) |
| 58 | + if entry is None: |
| 59 | + raise RuntimeError( |
| 60 | + f"resource '{name}' not in manifest " |
| 61 | + f"(has: {[r.get('name') for r in manifest.get('resources', [])]})" |
| 62 | + ) |
| 63 | + |
| 64 | + if APP_DIR not in sys.path: |
| 65 | + sys.path.insert(0, APP_DIR) |
| 66 | + module = importlib.import_module(entry["module"]) |
| 67 | + |
| 68 | + from runpod.apps.handles import ApiHandle |
| 69 | + |
| 70 | + for attr in vars(module).values(): |
| 71 | + if isinstance(attr, ApiHandle) and attr.spec.name == name: |
| 72 | + return attr |
| 73 | + raise RuntimeError( |
| 74 | + f"no @app.api handle named '{name}' found in module '{entry['module']}'" |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +async def _maybe_await(value: Any) -> Any: |
| 79 | + if inspect.isawaitable(value): |
| 80 | + return await value |
| 81 | + return value |
| 82 | + |
| 83 | + |
| 84 | +def _build_class_app(handle) -> Any: |
| 85 | + """construct a fastapi app from an ApiHandle's decorated class. |
| 86 | +
|
| 87 | + the class is instantiated once per worker; @init runs before /ping |
| 88 | + reports healthy so the LB only routes to ready workers. |
| 89 | + """ |
| 90 | + from contextlib import asynccontextmanager |
| 91 | + |
| 92 | + from fastapi import FastAPI, Request |
| 93 | + |
| 94 | + cls = handle._cls |
| 95 | + instance = cls() |
| 96 | + ready = {"ok": False} |
| 97 | + |
| 98 | + @asynccontextmanager |
| 99 | + async def lifespan(_app): |
| 100 | + if handle._init_name: |
| 101 | + await _maybe_await(getattr(instance, handle._init_name)()) |
| 102 | + ready["ok"] = True |
| 103 | + yield |
| 104 | + |
| 105 | + app = FastAPI(title=handle.spec.name, lifespan=lifespan) |
| 106 | + |
| 107 | + @app.get("/ping") |
| 108 | + async def ping(): |
| 109 | + from fastapi.responses import JSONResponse |
| 110 | + |
| 111 | + if not ready["ok"]: |
| 112 | + return JSONResponse({"status": "initializing"}, status_code=204) |
| 113 | + return {"status": "healthy"} |
| 114 | + |
| 115 | + for route in handle.spec.routes: |
| 116 | + method = getattr(route, "method", None) or route["method"] |
| 117 | + path = getattr(route, "path", None) or route["path"] |
| 118 | + handler_name = ( |
| 119 | + getattr(route, "handler_name", None) or route["handler"] |
| 120 | + ) |
| 121 | + bound = getattr(instance, handler_name) |
| 122 | + |
| 123 | + def make_endpoint(fn): |
| 124 | + async def endpoint(request: Request): |
| 125 | + body = None |
| 126 | + if request.method in ("POST", "PUT", "PATCH", "DELETE"): |
| 127 | + try: |
| 128 | + body = await request.json() |
| 129 | + except Exception: # noqa: BLE001 - empty/non-json body |
| 130 | + body = None |
| 131 | + if body is not None: |
| 132 | + return await _maybe_await(fn(body)) |
| 133 | + return await _maybe_await(fn()) |
| 134 | + |
| 135 | + return endpoint |
| 136 | + |
| 137 | + app.add_api_route( |
| 138 | + path, make_endpoint(bound), methods=[method], name=handler_name |
| 139 | + ) |
| 140 | + |
| 141 | + return app |
| 142 | + |
| 143 | + |
| 144 | +def _build_factory_app(handle) -> Any: |
| 145 | + """call the user's asgi factory and ensure /ping exists.""" |
| 146 | + app = handle._asgi_factory() |
| 147 | + |
| 148 | + routes = getattr(app, "routes", []) |
| 149 | + if not any(getattr(r, "path", None) == "/ping" for r in routes): |
| 150 | + |
| 151 | + @app.get("/ping") |
| 152 | + async def ping(): |
| 153 | + return {"status": "healthy"} |
| 154 | + |
| 155 | + return app |
| 156 | + |
| 157 | + |
| 158 | +def _build_live_app() -> Any: |
| 159 | + """generic /execute server for dev sessions (source per request).""" |
| 160 | + from fastapi import FastAPI |
| 161 | + |
| 162 | + app = FastAPI(title="runpod-live-api") |
| 163 | + |
| 164 | + @app.get("/ping") |
| 165 | + async def ping(): |
| 166 | + return {"status": "healthy"} |
| 167 | + |
| 168 | + @app.post("/execute") |
| 169 | + async def execute(request: dict): |
| 170 | + from runpod.runtimes.task.runner import execute_request |
| 171 | + |
| 172 | + return execute_request(request.get("input", request)) |
| 173 | + |
| 174 | + return app |
| 175 | + |
| 176 | + |
| 177 | +def build_app() -> Any: |
| 178 | + if _is_deployed(): |
| 179 | + handle = _load_api_handle() |
| 180 | + if handle._cls is not None: |
| 181 | + return _build_class_app(handle) |
| 182 | + return _build_factory_app(handle) |
| 183 | + return _build_live_app() |
| 184 | + |
| 185 | + |
| 186 | +def main() -> None: |
| 187 | + import uvicorn |
| 188 | + |
| 189 | + uvicorn.run( |
| 190 | + build_app(), |
| 191 | + host="0.0.0.0", |
| 192 | + port=PORT, |
| 193 | + timeout_keep_alive=600, |
| 194 | + log_level="info", |
| 195 | + ) |
| 196 | + |
| 197 | + |
| 198 | +if __name__ == "__main__": |
| 199 | + main() |
0 commit comments