Files
davidandClaude Opus 5.5 1bb2a299c7 Add Coremarket: Federated Core VM sizing and cloud pricing app
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>
2026-12-01 21:36:51 -07:00

201 lines
7.6 KiB
Python

"""Sizing, latency estimation and price matching."""
from __future__ import annotations
import math
from dataclasses import dataclass
from app.data.cities import CITIES
from app.data.software import APPS, BASE, IMPLIES, SHARED
# ---------------------------------------------------------------- sizing
@dataclass
class Workload:
apps: list[str]
concurrent: int = 5
named: int = 10
headroom: float = 0.25 # applied to RAM and CPU
disk_growth: float = 0.3 # fraction added to disk for 12-month growth
extra_disk_gb: int = 0
# Apps sit mostly idle; their "cpu" figure is the share when busy.
BACKGROUND_DUTY = 0.25
# A concurrent user is active in roughly one heavy app plus one light one,
# not in every installed app at once.
SECONDARY_APP_WEIGHT = 0.5
def _line(name, src, conc, named, kind, per_user=True):
return dict(
name=name, kind=kind,
ram_mb=src["ram_mb"] + (src["ram_pu"] * conc if per_user else 0),
cpu=src["cpu"] * BACKGROUND_DUTY + (src["cpu_pu"] * conc if per_user else 0),
disk_gb=src["disk_gb"] + src["disk_pu"] * named,
)
def _active_load(apps, key, conc):
vals = sorted((a[key] for a in apps), reverse=True) + [0, 0]
return (vals[0] + SECONDARY_APP_WEIGHT * vals[1]) * conc
def size(w: Workload) -> dict:
selected = [a for a in w.apps if a in APPS]
for a in list(selected):
for imp in IMPLIES.get(a, []):
if imp not in selected:
selected.append(imp)
# Federated Core is always present
for a in APPS.values():
if a["tier"] == "core" and a["id"] not in selected:
selected.append(a["id"])
lines = [_line(BASE["name"], BASE, w.concurrent, w.named, "base")]
deps: set[str] = set()
notes = []
for a in selected:
app = APPS[a]
lines.append(_line(app["name"], app, w.concurrent, w.named, app["tier"], per_user=False))
deps.update(app["deps"])
if app["note"] and app["tier"] != "core":
notes.append(f"{app['name']}: {app['note']}")
for d in sorted(deps):
lines.append(_line(SHARED[d]["name"], SHARED[d], w.concurrent, w.named, "shared"))
sel_apps = [APPS[a] for a in selected]
lines.append(dict(
name=f"Active users ({w.concurrent} concurrent, heaviest apps)", kind="users",
ram_mb=_active_load(sel_apps, "ram_pu", w.concurrent),
cpu=_active_load(sel_apps, "cpu_pu", w.concurrent),
disk_gb=0.0,
))
ram_mb = sum(l["ram_mb"] for l in lines)
cpu = sum(l["cpu"] for l in lines)
disk = sum(l["disk_gb"] for l in lines)
ram_need = ram_mb * (1 + w.headroom) / 1024
cpu_need = cpu * (1 + w.headroom)
disk_need = disk * (1 + w.disk_growth) + w.extra_disk_gb
vcpu = max(2, math.ceil(cpu_need))
ram_gb = max(2, math.ceil(ram_need))
disk_gb = max(40, int(math.ceil(disk_need / 10.0) * 10))
ratio = ram_gb / vcpu
if ratio >= 6:
family = "memory-optimised (>= 6-8 GB per vCPU)"
elif ratio <= 2.5:
family = "compute-optimised (~2 GB per vCPU)"
else:
family = "general purpose (~4 GB per vCPU)"
# nearest "standard" shape people actually sell
std_ram = next((r for r in (2, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128) if r >= ram_gb), ram_gb)
std_cpu = next((c for c in (2, 4, 6, 8, 12, 16, 24, 32) if c >= vcpu), vcpu)
return dict(
apps=selected,
lines=sorted(lines, key=lambda l: -l["ram_mb"]),
raw=dict(ram_gb=round(ram_mb / 1024, 2), cpu=round(cpu, 2), disk_gb=round(disk, 1)),
need=dict(vcpu=vcpu, ram_gb=ram_gb, disk_gb=disk_gb,
ram_exact=round(ram_need, 2), cpu_exact=round(cpu_need, 2)),
standard=dict(vcpu=std_cpu, ram_gb=std_ram, disk_gb=disk_gb),
family=family,
notes=notes,
needs_smtp=("email" in selected),
workload=dict(concurrent=w.concurrent, named=w.named, headroom=w.headroom, disk_growth=w.disk_growth),
)
# ---------------------------------------------------------------- latency
C_FIBER_KM_PER_MS = 204.0 # ~2/3 c in glass
ROUTE_FACTOR = 1.3 # real paths are longer than great circles
BASE_MS = 3.0 # serialisation, switching, last mile
def haversine_km(lat1, lon1, lat2, lon2) -> float:
r = 6371.0
p1, p2 = math.radians(lat1), math.radians(lat2)
dp, dl = p2 - p1, math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * r * math.asin(math.sqrt(a))
def est_rtt_ms(region: dict, city: tuple) -> int:
cid, _name, ccode, lat, lon, extra = city
d = haversine_km(region["lat"], region["lon"], lat, lon)
rtt = 2 * d * ROUTE_FACTOR / C_FIBER_KM_PER_MS + BASE_MS + extra
# Crossing the mainland-China border adds significant delay; staying inside avoids it.
if (ccode == "CN") != (region["country"] == "CN"):
rtt += 35
return int(round(max(rtt, 1)))
def latencies(region: dict) -> dict[str, int]:
return {c[0]: est_rtt_ms(region, c) for c in CITIES}
# ---------------------------------------------------------------- pricing
def plan_available(plan: dict, region: dict) -> bool:
if "regions" in plan and plan["regions"] is not None:
return region["code"] in plan["regions"]
tags = region.get("tags")
return tags is None or plan.get("tag") in tags
def plan_price(plan: dict, region: dict) -> float | None:
if "prices" in plan and plan["prices"] is not None:
return plan["prices"].get(region["code"])
return plan["price"] * region["mult"]
def quote(provider: dict, region: dict, need: dict, opts: dict) -> dict | None:
"""Cheapest plan in a region that satisfies the requirement."""
storage = provider["storage"]
sp = storage.get("price_gb")
best, alts = None, []
for plan in provider["plans"]:
if not plan_available(plan, region):
continue
if plan["arch"] != "x86_64" and not opts.get("allow_arm"):
continue
if plan["cpu_type"] == "burstable" and not opts.get("allow_burstable", True):
continue
if opts.get("dedicated_only") and plan["cpu_type"] != "dedicated":
continue
if plan["vcpu"] < need["vcpu"] or plan["ram_gb"] < need["ram_gb"] - 0.01:
continue
price = plan_price(plan, region)
if price is None:
continue
extra_gb = max(0, need["disk_gb"] - plan["disk_gb"])
if extra_gb and (storage["kind"] != "block" or sp is None):
continue
storage_mult = region["mult"] if "prices" not in plan else 1.0
extra_cost = extra_gb * sp * storage_mult if extra_gb else 0.0
ipv4 = provider.get("ipv4_monthly") or 0.0
setup = (provider.get("setup_fee") or {}).get("usd", 0.0)
recurring = price + extra_cost + ipv4
total = recurring + setup # first-month cost: recurring + one-time setup
q = dict(model=plan["model"], vcpu=plan["vcpu"], ram_gb=plan["ram_gb"], disk_gb=plan["disk_gb"],
cpu_type=plan["cpu_type"], arch=plan["arch"], plan_note=plan.get("note", ""),
base_price=round(price, 2), extra_storage_gb=extra_gb, extra_storage_cost=round(extra_cost, 2),
ipv4=round(ipv4, 2), recurring=round(recurring, 2), setup_fee=round(setup, 2),
total=round(total, 2),
storage_price_gb=round(sp * storage_mult, 4) if sp is not None else None)
alts.append(q)
if best is None or q["total"] < best["total"]:
best = q
if not best:
return None
alts.sort(key=lambda q: q["total"])
best = dict(best)
best["alternatives"] = [a for a in alts if a["model"] != best["model"]][:4]
return best