Spaces:
Runtime error
Runtime error
Update app/main.py
Browse files- app/main.py +244 -239
app/main.py
CHANGED
|
@@ -1,239 +1,244 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import asyncio
|
| 4 |
-
import logging
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
from
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
from
|
| 11 |
-
from
|
| 12 |
-
|
| 13 |
-
from fastapi
|
| 14 |
-
from
|
| 15 |
-
|
| 16 |
-
from .
|
| 17 |
-
from
|
| 18 |
-
|
| 19 |
-
from .
|
| 20 |
-
from .
|
| 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 |
-
self.
|
| 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 |
-
"
|
| 186 |
-
"
|
| 187 |
-
"
|
| 188 |
-
"
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import logging
|
| 5 |
+
# app/app/main.py
|
| 6 |
+
import os
|
| 7 |
+
from app.cache import Cache
|
| 8 |
+
from contextlib import asynccontextmanager, suppress
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Annotated
|
| 12 |
+
|
| 13 |
+
from fastapi import Depends, FastAPI, HTTPException, Query, Request
|
| 14 |
+
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
|
| 15 |
+
from fastapi.staticfiles import StaticFiles
|
| 16 |
+
from fastapi.templating import Jinja2Templates
|
| 17 |
+
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
| 18 |
+
|
| 19 |
+
from .cache import MeasurementCache
|
| 20 |
+
from .config import Settings, get_settings
|
| 21 |
+
from .fetcher import FetchResult, fetch_latest
|
| 22 |
+
from .metrics import record_fetch, set_background_state, set_data_age
|
| 23 |
+
from .models import HistoryResponse, LatestResponse, Measurement
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
CACHE_DIR = os.getenv("APP_CACHE_DIR", "/data")
|
| 28 |
+
cache = Cache(filename="cache.json") # nutzt intern APP_CACHE_DIR
|
| 29 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 30 |
+
TEMPLATES = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
| 31 |
+
|
| 32 |
+
@asynccontextmanager
|
| 33 |
+
async def lifespan(app: FastAPI):
|
| 34 |
+
logging.basicConfig(level=logging.INFO)
|
| 35 |
+
await service.start()
|
| 36 |
+
try:
|
| 37 |
+
yield
|
| 38 |
+
finally:
|
| 39 |
+
await service.stop()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
app = FastAPI(title="Rheinpegel App", version="0.1.0", lifespan=lifespan)
|
| 43 |
+
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class PegelService:
|
| 47 |
+
def __init__(self, settings: Settings, cache: MeasurementCache) -> None:
|
| 48 |
+
self.settings = settings
|
| 49 |
+
self.cache = cache
|
| 50 |
+
self._lock = asyncio.Lock()
|
| 51 |
+
self._task: asyncio.Task[None] | None = None
|
| 52 |
+
|
| 53 |
+
async def start(self) -> None:
|
| 54 |
+
if self._task and not self._task.done():
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
if len(self.cache) == 0:
|
| 58 |
+
try:
|
| 59 |
+
await self.fetch_and_update()
|
| 60 |
+
except Exception as exc: # noqa: BLE001
|
| 61 |
+
logger.warning("Initial fetch failed, cache remains empty: %s", exc)
|
| 62 |
+
|
| 63 |
+
self._task = asyncio.create_task(self._run_loop())
|
| 64 |
+
|
| 65 |
+
async def stop(self) -> None:
|
| 66 |
+
if self._task:
|
| 67 |
+
self._task.cancel()
|
| 68 |
+
with suppress(asyncio.CancelledError):
|
| 69 |
+
await self._task
|
| 70 |
+
self._task = None
|
| 71 |
+
set_background_state(False)
|
| 72 |
+
|
| 73 |
+
def is_running(self) -> bool:
|
| 74 |
+
return self._task is not None and not self._task.done()
|
| 75 |
+
|
| 76 |
+
async def fetch_and_update(
|
| 77 |
+
self,
|
| 78 |
+
*,
|
| 79 |
+
force_demo: bool = False,
|
| 80 |
+
) -> FetchResult:
|
| 81 |
+
async with self._lock:
|
| 82 |
+
previous = await self.cache.get_latest()
|
| 83 |
+
result = await fetch_latest(self.settings, previous, force_demo=force_demo)
|
| 84 |
+
await self.cache.add(result.measurement)
|
| 85 |
+
|
| 86 |
+
self._update_metrics(result)
|
| 87 |
+
return result
|
| 88 |
+
|
| 89 |
+
async def latest(self) -> Measurement | None:
|
| 90 |
+
return await self.cache.get_latest()
|
| 91 |
+
|
| 92 |
+
async def history(self) -> list[Measurement]:
|
| 93 |
+
return await self.cache.get_history()
|
| 94 |
+
|
| 95 |
+
async def _run_loop(self) -> None:
|
| 96 |
+
set_background_state(True)
|
| 97 |
+
try:
|
| 98 |
+
while True:
|
| 99 |
+
try:
|
| 100 |
+
await self.fetch_and_update()
|
| 101 |
+
except Exception as exc: # noqa: BLE001
|
| 102 |
+
logger.exception("Background fetch failure: %s", exc)
|
| 103 |
+
await asyncio.sleep(self.settings.refresh_seconds)
|
| 104 |
+
except asyncio.CancelledError:
|
| 105 |
+
raise
|
| 106 |
+
finally:
|
| 107 |
+
set_background_state(False)
|
| 108 |
+
|
| 109 |
+
def _update_metrics(self, result: FetchResult) -> None:
|
| 110 |
+
outcome = "success"
|
| 111 |
+
if result.error:
|
| 112 |
+
outcome = "error"
|
| 113 |
+
elif result.is_demo:
|
| 114 |
+
outcome = "demo"
|
| 115 |
+
record_fetch(result.latency_ms, outcome)
|
| 116 |
+
|
| 117 |
+
if result.measurement:
|
| 118 |
+
now = datetime.now(self.settings.timezone)
|
| 119 |
+
age = max(0.0, (now - result.measurement.timestamp).total_seconds())
|
| 120 |
+
set_data_age(age)
|
| 121 |
+
else:
|
| 122 |
+
set_data_age(None)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
settings = get_settings()
|
| 126 |
+
cache = MeasurementCache()
|
| 127 |
+
service = PegelService(settings=settings, cache=cache)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
async def get_service() -> PegelService:
|
| 131 |
+
return service
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _warning_levels() -> list[dict[str, str | int]]:
|
| 135 |
+
return [
|
| 136 |
+
{"label": "Normal", "range": "< 400 cm", "color": "badge-normal", "min": 0, "max": 399},
|
| 137 |
+
{"label": "Aufmerksamkeit", "range": "400 – 599 cm", "color": "badge-attention", "min": 400, "max": 599},
|
| 138 |
+
{"label": "Warnung", "range": "600 – 799 cm", "color": "badge-warning", "min": 600, "max": 799},
|
| 139 |
+
{"label": "Alarm", "range": "≥ 800 cm", "color": "badge-alarm", "min": 800, "max": 9999},
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _sparkline_path(measurements: list[Measurement]) -> str:
|
| 144 |
+
if not measurements:
|
| 145 |
+
return ""
|
| 146 |
+
levels = [m.level_cm for m in measurements]
|
| 147 |
+
min_level = min(levels)
|
| 148 |
+
max_level = max(levels)
|
| 149 |
+
span = max(max_level - min_level, 1)
|
| 150 |
+
step = 100 / max(len(levels) - 1, 1)
|
| 151 |
+
points = []
|
| 152 |
+
for idx, level in enumerate(levels):
|
| 153 |
+
x = idx * step
|
| 154 |
+
y = 40 - ((level - min_level) / span * 40)
|
| 155 |
+
points.append(f"{x:.2f},{y:.2f}")
|
| 156 |
+
return "M " + " L ".join(points)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@app.get("/", response_class=HTMLResponse)
|
| 160 |
+
async def dashboard(
|
| 161 |
+
request: Request,
|
| 162 |
+
demo: Annotated[bool, Query(alias="demo")] = False,
|
| 163 |
+
service: PegelService = Depends(get_service),
|
| 164 |
+
) -> HTMLResponse:
|
| 165 |
+
if demo:
|
| 166 |
+
await service.fetch_and_update(force_demo=True)
|
| 167 |
+
|
| 168 |
+
latest = await service.latest()
|
| 169 |
+
if latest is None:
|
| 170 |
+
result = await service.fetch_and_update(force_demo=demo)
|
| 171 |
+
latest = result.measurement
|
| 172 |
+
|
| 173 |
+
history = await service.history()
|
| 174 |
+
sparkline = history[-24:]
|
| 175 |
+
sparkline_path = _sparkline_path(sparkline)
|
| 176 |
+
initial_payload = {
|
| 177 |
+
"latest": latest.model_dump(mode="json") if latest else None,
|
| 178 |
+
"history": [item.model_dump(mode="json") for item in history],
|
| 179 |
+
"autoRefresh": settings.refresh_seconds,
|
| 180 |
+
"demo": demo or (latest.is_demo if latest else False),
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
context = {
|
| 184 |
+
"request": request,
|
| 185 |
+
"latest": latest,
|
| 186 |
+
"history": history,
|
| 187 |
+
"sparkline": sparkline,
|
| 188 |
+
"sparkline_path": sparkline_path,
|
| 189 |
+
"auto_refresh_seconds": settings.refresh_seconds,
|
| 190 |
+
"timezone": settings.tz,
|
| 191 |
+
"warning_levels": _warning_levels(),
|
| 192 |
+
"demo_mode": demo or (latest.is_demo if latest else False),
|
| 193 |
+
"initial_payload": initial_payload,
|
| 194 |
+
}
|
| 195 |
+
return TEMPLATES.TemplateResponse("index.html.j2", context)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@app.get("/api/latest")
|
| 199 |
+
async def api_latest(
|
| 200 |
+
demo: Annotated[bool, Query(alias="demo")] = False,
|
| 201 |
+
service: PegelService = Depends(get_service),
|
| 202 |
+
) -> JSONResponse:
|
| 203 |
+
result = await service.fetch_and_update(force_demo=demo)
|
| 204 |
+
history = await service.history()
|
| 205 |
+
response = LatestResponse(
|
| 206 |
+
measurement=result.measurement,
|
| 207 |
+
history=history,
|
| 208 |
+
latency_ms=result.latency_ms,
|
| 209 |
+
error=result.error,
|
| 210 |
+
demo_mode=result.is_demo,
|
| 211 |
+
)
|
| 212 |
+
return JSONResponse(response.model_dump(mode="json"))
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@app.get("/api/history")
|
| 216 |
+
async def api_history(service: PegelService = Depends(get_service)) -> JSONResponse:
|
| 217 |
+
history = await service.history()
|
| 218 |
+
response = HistoryResponse(data=history, demo_mode=any(item.is_demo for item in history))
|
| 219 |
+
return JSONResponse(response.model_dump(mode="json"))
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@app.get("/healthz")
|
| 223 |
+
async def healthz(service: PegelService = Depends(get_service)) -> PlainTextResponse:
|
| 224 |
+
if not service.is_running():
|
| 225 |
+
raise HTTPException(status_code=503, detail="Background task not running")
|
| 226 |
+
return PlainTextResponse("ok")
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@app.get("/metrics")
|
| 230 |
+
async def metrics_endpoint(service: PegelService = Depends(get_service)) -> PlainTextResponse:
|
| 231 |
+
latest = await service.latest()
|
| 232 |
+
if latest is None:
|
| 233 |
+
set_data_age(None)
|
| 234 |
+
else:
|
| 235 |
+
age = max(0.0, (datetime.now(settings.timezone) - latest.timestamp).total_seconds())
|
| 236 |
+
set_data_age(age)
|
| 237 |
+
data = generate_latest()
|
| 238 |
+
return PlainTextResponse(content=data.decode("utf-8"), media_type=CONTENT_TYPE_LATEST)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
import uvicorn
|
| 243 |
+
|
| 244 |
+
uvicorn.run("app.main:app", host="0.0.0.0", port=settings.port, reload=True)
|