Files
2026-12-02 09:46:25 -07:00

111 lines
3.7 KiB
Python

"""Coremarket: size a Federated Computer stack and price it across clouds."""
from __future__ import annotations
import asyncio
import logging
import os
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import Depends, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.responses import FileResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from app import accounts_api, auth, live, state
from app.api import API_VERSION, router
logging.basicConfig(level=logging.INFO)
STATIC = Path(__file__).parent / "static"
REFRESH_HOURS = float(os.environ.get("LIVE_REFRESH_HOURS", "24"))
LIVE_ENABLED = os.environ.get("LIVE_PRICING", "1") != "0"
@asynccontextmanager
async def lifespan(_app):
auth.init() # creates the first admin from ADMIN_USERNAME / ADMIN_PASSWORD, or refuses to start
state.live_cache.update(live.load_cache())
tasks = []
if LIVE_ENABLED:
async def periodic():
age = live.cache_age_hours()
if age is not None and age < REFRESH_HOURS:
await asyncio.sleep((REFRESH_HOURS - age) * 3600)
while True:
await state.refresh_live()
await asyncio.sleep(REFRESH_HOURS * 3600)
tasks.append(asyncio.create_task(periodic()))
yield
for t in tasks:
t.cancel()
app = FastAPI(
title="Coremarket API",
version=API_VERSION,
description="Size a VM for a set of Federated Computer apps and price it across cloud providers and regions. "
"Authenticate with a browser session (sign in at /login) or an API key in the X-API-Key header. "
"See README.md for a guide and examples.",
lifespan=lifespan,
docs_url=None, redoc_url=None, openapi_url=None, # re-added below behind sign-in
)
if origins := os.environ.get("CORS_ORIGINS"):
app.add_middleware(CORSMiddleware, allow_origins=[o.strip() for o in origins.split(",") if o.strip()],
allow_methods=["*"], allow_headers=["*"])
app.include_router(accounts_api.router)
app.include_router(router)
app.mount("/static", StaticFiles(directory=STATIC), name="static")
@app.get("/favicon.ico", include_in_schema=False)
def favicon():
return FileResponse(STATIC / "favicon.svg", media_type="image/svg+xml")
def _signed_in(request: Request) -> bool:
token = request.cookies.get(auth.SESSION_COOKIE)
return bool(token and auth._session_user(token))
def _to_login(request: Request):
return RedirectResponse(f"/login?next={request.url.path}", status_code=303)
@app.get("/", include_in_schema=False)
def index(request: Request):
return FileResponse(STATIC / "index.html") if _signed_in(request) else _to_login(request)
@app.get("/login", include_in_schema=False)
def login_page():
return FileResponse(STATIC / "login.html")
@app.get("/openapi.json", include_in_schema=False, dependencies=[Depends(auth.current_user)])
def openapi_json():
return app.openapi()
@app.get("/docs", include_in_schema=False)
def docs(request: Request):
if not _signed_in(request):
return _to_login(request)
return get_swagger_ui_html(openapi_url="/openapi.json", title="Coremarket API",
swagger_ui_parameters={"persistAuthorization": True})
@app.get("/redoc", include_in_schema=False)
def redoc(request: Request):
if not _signed_in(request):
return _to_login(request)
return get_redoc_html(openapi_url="/openapi.json", title="Coremarket API")
@app.get("/healthz", tags=["meta"], summary="Liveness check (no sign-in needed)")
def healthz():
return {"ok": True}