File size: 3,779 Bytes
b99b9ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""FastAPI app + ``physix-server`` console-script entry point.

Mounts the OpenEnv stateless endpoints (``/reset`` etc.) plus the bespoke
``/interactive/*`` router that maintains in-process sessions for browsers.
CORS allows the Vite dev origin out of the box; override with the
``PHYSIX_CORS_ORIGINS`` env var (comma-separated, or ``*`` for any).
"""

from __future__ import annotations

import argparse
import logging
import os

import uvicorn
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from openenv.core.env_server import create_fastapi_app
from starlette.exceptions import HTTPException as StarletteHTTPException

from physix.models import PhysiXAction, PhysiXObservation
from physix.server.environment import PhysiXEnvironment
from physix.server.interactive import build_interactive_router


_DEFAULT_CORS_ORIGINS = (
    "http://localhost:5173",
    "http://127.0.0.1:5173",
)


def build_app() -> FastAPI:
    app = create_fastapi_app(
        env=PhysiXEnvironment,
        action_cls=PhysiXAction,
        observation_cls=PhysiXObservation,
    )
    _install_cors(app)
    _install_error_handlers(app)
    app.include_router(build_interactive_router())
    return app


def _install_cors(app: FastAPI) -> None:
    raw = os.environ.get("PHYSIX_CORS_ORIGINS", "")
    origins = (
        [o.strip() for o in raw.split(",") if o.strip()]
        if raw
        else list(_DEFAULT_CORS_ORIGINS)
    )
    allow_all = origins == ["*"]
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins if not allow_all else ["*"],
        allow_credentials=not allow_all,
        allow_methods=["*"],
        allow_headers=["*"],
    )


def _install_error_handlers(app: FastAPI) -> None:
    """Make sure 4xx/5xx responses still carry the request's CORS headers.

    Starlette's ``CORSMiddleware`` only annotates responses produced by
    successful route handlers; raw ``HTTPException`` responses skip the
    middleware and reach the browser without ``Access-Control-Allow-Origin``,
    which the browser surfaces as a generic network error rather than the
    real status code (e.g. 502 "Ollama not reachable" was reported as 404
    in the dev UI). Re-emitting through ``JSONResponse`` runs the middleware.
    """

    @app.exception_handler(StarletteHTTPException)
    async def _http_exc(_request: Request, exc: StarletteHTTPException) -> JSONResponse:
        return JSONResponse(
            status_code=exc.status_code,
            content={"detail": exc.detail},
            headers=exc.headers,
        )

    @app.exception_handler(RequestValidationError)
    async def _validation_exc(
        _request: Request, exc: RequestValidationError
    ) -> JSONResponse:
        return JSONResponse(status_code=422, content={"detail": exc.errors()})


app: FastAPI = build_app()


def main() -> None:
    parser = argparse.ArgumentParser(description="Run the PhysiX-Live env server.")
    parser.add_argument("--host", default=os.environ.get("PHYSIX_HOST", "0.0.0.0"))
    parser.add_argument("--port", type=int, default=int(os.environ.get("PORT", "8000")))
    parser.add_argument(
        "--log-level", default=os.environ.get("PHYSIX_LOG_LEVEL", "info")
    )
    parser.add_argument(
        "--reload",
        action="store_true",
        help="Auto-reload on source changes. Use during development only.",
    )
    args = parser.parse_args()

    logging.basicConfig(level=args.log_level.upper())
    uvicorn.run(
        "physix.server.app:app",
        host=args.host,
        port=args.port,
        log_level=args.log_level,
        reload=args.reload,
    )


if __name__ == "__main__":
    main()