"""Live price adapters. Public, no-auth: Vultr, Akamai/Linode, Azure Retail Prices. Token-based (optional env vars): DigitalOcean (DIGITALOCEAN_TOKEN), Hetzner (HCLOUD_TOKEN). Results are cached to $DATA_DIR/live_prices.json and overlaid on the static catalog: a provider with live data uses the live plan list and per-region prices instead of the baseline x multiplier model. """ from __future__ import annotations import asyncio import json import logging import os import time from pathlib import Path import httpx from app.data.providers import PROVIDERS log = logging.getLogger("coremarket.live") DATA_DIR = Path(os.environ.get("DATA_DIR", "/data")) CACHE = DATA_DIR / "live_prices.json" EUR_USD = float(os.environ.get("EUR_USD", "1.16")) H = 730 MAX_RAM_GB = 64 MAX_VCPU = 16 def _static(pid): return next(p for p in PROVIDERS if p["id"] == pid) def _plan(model, vcpu, ram_gb, disk_gb, prices, cpu="shared", arch="x86_64"): return dict(model=model, vcpu=vcpu, ram_gb=round(ram_gb, 2), disk_gb=disk_gb, cpu_type=cpu, arch=arch, prices={k: round(v, 2) for k, v in prices.items()}, price=min(prices.values()) if prices else 0) async def fetch_vultr(c: httpx.AsyncClient) -> list[dict]: r = await c.get("https://api.vultr.com/v2/plans", params={"per_page": 500}) r.raise_for_status() out = [] for p in r.json()["plans"]: if p["type"] not in ("vc2", "vhf", "vhp", "voc") or p["monthly_cost"] <= 0: continue ram = p["ram"] / 1024 if ram < 2 or ram > MAX_RAM_GB or p["vcpu_count"] > MAX_VCPU or "free" in p["id"] or "v6" in p["id"]: continue cpu = "dedicated" if p["type"] == "voc" else "shared" out.append(_plan(p["id"], p["vcpu_count"], ram, p["disk"], {loc: p["monthly_cost"] for loc in p["locations"]}, cpu)) return out async def fetch_linode(c: httpx.AsyncClient) -> list[dict]: r = await c.get("https://api.linode.com/v4/linode/types", params={"page_size": 200}) r.raise_for_status() regions = [x["code"] for x in _static("linode")["regions"]] out = [] for t in r.json()["data"]: if t["class"] not in ("standard", "nanode", "dedicated"): continue ram = t["memory"] / 1024 if ram < 2 or ram > MAX_RAM_GB or t["vcpus"] > MAX_VCPU: continue overrides = {rp["id"]: rp["monthly"] for rp in t.get("region_prices") or [] if rp.get("monthly")} base = (t.get("price") or {}).get("monthly") prices = {rc: overrides.get(rc, base) for rc in regions} prices = {k: v for k, v in prices.items() if v} if not prices: continue cpu = "dedicated" if t["class"] == "dedicated" else "shared" out.append(_plan(t["id"], t["vcpus"], ram, t["disk"] // 1024, prices, cpu)) return out async def fetch_digitalocean(c: httpx.AsyncClient) -> list[dict] | None: tok = os.environ.get("DIGITALOCEAN_TOKEN") if not tok: return None r = await c.get("https://api.digitalocean.com/v2/sizes", params={"per_page": 200}, headers={"Authorization": f"Bearer {tok}"}) r.raise_for_status() out = [] for s in r.json()["sizes"]: ram = s["memory"] / 1024 if not s.get("available") or ram < 2 or ram > MAX_RAM_GB or s["vcpus"] > MAX_VCPU: continue cpu = "shared" if s["slug"].startswith("s-") else "dedicated" out.append(_plan(s["slug"], s["vcpus"], ram, s["disk"], {rg: s["price_monthly"] for rg in s["regions"]}, cpu)) return out _HETZNER_LOC = {"fsn1": "fsn1", "nbg1": "nbg1", "hel1": "hel1", "ash": "ash", "hil": "hil", "sin": "sin"} async def fetch_hetzner(c: httpx.AsyncClient) -> list[dict] | None: tok = os.environ.get("HCLOUD_TOKEN") if not tok: return None r = await c.get("https://api.hetzner.cloud/v1/server_types", params={"per_page": 50}, headers={"Authorization": f"Bearer {tok}"}) r.raise_for_status() out = [] for t in r.json()["server_types"]: if t.get("deprecated") or t.get("deprecation"): continue if t["memory"] < 2 or t["memory"] > MAX_RAM_GB or t["cores"] > MAX_VCPU: continue prices = {_HETZNER_LOC[p["location"]]: float(p["price_monthly"]["net"]) * EUR_USD for p in t["prices"] if p["location"] in _HETZNER_LOC} arch = "arm64" if t["architecture"] == "arm" else "x86_64" out.append(_plan(t["name"].upper(), t["cores"], t["memory"], t["disk"], prices, t["cpu_type"], arch)) return out async def fetch_azure(c: httpx.AsyncClient) -> list[dict]: prov = _static("azure") wanted = {r["code"] for r in prov["regions"]} out = [] for plan in prov["plans"]: sku = plan["model"] flt = (f"serviceName eq 'Virtual Machines' and armSkuName eq '{sku}' " f"and priceType eq 'Consumption'") url, params, prices = "https://prices.azure.com/api/retail/prices", {"$filter": flt}, {} while url: for attempt in range(5): r = await c.get(url, params=params) if r.status_code != 429: break await asyncio.sleep(float(r.headers.get("Retry-After", 2 * (attempt + 1)))) r.raise_for_status() j = r.json() for it in j["Items"]: if ("Windows" in it["productName"] or "Spot" in it["skuName"] or "Low Priority" in it["skuName"] or it["unitOfMeasure"] != "1 Hour" or it["armRegionName"] not in wanted): continue prices[it["armRegionName"]] = it["retailPrice"] * H url, params = j.get("NextPageLink"), None await asyncio.sleep(0.5) if prices: out.append(_plan(sku, plan["vcpu"], plan["ram_gb"], 0, prices, plan["cpu_type"], plan["arch"])) return out ADAPTERS = { "vultr": fetch_vultr, "linode": fetch_linode, "azure": fetch_azure, "digitalocean": fetch_digitalocean, "hetzner": fetch_hetzner, } def load_cache() -> dict: try: return json.loads(CACHE.read_text()) except (FileNotFoundError, json.JSONDecodeError): return {} async def refresh(cache: dict) -> dict: """Refresh all adapters, updating `cache` in place as each one finishes.""" status = cache.setdefault("_status", {}) async with httpx.AsyncClient(timeout=30, headers={"User-Agent": "coremarket/1.0"}) as c: async def run(pid, fn): try: plans = await fn(c) if plans is None: status[pid] = "skipped (no API token configured)" return if not plans: status[pid] = "error: no plans returned" return cache[pid] = dict(fetched_at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), plans=plans) status[pid] = f"ok ({len(plans)} plans)" _save(cache) except Exception as e: # keep previous cache on failure log.warning("live refresh %s failed: %s", pid, e) status[pid] = f"error: {e.__class__.__name__}: {e}"[:200] await asyncio.gather(*(run(pid, fn) for pid, fn in ADAPTERS.items())) _save(cache) return cache def _save(cache: dict): try: DATA_DIR.mkdir(parents=True, exist_ok=True) tmp = CACHE.with_suffix(".tmp") tmp.write_text(json.dumps({k: v for k, v in cache.items() if k != "_status"})) tmp.replace(CACHE) except OSError as e: log.warning("cannot write cache: %s", e) def cache_age_hours() -> float | None: try: return (time.time() - CACHE.stat().st_mtime) / 3600 except FileNotFoundError: return None