Dockerised FastAPI web app that sizes a VM for a selection of Federated Computer apps (Base/Good/Better/Best tiers or custom) and prices it across 14 cloud providers and ~250 regions, grouped by continent. - Sizing model per app with shared databases, headroom and disk growth - Live pricing from Vultr, Akamai/Linode and Azure (DigitalOcean and Hetzner with tokens); dated catalog for the rest - Hand-maintained Contabo price sheet with editor and table paste, including the one-time setup fee - HIPAA/SOC2/PCI DSS/GDPR status, SMTP port 25, IPv4 and egress notes - Estimated latency to 40 cities, real RTT via Globalping probes - Versioned REST API (/api/v1) with OpenAPI docs and CSV export - Accounts with admin/user roles, first admin from ADMIN_USERNAME / ADMIN_PASSWORD, per-account API keys, SQLite storage Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
106 lines
3.5 KiB
Python
106 lines
3.5 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")
|
|
|
|
|
|
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}
|