"""Coremarket REST API, version 1 (mounted at /api/v1).""" from __future__ import annotations import asyncio import csv import io import os from typing import Literal import httpx from fastapi import APIRouter, Depends, HTTPException, Query from fastapi.responses import Response from pydantic import BaseModel, Field from app import auth, manual, state from app.data.cities import CITIES from app.data.providers import CATALOG_DATE, CONTINENTS, FX_NOTE, PROVIDERS from app.data.software import APPS, CATEGORY_ORDER, PRESETS from app.engine import Workload, latencies, quote, size API_VERSION = "1.0.0" # Every endpoint here needs a signed-in session or an API key. router = APIRouter(prefix="/api/v1", dependencies=[Depends(auth.current_user)]) COMPLIANCE = ("hipaa", "soc2", "pci", "gdpr") CITY_IDS = {c[0] for c in CITIES} SORT_KEYS = ("total", "recurring", "rtt_avg_ms", "rtt_max_ms", "vcpu", "ram_gb", "provider") # ------------------------------------------------------------------ helpers def _norm(s: str) -> str: return s.strip().lower().replace("-", " ").replace("_", " ") _CONT = {_norm(c): c for c in CONTINENTS} def _continents(vals: list[str]) -> list[str]: out = [] for v in vals: c = _CONT.get(_norm(v)) if not c: raise HTTPException(422, f"unknown continent '{v}'. Use one of: {', '.join(CONTINENTS)}") out.append(c) return out def _split(vals: list[str] | None) -> list[str]: """Accept both repeated (?x=a&x=b) and comma-separated (?x=a,b) query values.""" return [p.strip() for v in (vals or []) for p in v.split(",") if p.strip()] def _provider(pid: str) -> dict: p = next((p for p in state.effective_providers() if p["id"] == pid), None) if not p: raise HTTPException(404, f"unknown provider '{pid}'") return p def _provider_summary(p: dict) -> dict: return {k: p.get(k) for k in ( "id", "name", "website", "pricing_url", "api_docs", "api_docs_note", "pricing_api", "compliance_url", "price_confidence", "compliance", "compliance_note", "storage", "ipv4_monthly", "egress", "smtp25", "price_source", "live", "setup_fee")} | { "manual": bool(p.get("manual_defaults")), "region_count": len(p["regions"]), "continents": sorted({r["continent"] for r in p["regions"]})} def _region_out(r: dict, provider_id: str | None = None) -> dict: d = dict(code=r["code"], location=r["label"], country=r["country"], continent=r["continent"], lat=r["lat"], lon=r["lon"], price_multiplier=r["mult"], ping_host=r.get("ping_host")) if provider_id: d["provider_id"] = provider_id return d # ------------------------------------------------------------------ models class SizeRequest(BaseModel): """Workload to size. Give `tier`, `apps`, or both (apps are added to the tier).""" tier: str | None = Field(None, description="Federated tier id: base, good, better, best", examples=["good"]) apps: list[str] = Field([], description="App ids (see GET /apps). Core apps are always included.", examples=[["nextcloud", "vaultwarden"]]) concurrent: int = Field(5, ge=1, le=10000, description="Concurrent active users") named: int = Field(10, ge=1, le=100000, description="Named users (accounts); drives disk") headroom: float = Field(0.25, ge=0, le=3, description="Extra CPU/RAM fraction (0.25 = 25%)") disk_growth: float = Field(0.3, ge=0, le=5, description="Extra disk fraction for 12-month growth") extra_disk_gb: int = Field(0, ge=0, le=100000, description="Additional disk to add, GB") class Override(BaseModel): vcpu: int | None = Field(None, ge=1, le=512) ram_gb: float | None = Field(None, gt=0, le=4096) disk_gb: float | None = Field(None, gt=0, le=100000) class QuoteRequest(SizeRequest): continents: list[str] = Field([], description=f"Limit to: {', '.join(CONTINENTS)}") providers: list[str] = Field([], description="Limit to provider ids (see GET /providers)") compliance: list[Literal["hipaa", "soc2", "pci", "gdpr"]] = Field([], description="All must be 'yes' (or 'partial' if allow_partial_compliance)") allow_partial_compliance: bool = False require_smtp: bool = Field(False, description="Exclude providers that hard-block outbound TCP 25") allow_arm: bool = False allow_burstable: bool = True dedicated_only: bool = False override: Override | None = Field(None, description="Use these values instead of the computed size") cities: list[str] = Field([], description="City ids for rtt_avg_ms / rtt_max_ms (see GET /cities)", examples=[["nyc", "chi"]]) max_rtt_ms: int | None = Field(None, ge=1, description="Drop results whose worst RTT to `cities` exceeds this") best_per_provider: bool = Field(False, description="Keep only the cheapest region per provider") sort: Literal["total", "recurring", "rtt_avg_ms", "rtt_max_ms", "vcpu", "ram_gb", "provider"] = "total" limit: int | None = Field(None, ge=1, le=5000) include_latency: bool = Field(True, description="Include the RTT estimate to all 40 cities per result") include_alternatives: bool = Field(True, description="Include next-best plans in the same region") class MeasureRequest(BaseModel): host: str = Field(description="A region's ping_host (see GET /regions)", examples=["ash-speed.hetzner.com"]) city: str = Field(description="City id (see GET /cities)", examples=["chi"]) # ------------------------------------------------------------------ core logic def _sizing(req: SizeRequest) -> dict: apps = list(req.apps) if req.tier: if req.tier not in PRESETS: raise HTTPException(422, f"unknown tier '{req.tier}'. Use one of: {', '.join(PRESETS)}") apps = PRESETS[req.tier]["apps"] + [a for a in apps if a not in PRESETS[req.tier]["apps"]] unknown = [a for a in apps if a not in APPS] if unknown: raise HTTPException(422, f"unknown app id(s): {', '.join(unknown)} (see GET /api/v1/apps)") return size(Workload(apps, req.concurrent, req.named, req.headroom, req.disk_growth, req.extra_disk_gb)) def run_quote(req: QuoteRequest) -> dict: sizing = _sizing(req) need = dict(sizing["need"]) if req.override: need.update({k: v for k, v in req.override.model_dump().items() if v}) continents = _continents(req.continents) ids = {p["id"] for p in PROVIDERS} if bad := [p for p in req.providers if p not in ids]: raise HTTPException(422, f"unknown provider id(s): {', '.join(bad)}") if bad := [c for c in req.cities if c not in CITY_IDS]: raise HTTPException(422, f"unknown city id(s): {', '.join(bad)} (see GET /api/v1/cities)") opts = req.model_dump() ok_vals = {"yes", "partial"} if req.allow_partial_compliance else {"yes"} results = [] for p in state.effective_providers(): if req.providers and p["id"] not in req.providers: continue if any(p["compliance"].get(c) not in ok_vals for c in req.compliance): continue if req.require_smtp and p["smtp25"] == "blocked": continue for r in p["regions"]: if continents and r["continent"] not in continents: continue q = quote(p, r, need, opts) if not q: continue lat = latencies(r) sel = [lat[c] for c in req.cities] row = dict( provider_id=p["id"], provider=p["name"], region=r["code"], location=r["label"], country=r["country"], continent=r["continent"], ping_host=r.get("ping_host"), compliance=p["compliance"], smtp25=p["smtp25"], price_confidence=p["price_confidence"], price_source=p["price_source"], storage_name=p["storage"]["name"], storage_kind=p["storage"]["kind"], egress=p["egress"], rtt_avg_ms=round(sum(sel) / len(sel)) if sel else None, rtt_max_ms=max(sel) if sel else None, latency=lat, **q, ) if req.max_rtt_ms and sel and row["rtt_max_ms"] > req.max_rtt_ms: continue results.append(row) results.sort(key=lambda x: x["total"]) if req.best_per_provider: seen = set() results = [r for r in results if not (r["provider_id"] in seen or seen.add(r["provider_id"]))] if req.sort != "total": results.sort(key=lambda x: (x[req.sort] is None, x[req.sort] if x[req.sort] is not None else 0, x["total"])) total = len(results) if req.limit: results = results[:req.limit] for r in results: if not req.include_latency: r.pop("latency") if not req.include_alternatives: r.pop("alternatives", None) return dict(sizing=sizing, need=need, count=total, returned=len(results), results=results) def _csv(out: dict) -> Response: buf = io.StringIO() w = csv.writer(buf) cities = [c for c in CITIES] w.writerow(["provider_id", "provider", "region", "location", "country", "continent", "model", "vcpu", "ram_gb", "disk_gb", "cpu_type", "arch", "vm_usd_mo", "extra_storage_gb", "extra_storage_usd_mo", "ipv4_usd_mo", "monthly_usd", "setup_fee_usd", "total_first_month_usd", "addl_storage_usd_gb_mo", "hipaa", "soc2", "pci_dss", "gdpr", "smtp25", "price_source", "price_confidence", "rtt_avg_ms", "rtt_max_ms"] + [f"rtt_ms_{c[0]}" for c in cities]) for r in out["results"]: lat = r.get("latency") or {} w.writerow([r["provider_id"], r["provider"], r["region"], r["location"], r["country"], r["continent"], r["model"], r["vcpu"], r["ram_gb"], r["disk_gb"], r["cpu_type"], r["arch"], r["base_price"], r["extra_storage_gb"], r["extra_storage_cost"], r["ipv4"], r["recurring"], r["setup_fee"], r["total"], r["storage_price_gb"], r["compliance"]["hipaa"], r["compliance"]["soc2"], r["compliance"]["pci"], r["compliance"]["gdpr"], r["smtp25"], r["price_source"], r["price_confidence"], r["rtt_avg_ms"], r["rtt_max_ms"]] + [lat.get(c[0], "") for c in cities]) return Response(buf.getvalue(), media_type="text/csv", headers={"Content-Disposition": 'attachment; filename="coremarket-quote.csv"'}) # ------------------------------------------------------------------ meta @router.get("/status", tags=["meta"], summary="Service, catalog and live-pricing status") def status(): return dict( api_version=API_VERSION, catalog_date=CATALOG_DATE, fx_note=FX_NOTE, live_status=state.live_cache.get("_status", {}), price_sources={p["id"]: p["price_source"] for p in state.effective_providers()}, ) @router.get("/catalog", tags=["meta"], summary="Everything the web UI needs in one call") def catalog(): cats = {c: [] for c in CATEGORY_ORDER} for a in APPS.values(): if a["tier"] != "core": cats.setdefault(a["category"], []).append(dict(id=a["id"], name=a["name"], note=a["note"])) return dict( categories=[dict(name=k, apps=v) for k, v in cats.items() if v], core=[a["name"] for a in APPS.values() if a["tier"] == "core"], presets=PRESETS, cities=[dict(id=c[0], name=c[1], country=c[2]) for c in CITIES], continents=CONTINENTS, providers=[_provider_summary(p) for p in state.effective_providers()], catalog_date=CATALOG_DATE, fx_note=FX_NOTE, live_status=state.live_cache.get("_status"), ) # ------------------------------------------------------------------ reference data @router.get("/apps", tags=["reference"], summary="List apps and their resource profiles") def list_apps(category: str | None = Query(None, description="Exact category name"), tier: Literal["core", "library", "on_demand"] | None = Query(None, description="core = always installed")): return [a for a in APPS.values() if (not category or a["category"] == category) and (not tier or a["tier"] == tier)] @router.get("/apps/{app_id}", tags=["reference"], summary="One app") def get_app(app_id: str): if app_id not in APPS: raise HTTPException(404, f"unknown app '{app_id}'") return APPS[app_id] @router.get("/tiers", tags=["reference"], summary="Federated tiers (Base, Good, Better, Best)") def list_tiers(): core = [a["id"] for a in APPS.values() if a["tier"] == "core"] return [dict(id=k, label=v["label"], apps=v["apps"], core_apps=core, federated_price_usd_mo=v["federated_price"], federated_storage_gb=v["storage_gb"]) for k, v in PRESETS.items()] @router.get("/cities", tags=["reference"], summary="Latency target cities") def list_cities(): return [dict(id=c[0], name=c[1], country=c[2], lat=c[3], lon=c[4]) for c in CITIES] @router.get("/continents", tags=["reference"], summary="Continent names used for filtering") def list_continents(): return CONTINENTS @router.get("/providers", tags=["reference"], summary="List providers (compliance, storage, egress, API docs)") def list_providers(): return [_provider_summary(p) for p in state.effective_providers()] @router.get("/providers/{provider_id}", tags=["reference"], summary="One provider with its regions and plans") def get_provider(provider_id: str): p = _provider(provider_id) plans = [{k: v for k, v in pl.items() if k != "tag"} for pl in p["plans"]] return _provider_summary(p) | dict(regions=[_region_out(r) for r in p["regions"]], plans=plans) @router.get("/regions", tags=["reference"], summary="All provider regions") def list_regions(continent: list[str] | None = Query(None, description="Repeat or comma-separate"), provider: list[str] | None = Query(None, description="Provider id; repeat or comma-separate")): conts, provs = _continents(_split(continent)), _split(provider) return [_region_out(r, p["id"]) for p in state.effective_providers() if not provs or p["id"] in provs for r in p["regions"] if not conts or r["continent"] in conts] # ------------------------------------------------------------------ sizing & quoting @router.post("/size", tags=["quote"], summary="Compute the VM size for a workload") def post_size(req: SizeRequest): return _sizing(req) @router.post("/quote", tags=["quote"], summary="Size the workload and price it in every matching region", responses={200: {"content": {"application/json": {}, "text/csv": {}}}}) def post_quote(req: QuoteRequest, format: Literal["json", "csv"] = Query("json")): out = run_quote(req) return _csv(out) if format == "csv" else out @router.get("/quote", tags=["quote"], summary="Same as POST /quote, with query parameters", responses={200: {"content": {"application/json": {}, "text/csv": {}}}}) def get_quote( tier: str | None = None, apps: list[str] | None = Query(None, description="App ids; repeat or comma-separate"), concurrent: int = Query(5, ge=1, le=10000), named: int = Query(10, ge=1, le=100000), headroom: float = Query(0.25, ge=0, le=3), disk_growth: float = Query(0.3, ge=0, le=5), extra_disk_gb: int = Query(0, ge=0), continent: list[str] | None = Query(None, description="e.g. europe, north-america"), provider: list[str] | None = Query(None), compliance: list[str] | None = Query(None), allow_partial_compliance: bool = False, require_smtp: bool = False, allow_arm: bool = False, allow_burstable: bool = True, dedicated_only: bool = False, vcpu: int | None = Query(None, ge=1, description="Override computed vCPU"), ram_gb: float | None = Query(None, gt=0, description="Override computed RAM"), disk_gb: float | None = Query(None, gt=0, description="Override computed disk"), cities: list[str] | None = Query(None), max_rtt_ms: int | None = Query(None, ge=1), best_per_provider: bool = False, sort: Literal["total", "recurring", "rtt_avg_ms", "rtt_max_ms", "vcpu", "ram_gb", "provider"] = "total", limit: int | None = Query(None, ge=1, le=5000), include_latency: bool = False, include_alternatives: bool = False, format: Literal["json", "csv"] = "json", ): comp = [c.lower() for c in _split(compliance)] if bad := [c for c in comp if c not in COMPLIANCE]: raise HTTPException(422, f"unknown compliance '{', '.join(bad)}'. Use: {', '.join(COMPLIANCE)}") req = QuoteRequest( tier=tier, apps=_split(apps), concurrent=concurrent, named=named, headroom=headroom, disk_growth=disk_growth, extra_disk_gb=extra_disk_gb, continents=_split(continent), providers=_split(provider), compliance=comp, allow_partial_compliance=allow_partial_compliance, require_smtp=require_smtp, allow_arm=allow_arm, allow_burstable=allow_burstable, dedicated_only=dedicated_only, override=Override(vcpu=vcpu, ram_gb=ram_gb, disk_gb=disk_gb) if (vcpu or ram_gb or disk_gb) else None, cities=_split(cities), max_rtt_ms=max_rtt_ms, best_per_provider=best_per_provider, sort=sort, limit=limit, include_latency=include_latency or format == "csv", include_alternatives=include_alternatives, ) out = run_quote(req) return _csv(out) if format == "csv" else out # ------------------------------------------------------------------ prices @router.post("/prices/refresh", tags=["prices"], summary="Pull live prices from provider APIs now", dependencies=[Depends(auth.require_admin)]) async def refresh_prices(): return dict(status=await state.refresh_live()) def _manual_provider(pid: str) -> dict: p = next((p for p in PROVIDERS if p["id"] == pid), None) if not p: raise HTTPException(404, f"unknown provider '{pid}'") if not p.get("manual_defaults"): raise HTTPException(404, f"provider '{pid}' has no manual price sheet") return p @router.get("/providers/{provider_id}/price-sheet", tags=["prices"], summary="Read a hand-maintained price sheet (Contabo)") def get_price_sheet(provider_id: str): p = _manual_provider(provider_id) sheet, is_default = manual.get_sheet(p) return dict(provider=p["name"], sheet=sheet, is_default=is_default, regions=[dict(code=r["code"], label=r["label"], country=r["country"]) for r in p["regions"]]) @router.put("/providers/{provider_id}/price-sheet", tags=["prices"], summary="Replace a price sheet", dependencies=[Depends(auth.require_admin)]) def put_price_sheet(provider_id: str, sheet: manual.ManualSheet): return dict(sheet=manual.save_sheet(_manual_provider(provider_id), sheet)) @router.delete("/providers/{provider_id}/price-sheet", tags=["prices"], summary="Reset a price sheet to built-in defaults", dependencies=[Depends(auth.require_admin)]) def delete_price_sheet(provider_id: str): manual.reset_sheet(_manual_provider(provider_id)) return dict(ok=True) # ------------------------------------------------------------------ latency @router.post("/latency/measure", tags=["latency"], summary="Measure real RTT from a city to a region (Globalping)") async def measure(req: MeasureRequest): city = next((c for c in CITIES if c[0] == req.city), None) if not city: raise HTTPException(422, f"unknown city '{req.city}'") hosts = {r.get("ping_host") for p in PROVIDERS for r in p["regions"]} - {None} if req.host not in hosts: raise HTTPException(422, "host is not a known provider ping_host (see GET /api/v1/regions)") port = 80 if "speed" in req.host or "proof" in req.host else 443 headers = {"User-Agent": "coremarket/1.0"} if tok := os.environ.get("GLOBALPING_TOKEN"): headers["Authorization"] = f"Bearer {tok}" # Probe-location fallbacks: full city name, its first word (e.g. "Washington"), then the whole country. name, cc = city[1].split("/")[0], city[2] tries = [(f"{name}+{cc}", "city"), (f"{name.split()[0]}+{cc}", "city"), (cc, "country")] async with httpx.AsyncClient(timeout=30, headers=headers) as c: last, scope, mid = "", None, None for magic, scope in dict.fromkeys(tries): body = {"type": "ping", "target": req.host, "limit": 3, "locations": [{"magic": magic}], "measurementOptions": {"packets": 4, "protocol": "TCP", "port": port}} r = await c.post("https://api.globalping.io/v1/measurements", json=body) if r.status_code < 400: mid = r.json()["id"] break last = r.text[:300] if "no_probes_found" not in last: break if not mid: raise HTTPException(502, f"globalping: {last}") m = {} for _ in range(20): await asyncio.sleep(1) m = (await c.get(f"https://api.globalping.io/v1/measurements/{mid}")).json() if m.get("status") == "finished": break vals = [] for res in m.get("results", []): avg = (res.get("result", {}).get("stats") or {}).get("avg") if avg is not None: pr = res["probe"] vals.append(dict(probe=f"{pr.get('city')}, {pr.get('country')} ({pr.get('network')})", avg_ms=round(avg, 1))) if not vals: raise HTTPException(502, "no probe results (no probe in that city or target unreachable)") return dict(host=req.host, city=city[1], probe_scope=scope, results=vals, min_ms=min(v["avg_ms"] for v in vals))