Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
185 lines (161 loc) · 6.96 KB
/
Copy pathmain.py
File metadata and controls
185 lines (161 loc) · 6.96 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""FastAPI application factory.
Wires routers, CORS, static UI, and the controller singleton. Run
with ``uvicorn app.main:app`` — the minimal chat UI is served at ``/``.
"""
from __future__ import annotations
import asyncio
import contextlib
import time
import uuid
import warnings
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from .controllers.errors import DomainError
from .controllers.manager import Controller, get_controller
from .infra.config import get_settings
from .infra.db import get_engine
from .infra.logging import configure_logging, get_logger, reset_request_id, set_request_id
from .infra.metrics import get_registry, normalize_method
from .routes import account, auth, billing, conversations, secrets
_log = get_logger("request")
@asynccontextmanager
async def lifespan(app: FastAPI):
get_engine() # migrate schema to head
controller = get_controller()
controller.reconcile_orphaned_runs() # fail runs stranded by a restart
controller.reconcile_orphaned_sandboxes() # retire this instance's dead sandbox rows
controller.reap_idle_sandboxes()
reaper = asyncio.create_task(_reap_idle_sandboxes_forever(controller))
try:
yield
finally:
reaper.cancel()
with contextlib.suppress(asyncio.CancelledError):
await reaper
# graceful shutdown: stop taking new runs and let in-flight ones
# finish (bounded), so a deploy does not kill short runs mid-flight.
# Whatever does not finish in time is reconciled on the next start.
controller.drain(timeout=get_settings().shutdown_drain_seconds)
async def _reap_idle_sandboxes_forever(controller: Controller) -> None:
"""Sweep idle sandboxes on a timer for the life of the process.
The startup call alone could never reclaim anything: sandboxes live
in the runner's in-memory registry, so at startup it is empty and
the sweep is a guaranteed no-op — ``PAW_SANDBOX__TTL_SECONDS`` was
documented but never applied to a single sandbox, and idle ones
leaked until the process exited.
The sweep skips any sandbox with a live run (enforced in
``Runner.reap_idle``), so it cannot shorten a run however long that
run takes. Runs on a thread because reaping blocks on process
teardown and the DB.
"""
interval = get_settings().sandbox.reap_interval_seconds
if interval <= 0:
return
while True:
await asyncio.sleep(interval)
try:
destroyed = await asyncio.to_thread(controller.reap_idle_sandboxes)
except Exception: # noqa: BLE001 - the sweep must survive a bad pass
_log.warning("idle sandbox reaper failed", exc_info=True)
continue
if destroyed:
_log.info("reaped %d idle sandbox(es)", len(destroyed))
def create_app() -> FastAPI:
settings = get_settings()
configure_logging(settings.log_level, settings.log_json)
if settings.secret_key == "dev-only-insecure-key-change-me":
warnings.warn(
"PAW_SECRET_KEY is unset — using the insecure dev default; "
"set it before any real deployment.",
stacklevel=1,
)
app = FastAPI(title="python-agent-web", version="0.1.0", lifespan=lifespan)
@app.middleware("http")
async def _request_context(request: Request, call_next):
"""Bind a request id to logs, time the request, and capture any
unhandled error as a logged 500 that carries the id back to the
client (so a user can quote it in a bug report)."""
rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:16]
token = set_request_id(rid)
start = time.perf_counter()
try:
try:
response = await call_next(request)
except Exception:
_log.exception("%s %s unhandled error", request.method, request.url.path)
response = JSONResponse(
{"detail": "internal server error", "request_id": rid},
status_code=500,
)
dur_ms = (time.perf_counter() - start) * 1000
response.headers["X-Request-ID"] = rid
# metrics: count by method+status and record latency. The
# method is normalized to a bounded set so arbitrary/garbage
# verbs cannot create unbounded metric series.
registry = get_registry()
method = normalize_method(request.method)
registry.counter(
"paw_http_requests_total",
labels={"method": method, "status": str(response.status_code)},
help="HTTP requests by method and status.",
)
registry.observe(
"paw_http_request_duration_seconds",
dur_ms / 1000.0,
labels={"method": method},
help="HTTP request latency in seconds.",
)
_log.info(
"%s %s -> %s %.1fms",
request.method,
request.url.path,
response.status_code,
dur_ms,
)
return response
finally:
reset_request_id(token)
@app.exception_handler(DomainError)
def _domain_error(_request: Request, exc: DomainError) -> JSONResponse:
"""Render a controller's refusal in FastAPI's own error shape.
With this, routes never translate business rules into status
codes -- the controller names the failure, the status follows
from its type.
"""
headers = {}
retry_after = getattr(exc, "retry_after", None)
if retry_after is not None:
headers["Retry-After"] = str(retry_after)
return JSONResponse(
{"detail": exc.detail}, status_code=exc.status_code, headers=headers or None
)
app.include_router(auth.router)
app.include_router(account.router)
app.include_router(conversations.router)
app.include_router(billing.router)
app.include_router(secrets.router)
if settings.cors_origins:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/healthz")
def healthz() -> dict:
return {"ok": True, "runner": settings.runner}
@app.get("/metrics")
def metrics() -> Response:
"""Prometheus text exposition of process metrics (runs, tokens,
HTTP, span durations). Scrape target for a monitoring stack."""
return Response(get_registry().render(), media_type="text/plain; version=0.0.4")
static_dir = Path(__file__).parent / "views"
if static_dir.is_dir():
app.mount("/", StaticFiles(directory=static_dir, html=True), name="ui")
return app
app = create_app()