commit 1bb2a299c75b52c828ce6b3d469b5ebb0df8536c Author: David Young Date: Tue Dec 1 21:36:51 2026 -0700 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 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4a390a4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +* +!app/ +!requirements.txt +**/__pycache__ diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..a3dfed2 --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +# Copy to .env (next to docker-compose.yml) and fill in before the first start. +# Used only on first run to create the admin account; ignored once any account exists. +ADMIN_USERNAME=admin +ADMIN_PASSWORD=change-me-to-something-long + +# Optional +# SESSION_HOURS=12 +# COOKIE_SECURE=1 # when Coremarket is served over HTTPS +# CORS_ORIGINS=https://example.com +# DIGITALOCEAN_TOKEN= +# HCLOUD_TOKEN= +# GLOBALPING_TOKEN= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a31446c --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +__pycache__/ +*.pyc +.venv/ +.env +.claude/settings.local.json +*.db +live_prices.json +manual_prices.json diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2cb588f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.13-slim +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 DATA_DIR=/data +WORKDIR /srv +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY app ./app +RUN useradd -r -u 10001 coremarket && mkdir -p /data && chown coremarket /data +USER coremarket +EXPOSE 8080 +HEALTHCHECK CMD python -c "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8080/healthz')" +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..36e6ed8 --- /dev/null +++ b/README.md @@ -0,0 +1,325 @@ +# Coremarket + +Size a VM for a chosen set of [Federated Computer](https://federated.computer/product/software-library/) +apps, then price that VM across 14 cloud providers and ~250 regions. Results are grouped by +North America, Europe, Asia, Australia, Africa and South America. Each option shows HIPAA / SOC 2 / +PCI DSS / GDPR status and estimated latency to 40 cities. + +## Run + +```bash +cp .env.example .env # then set ADMIN_USERNAME and ADMIN_PASSWORD (at least 10 characters) +docker compose up -d --build +open http://localhost:8080 # sign in as the admin +``` + +On first run, Coremarket creates the admin account from `ADMIN_USERNAME` / `ADMIN_PASSWORD`. If no +account exists and those aren't set, it refuses to start and says so in `docker compose logs`. After +that the two variables are ignored, so changing them later does not change any password. You can +remove `ADMIN_PASSWORD` from `.env` once you've signed in. + +| Env var | Default | Purpose | +|---|---|---| +| `LIVE_PRICING` | `1` | Pull live prices from provider APIs at startup, then every `LIVE_REFRESH_HOURS` | +| `LIVE_REFRESH_HOURS` | `24` | Refresh interval | +| `EUR_USD` | `1.16` | FX rate for EUR-priced providers (Hetzner, Scaleway) | +| `DIGITALOCEAN_TOKEN` | – | Read-only token enables live DigitalOcean pricing | +| `HCLOUD_TOKEN` | – | Read-only token enables live Hetzner pricing | +| `GLOBALPING_TOKEN` | – | Higher rate limit for real latency measurements | +| `ADMIN_USERNAME` / `ADMIN_PASSWORD` | – | First run only: creates the admin account (see [Accounts](#accounts-and-sign-in)) | +| `SESSION_HOURS` | `12` | How long a browser sign-in lasts | +| `COOKIE_SECURE` | `0` | Set to `1` when Coremarket is served over HTTPS, so the session cookie is only sent encrypted | +| `CORS_ORIGINS` | – | Comma-separated browser origins allowed to call the API from other sites | + +Live pricing works with no keys for **Vultr, Akamai/Linode and Azure**. **Contabo** has no pricing +API: its prices are kept in an editable sheet. Use **Edit Contabo prices** in the header (or "Edit +prices" in the Notes tab) to change plans, prices, currency/FX, setup fee and per-region surcharges, or +paste a price table copied from Contabo's site. Saved edits go to `/data/manual_prices.json`, and +"Reset to built-in" goes back to the defaults. The other providers use the +bundled catalog in `app/data/providers.py`, which is dated. Each row shows its price source and a +confidence level. + +## Accounts and sign-in + +Everything needs a signed-in account or an API key. The only exceptions are the sign-in page and +`/healthz`. + +| Role | Can | +|---|---| +| **admin** | Everything a user can, plus: create, disable, delete and re-role accounts, reset passwords, see and revoke every API key, create keys for any account, edit Contabo prices, refresh live prices | +| **user** | Use the web page and API (sizing, quotes, latency measurements), create and revoke their own API keys, change their own password | + +In the web page, the account menu (your username, top right) has **API keys**, **Users** (admins), +**Change password**, **API docs** and **Sign out**. + +- **API keys** belong to an account and act with that account's role. A key is shown only once, when + it's created; Coremarket stores only a hash of it. A key can have an expiry (in days) or never + expire. A key stops working when it's revoked, expires, or its account is disabled or deleted. +- **Safety rules:** the last active admin can't be demoted, disabled or deleted, and you can't disable + or delete your own account. Disabling an account, or resetting its password, signs it out + everywhere. +- **Passwords** need at least 10 characters and are stored as scrypt hashes. After 5 failed sign-ins + for the same username from the same address, sign-in is blocked for 5 minutes. +- **Storage:** accounts, keys and sessions live in `/data/coremarket.db` (SQLite) in the + `coremarket-data` volume. Back up that volume to keep them. +- **Lost the only admin password?** Stop the app, delete `/data/coremarket.db`, set + `ADMIN_USERNAME`/`ADMIN_PASSWORD`, and start again. This removes all accounts and keys. + +## How it works + +- **Sizing** (`app/engine.py`, `app/data/software.py`): each app has an idle RAM/CPU/disk footprint, + plus per-concurrent-user RAM/CPU and per-named-user disk. Shared databases are counted once, and + Federated Core (Traefik, PowerDNS, Authelia) is always included. Presets: Base (email, Headscale), + Good, Better, Best. Concurrent + users are assumed to be active in about 1.5 apps at a time, not all of them. Headroom and 12-month + disk growth are then added. +- **Matching**: in each region, the cheapest plan with at least the required vCPU and RAM wins. Block + storage is added if the plan's bundled disk is too small, and paid public IPv4 is included. You can + override the computed vCPU/RAM/disk in the UI. +- **Latency**: estimated from great-circle distance × 1.3 route factor at 204 km/ms, + 3 ms, plus + per-market penalties and +35 ms across the mainland-China border. For regions with a public probe + host, the detail view can measure real RTT through [Globalping](https://globalping.io) probes. +- **Compliance**: provider-level attestations for IaaS compute (yes / partial / no), with notes and + links in the Notes tab. HIPAA always needs a signed BAA. + +## API + +Coremarket has a JSON REST API. The web page uses the same API. + +- **Base URL:** `http://localhost:8080/api/v1` +- **Authentication:** every call needs an API key in the `X-API-Key` header (or + `Authorization: Bearer `). Create keys under **Account → API keys**. See + [Authentication](#authentication). +- **Interactive docs:** `http://localhost:8080/docs` (Swagger UI, where you can try every call; sign in + first). There's also `http://localhost:8080/redoc`. +- **OpenAPI spec:** `http://localhost:8080/openapi.json` (for generating client code; needs a key or + sign-in) +- **Prices** are USD per month unless a field says otherwise. Latencies are estimated round-trip times + in milliseconds. + +### Quick start + +```bash +export KEY=cmk_... # your API key (Account → API keys) +alias cm='curl -s -H "X-API-Key: $KEY"' + +# Cheapest GDPR-compliant European option per provider for the Good tier, +# with average/worst latency to Paris and Berlin +cm "http://localhost:8080/api/v1/quote?tier=good&continent=europe&compliance=gdpr&cities=par,ber&best_per_provider=true&limit=5" + +# HIPAA-eligible options for the Best tier, closest to Bogota and Lima first +cm "http://localhost:8080/api/v1/quote?tier=best&compliance=hipaa&cities=bog,lim&sort=rtt_max_ms&limit=5" + +# Just the VM size for Base plus Vaultwarden, 20 concurrent users +cm -X POST http://localhost:8080/api/v1/size -H 'Content-Type: application/json' \ + -d '{"tier": "base", "apps": ["vaultwarden"], "concurrent": 20}' + +# Every option as a spreadsheet (one column per city latency) +cm -o quote.csv "http://localhost:8080/api/v1/quote?tier=better&format=csv" +``` + +### Endpoints + +All paths are under `/api/v1`. "Role" is the minimum role needed. + +| Method | Path | Purpose | Role | +|---|---|---|---| +| POST | `/auth/login` | Sign in with `{"username", "password"}`; sets the session cookie (browser use) | none | +| POST | `/auth/logout` | Sign out | none | +| GET | `/auth/me` | The signed-in account, or the API key's owner | user | +| POST | `/auth/password` | Change your password: `{"current_password", "new_password"}` | user | +| GET | `/keys` | Your API keys. Admin: `?all=true` or `?user_id=` | user | +| POST | `/keys` | Create a key: `{"name", "expires_days"?}`. Admin may add `"user_id"`. Returns the key once. | user | +| DELETE | `/keys/{key_id}` | Revoke a key (your own; admin: any) | user | +| GET | `/users` | List accounts (with key counts and last sign-in) | admin | +| POST | `/users` | Create an account: `{"username", "password", "role"}` (`role` is `user` or `admin`) | admin | +| GET | `/users/{user_id}` | One account | admin | +| PATCH | `/users/{user_id}` | Change `role`, set `disabled` true/false, or set a new `password` | admin | +| DELETE | `/users/{user_id}` | Delete an account and its keys | admin | +| GET | `/status` | API version, catalog date, live-pricing status, price source per provider | user | +| GET | `/apps` | All apps with resource profiles. Filters: `?tier=core\|library\|on_demand`, `?category=` | user | +| GET | `/apps/{app_id}` | One app | user | +| GET | `/tiers` | Federated tiers (base, good, better, best): apps, Federated price and storage | user | +| GET | `/cities` | The 40 latency target cities (`id` is used in `cities=`) | user | +| GET | `/continents` | Continent names used for filtering | user | +| GET | `/providers` | Providers: compliance, storage, IPv4, egress, SMTP, API doc links, price source | user | +| GET | `/providers/{provider_id}` | One provider with its regions and plans | user | +| GET | `/regions` | All regions. Filters: `?continent=`, `?provider=` | user | +| POST | `/size` | Compute the VM size for a workload | user | +| POST | `/quote` | Size the workload and price it in every matching region (JSON body) | user | +| GET | `/quote` | Same as POST `/quote`, using query parameters | user | +| GET | `/catalog` | Everything the web page needs in one call | user | +| POST | `/latency/measure` | Measure real RTT from a city to a region (uses Globalping quota) | user | +| GET | `/providers/{provider_id}/price-sheet` | Read a hand-maintained price sheet (Contabo) | user | +| PUT | `/providers/{provider_id}/price-sheet` | Replace that price sheet | admin | +| DELETE | `/providers/{provider_id}/price-sheet` | Reset it to the built-in defaults | admin | +| POST | `/prices/refresh` | Pull live prices from provider APIs now | admin | + +Health check: `GET /healthz` (outside `/api/v1`, no sign-in). + +### Managing accounts and keys with the API + +```bash +# Admin: create an account, then a 90-day key for it +cm -X POST http://localhost:8080/api/v1/users -H 'Content-Type: application/json' \ + -d '{"username": "alice", "password": "a-long-password", "role": "user"}' +# -> {"id": 2, "username": "alice", "role": "user", "disabled": false, ...} + +cm -X POST http://localhost:8080/api/v1/keys -H 'Content-Type: application/json' \ + -d '{"name": "alice reporting", "expires_days": 90, "user_id": 2}' +# -> {"key": "cmk_1a2b3c4d_...", "id": 5, "prefix": "cmk_1a2b3c4d_…", "username": "alice", "expires_at": ..., "warning": "..."} + +# Disable, re-enable, or delete the account +cm -X PATCH http://localhost:8080/api/v1/users/2 -H 'Content-Type: application/json' -d '{"disabled": true}' +cm -X PATCH http://localhost:8080/api/v1/users/2 -H 'Content-Type: application/json' -d '{"disabled": false}' +cm -X DELETE http://localhost:8080/api/v1/users/2 + +# Any user: list and revoke your own keys +cm http://localhost:8080/api/v1/keys +cm -X DELETE http://localhost:8080/api/v1/keys/5 +``` + +### Sizing and quote parameters + +`POST /size` and `POST /quote` take a JSON body. `GET /quote` takes the same fields as query +parameters. For lists, repeat the parameter (`continent=europe&continent=asia`) or separate values +with commas (`continent=europe,asia`). + +| Field | Type | Default | Meaning | +|---|---|---|---| +| `tier` | string | – | `base`, `good`, `better` or `best`. Its apps are included. | +| `apps` | list of app ids | `[]` | Apps to include, added to the tier's apps. Core apps (Traefik, PowerDNS, Authelia) are always included. | +| `concurrent` | int | `5` | Concurrent active users (drives CPU/RAM) | +| `named` | int | `10` | Named user accounts (drives disk) | +| `headroom` | float | `0.25` | Extra CPU/RAM (0.25 = 25%) | +| `disk_growth` | float | `0.3` | Extra disk for 12-month growth | +| `extra_disk_gb` | int | `0` | Disk to add on top, GB | +| **Quote only:** | | | | +| `continents` (GET: `continent`) | list | all | `North America`, `Europe`, `Asia`, `Australia`, `Africa`, `South America`. Case-insensitive; `north-america` also works. | +| `providers` (GET: `provider`) | list | all | Provider ids, e.g. `aws`, `hetzner`, `contabo` (see `/providers`) | +| `compliance` | list | none | `hipaa`, `soc2`, `pci`, `gdpr`. The provider must be `yes` for all of them. | +| `allow_partial_compliance` | bool | `false` | Also accept `partial` | +| `require_smtp` | bool | `false` | Exclude providers that hard-block outbound port 25 (needed by the email server) | +| `allow_arm` / `allow_burstable` / `dedicated_only` | bool | `false` / `true` / `false` | CPU type filters | +| `override` (GET: `vcpu`, `ram_gb`, `disk_gb`) | object | – | Use these instead of the computed size, e.g. `{"vcpu": 8, "ram_gb": 32}` | +| `cities` | list of city ids | `[]` | Cities used for `rtt_avg_ms` / `rtt_max_ms` | +| `max_rtt_ms` | int | – | Drop results whose worst RTT to `cities` is higher | +| `best_per_provider` | bool | `false` | Keep only each provider's cheapest region | +| `sort` | string | `total` | `total`, `recurring`, `rtt_avg_ms`, `rtt_max_ms`, `vcpu`, `ram_gb`, `provider` | +| `limit` | int | all | Return at most this many results (`count` still reports the full number) | +| `include_latency` | bool | POST `true`, GET `false` | Include RTT to all 40 cities per result | +| `include_alternatives` | bool | POST `true`, GET `false` | Include next-best plans in the same region | +| `format` (query) | string | `json` | `csv` returns a spreadsheet instead (always includes all city latencies) | + +Unknown tiers, apps, continents, providers, cities or compliance names return **422** with a message +listing the valid values. + +### Quote response + +```jsonc +{ + "sizing": { "need": {...}, "standard": {...}, "family": "...", "raw": {...}, "lines": [...], "notes": [...], "apps": [...] }, + "need": { "vcpu": 4, "ram_gb": 12, "disk_gb": 270, "ram_exact": 11.8, "cpu_exact": 3.17 }, + "count": 13, // matching results before `limit` + "returned": 2, + "results": [ + { + "provider_id": "contabo", "provider": "Contabo", + "region": "eu-de-nue", "location": "Nuremberg", "country": "DE", "continent": "Europe", + "model": "Cloud VPS 8 (V155)", "vcpu": 8, "ram_gb": 24, "disk_gb": 300, + "cpu_type": "shared", "arch": "x86_64", "plan_note": "SSD, 600 Mbit/s", + "base_price": 16.24, // VM, per month + "extra_storage_gb": 0, "extra_storage_cost": 0.0, + "ipv4": 0.0, + "recurring": 16.24, // VM + extra storage + IPv4, per month + "setup_fee": 2.32, // one-time + "total": 18.56, // first month = recurring + setup_fee + "storage_price_gb": null, // additional block storage, $/GB-month (null = not offered) + "compliance": { "hipaa": "no", "soc2": "no", "pci": "no", "gdpr": "yes" }, + "smtp25": "open", // open | on request | blocked + "egress": { "included_gb": null, "per_gb": null, "note": "Unmetered (32 TB fair use)" }, + "price_source": "manual sheet 2026-12-01 (defaults)", "price_confidence": "medium", + "rtt_avg_ms": 10, "rtt_max_ms": 11, // over the requested `cities` + "latency": { "nyc": 85, "par": 10, ... }, // when include_latency + "alternatives": [ ... ], // when include_alternatives + "ping_host": null // host for /latency/measure, if available + } + ] +} +``` + +`need` is what the plans are matched against. It equals `sizing.need` unless you send `override`. + +### Price sheets (Contabo) + +Contabo has no pricing API, so its prices live in an editable sheet: + +```bash +# Read the current sheet +cm http://localhost:8080/api/v1/providers/contabo/price-sheet + +# Replace it (admin; prices in the sheet's currency, per month; surcharge is % per region code) +cm -X PUT http://localhost:8080/api/v1/providers/contabo/price-sheet -H 'Content-Type: application/json' \ + -d '{ + "currency": "EUR", "fx": 1.16, "setup_fee": 2.00, + "plans": [ + {"code": "V153", "name": "Cloud VPS 4", "vcpu": 4, "ram_gb": 8, "disk_gb": 100, "price": 5.50}, + {"code": "V154", "name": "Cloud VPS 6", "vcpu": 6, "ram_gb": 12, "disk_gb": 200, "price": 7.50} + ], + "region_surcharge_pct": {"us-east": 0, "us-west": 20, "sin": 40} + }' + +# Go back to the built-in sheet +cm -X DELETE http://localhost:8080/api/v1/providers/contabo/price-sheet +``` + +Plan fields: `name`, `vcpu`, `ram_gb` and `price` are required. `code`, `disk_gb`, `cpu_type` +(`shared`/`dedicated`) and `note` are optional. Regions missing from `region_surcharge_pct` get 0%. + +### Latency measurement + +```bash +cm -X POST http://localhost:8080/api/v1/latency/measure -H 'Content-Type: application/json' \ + -d '{"host": "ash-speed.hetzner.com", "city": "was"}' +# -> {"host": "...", "city": "Washington DC", "probe_scope": "city", "min_ms": ..., "results": [{"probe": "Washington, US (...)", "avg_ms": ...}, ...]} +``` + +`host` must be a region's `ping_host` from `/regions` or a quote result. If Globalping has no probe in the city, the +measurement falls back to the whole country and `probe_scope` says `country`. Probe hosts are available for AWS, +Hetzner and OVHcloud regions. Other providers don't publish one that answers, so they show estimates only. This calls the free +[Globalping](https://globalping.io) service, which limits how often it can be used. Set +`GLOBALPING_TOKEN` for a higher limit. + +### Authentication + +- **Scripts and integrations:** send an API key with every request, as `X-API-Key: ` or + `Authorization: Bearer `. Keys look like `cmk_<8 characters>_`. The request runs with + the key owner's role. +- **Browsers:** sign in at `/login`. The session is an HttpOnly cookie that lasts `SESSION_HOURS`. + Requests that change data using a session must also send the header `X-Coremarket: 1`, so other + websites can't submit forms on a signed-in user's behalf. The web page does this automatically; API + key requests don't need it. +- **Swagger UI (`/docs`):** sign in first. Then use **Authorize** to paste an API key, which also lets + you try write calls. + +A missing, invalid, expired or revoked key returns **401**. A valid key or session without the +needed role returns **403**. + +### Errors + +Errors return JSON `{"detail": "..."}`: **401** not signed in or invalid key, **403** role not allowed +(or missing `X-Coremarket` header on a session write), **404** not found, **409** conflict (e.g. +duplicate username, removing the last admin), **422** invalid parameters, **429** too many failed +sign-ins, **502** an upstream service (Globalping) failed. + +### Versioning + +Everything lives under `/api/v1`. Fields may be added within v1. Removing or renaming fields would +mean a new `/api/v2`. + +## Updating data + +- Prices and regions: `app/data/providers.py` (bump `CATALOG_DATE`) +- App profiles: `app/data/software.py` +- Cities: `app/data/cities.py` +- New live adapter: add a function to `ADAPTERS` in `app/live.py` diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/accounts_api.py b/app/accounts_api.py new file mode 100644 index 0000000..b7abb86 --- /dev/null +++ b/app/accounts_api.py @@ -0,0 +1,133 @@ +"""Sign-in, account management and API-key endpoints (mounted under /api/v1).""" + +from __future__ import annotations + +from typing import Literal + +from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response +from pydantic import BaseModel, Field + +from app import auth + +router = APIRouter(prefix="/api/v1") + + +def _ip(request: Request) -> str: + return request.client.host if request.client else "?" + + +# ------------------------------------------------------------------ models + +class LoginRequest(BaseModel): + username: str + password: str + + +class PasswordChange(BaseModel): + current_password: str + new_password: str = Field(min_length=auth.MIN_PASSWORD) + + +class NewUser(BaseModel): + username: str = Field(examples=["alice"]) + password: str = Field(min_length=auth.MIN_PASSWORD) + role: Literal["admin", "user"] = "user" + + +class UserUpdate(BaseModel): + role: Literal["admin", "user"] | None = None + disabled: bool | None = None + password: str | None = Field(None, min_length=auth.MIN_PASSWORD, description="Set a new password (signs the user out everywhere)") + + +class NewKey(BaseModel): + name: str = Field("API key", max_length=100, examples=["CI pipeline"]) + expires_days: int | None = Field(None, ge=1, le=3650, description="Omit for a key that never expires") + user_id: int | None = Field(None, description="Admin only: create the key for another account") + + +# ------------------------------------------------------------------ sign-in + +@router.post("/auth/login", tags=["auth"], summary="Sign in (sets a session cookie)") +def login(req: LoginRequest, request: Request, response: Response): + token, user = auth.login(req.username.strip(), req.password, _ip(request)) + response.set_cookie(auth.SESSION_COOKIE, token, max_age=int(auth.SESSION_HOURS * 3600), httponly=True, + samesite="lax", secure=auth.COOKIE_SECURE, path="/") + return dict(user=user) + + +@router.post("/auth/logout", tags=["auth"], summary="Sign out") +def logout(request: Request, response: Response): + auth.logout(request.cookies.get(auth.SESSION_COOKIE)) + response.delete_cookie(auth.SESSION_COOKIE, path="/") + return dict(ok=True) + + +@router.get("/auth/me", tags=["auth"], summary="The signed-in account (or the API key's owner)") +def me(user: dict = Depends(auth.current_user)): + return {k: v for k, v in user.items() if k != "token_hash"} + + +@router.post("/auth/password", tags=["auth"], summary="Change your own password (signs out your other sessions)") +def change_password(req: PasswordChange, user: dict = Depends(auth.current_user)): + auth.change_own_password(user, req.current_password, req.new_password, user.get("token_hash")) + return dict(ok=True) + + +# ------------------------------------------------------------------ users (admin) + +@router.get("/users", tags=["users"], summary="List accounts (admin)", dependencies=[Depends(auth.require_admin)]) +def list_users(): + return auth.list_users() + + +@router.post("/users", tags=["users"], summary="Create an account (admin)", status_code=201) +def create_user(req: NewUser, admin: dict = Depends(auth.require_admin)): + return auth.create_user(req.username.strip(), req.password, req.role) + + +@router.get("/users/{user_id}", tags=["users"], summary="One account (admin)", dependencies=[Depends(auth.require_admin)]) +def get_user(user_id: int): + return auth.get_user(user_id) + + +@router.patch("/users/{user_id}", tags=["users"], summary="Change role, disable/enable, or reset password (admin)") +def update_user(user_id: int, req: UserUpdate, admin: dict = Depends(auth.require_admin)): + return auth.update_user(user_id, admin, role=req.role, disabled=req.disabled, password=req.password) + + +@router.delete("/users/{user_id}", tags=["users"], summary="Delete an account and its API keys (admin)") +def delete_user(user_id: int, admin: dict = Depends(auth.require_admin)): + auth.delete_user(user_id, admin) + return dict(ok=True) + + +# ------------------------------------------------------------------ API keys + +@router.get("/keys", tags=["api keys"], summary="List API keys (yours; admins can see all)") +def list_keys(all: bool = Query(False, description="Admin only: every account's keys"), + user_id: int | None = Query(None, description="Admin only: one account's keys"), + user: dict = Depends(auth.current_user)): + if (all or user_id is not None) and user["role"] != "admin": + raise HTTPException(403, "admin role required") + if all: + return auth.list_keys() + return auth.list_keys(user_id if user_id is not None else user["id"]) + + +@router.post("/keys", tags=["api keys"], summary="Create an API key (the key is shown only in this response)", status_code=201) +def create_key(req: NewKey, user: dict = Depends(auth.current_user)): + owner = user["id"] + if req.user_id is not None and req.user_id != user["id"]: + if user["role"] != "admin": + raise HTTPException(403, "admin role required to create keys for other accounts") + owner = req.user_id + key, info = auth.create_key(owner, req.name, req.expires_days) + return dict(key=key, **info, username=auth.get_user(owner)["username"], + warning="Store this key now; it cannot be shown again.") + + +@router.delete("/keys/{key_id}", tags=["api keys"], summary="Revoke an API key (your own; admins any)") +def delete_key(key_id: int, user: dict = Depends(auth.current_user)): + auth.delete_key(key_id, user) + return dict(ok=True) diff --git a/app/api.py b/app/api.py new file mode 100644 index 0000000..5d13f03 --- /dev/null +++ b/app/api.py @@ -0,0 +1,435 @@ +"""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)) diff --git a/app/auth.py b/app/auth.py new file mode 100644 index 0000000..579c863 --- /dev/null +++ b/app/auth.py @@ -0,0 +1,371 @@ +"""Accounts, API keys and sessions (SQLite in $DATA_DIR/coremarket.db, stdlib only). + +- Passwords: scrypt with a per-user salt. +- API keys: "cmk_<8-char prefix>_"; only a SHA-256 hash is stored, the key is shown once. +- Sessions: random token in an HttpOnly cookie; only its SHA-256 hash is stored. +""" + +from __future__ import annotations + +import hashlib +import hmac +import logging +import os +import secrets +import sqlite3 +import threading +import time +from contextlib import contextmanager +from pathlib import Path + +from fastapi import Depends, HTTPException, Request +from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer + +log = logging.getLogger("coremarket.auth") +DATA_DIR = Path(os.environ.get("DATA_DIR", "/data")) +DB_PATH = DATA_DIR / "coremarket.db" +SESSION_COOKIE = "cm_session" +SESSION_HOURS = float(os.environ.get("SESSION_HOURS", "12")) +COOKIE_SECURE = os.environ.get("COOKIE_SECURE", "0") == "1" +MIN_PASSWORD = 10 +ROLES = ("admin", "user") +CSRF_HEADER = "x-coremarket" # required on cookie-authenticated writes (blocks cross-site form posts) + +_lock = threading.Lock() + + +# ------------------------------------------------------------------ database + +@contextmanager +def db(): + with _lock: + con = sqlite3.connect(DB_PATH) + con.row_factory = sqlite3.Row + con.execute("PRAGMA foreign_keys = ON") + try: + yield con + con.commit() + finally: + con.close() + + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + password_hash TEXT NOT NULL, + role TEXT NOT NULL CHECK (role IN ('admin','user')), + disabled INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + last_login INTEGER +); +CREATE TABLE IF NOT EXISTS api_keys ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + prefix TEXT NOT NULL UNIQUE, + key_hash TEXT NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER, + last_used INTEGER +); +CREATE TABLE IF NOT EXISTS sessions ( + token_hash TEXT PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL +); +""" + + +def init(): + """Create tables; on first run create the admin from ADMIN_USERNAME / ADMIN_PASSWORD.""" + DATA_DIR.mkdir(parents=True, exist_ok=True) + with db() as con: + con.execute("PRAGMA journal_mode = WAL") + con.executescript(SCHEMA) + n = con.execute("SELECT COUNT(*) FROM users").fetchone()[0] + con.execute("DELETE FROM sessions WHERE expires_at < ?", (int(time.time()),)) + if n: + if os.environ.get("ADMIN_PASSWORD"): + log.info("accounts already exist; ADMIN_USERNAME/ADMIN_PASSWORD are ignored (only used on first run)") + return + user, pw = os.environ.get("ADMIN_USERNAME", "").strip(), os.environ.get("ADMIN_PASSWORD", "") + if not user or not pw: + raise RuntimeError( + "First run: no accounts exist. Set ADMIN_USERNAME and ADMIN_PASSWORD (e.g. in .env next to " + "docker-compose.yml) to create the admin account, then start again.") + try: + create_user(user, pw, "admin") + except HTTPException as e: + raise RuntimeError(f"Cannot create the admin account from ADMIN_USERNAME/ADMIN_PASSWORD: {e.detail}") from None + log.warning("created admin account '%s' from ADMIN_USERNAME/ADMIN_PASSWORD", user) + + +# ------------------------------------------------------------------ hashing + +def hash_password(pw: str) -> str: + salt = secrets.token_bytes(16) + h = hashlib.scrypt(pw.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32) + return f"scrypt$16384$8$1${salt.hex()}${h.hex()}" + + +def verify_password(pw: str, stored: str) -> bool: + try: + _, n, r, p, salt, h = stored.split("$") + calc = hashlib.scrypt(pw.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p), dklen=len(h) // 2) + return hmac.compare_digest(calc.hex(), h) + except (ValueError, TypeError): + return False + + +_DUMMY_HASH = hash_password(secrets.token_hex(8)) # equalise timing for unknown usernames + + +def _sha(s: str) -> str: + return hashlib.sha256(s.encode()).hexdigest() + + +def check_password(pw: str): + if len(pw) < MIN_PASSWORD: + raise HTTPException(422, f"password must be at least {MIN_PASSWORD} characters") + + +def check_username(u: str): + if not (2 <= len(u) <= 64) or not all(c.isalnum() or c in "._-@" for c in u): + raise HTTPException(422, "username must be 2-64 characters: letters, digits, . _ - @") + + +# ------------------------------------------------------------------ users + +def _user_out(row) -> dict: + return dict(id=row["id"], username=row["username"], role=row["role"], disabled=bool(row["disabled"]), + created_at=row["created_at"], last_login=row["last_login"]) + + +def create_user(username: str, password: str, role: str) -> dict: + check_username(username) + check_password(password) + if role not in ROLES: + raise HTTPException(422, f"role must be one of {ROLES}") + try: + with db() as con: + cur = con.execute("INSERT INTO users (username, password_hash, role, created_at) VALUES (?,?,?,?)", + (username, hash_password(password), role, int(time.time()))) + row = con.execute("SELECT * FROM users WHERE id=?", (cur.lastrowid,)).fetchone() + except sqlite3.IntegrityError: + raise HTTPException(409, f"username '{username}' already exists") + return _user_out(row) + + +def list_users() -> list[dict]: + with db() as con: + rows = con.execute("SELECT * FROM users ORDER BY id").fetchall() + counts = dict(con.execute("SELECT user_id, COUNT(*) FROM api_keys GROUP BY user_id").fetchall()) + return [_user_out(r) | {"api_keys": counts.get(r["id"], 0)} for r in rows] + + +def get_user(uid: int) -> dict: + with db() as con: + row = con.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone() + if not row: + raise HTTPException(404, "user not found") + return _user_out(row) + + +def _active_admins(con, excluding: int) -> int: + return con.execute("SELECT COUNT(*) FROM users WHERE role='admin' AND disabled=0 AND id<>?", (excluding,)).fetchone()[0] + + +def update_user(uid: int, actor: dict, role: str | None = None, disabled: bool | None = None, + password: str | None = None) -> dict: + target = get_user(uid) + with db() as con: + removing_admin = target["role"] == "admin" and not target["disabled"] and ( + (role is not None and role != "admin") or disabled is True) + if removing_admin and _active_admins(con, uid) == 0: + raise HTTPException(409, "cannot demote or disable the last active admin") + if uid == actor["id"] and (disabled is True or (role is not None and role != actor["role"])): + raise HTTPException(409, "you cannot disable yourself or change your own role") + if role is not None: + if role not in ROLES: + raise HTTPException(422, f"role must be one of {ROLES}") + con.execute("UPDATE users SET role=? WHERE id=?", (role, uid)) + if disabled is not None: + con.execute("UPDATE users SET disabled=? WHERE id=?", (int(disabled), uid)) + if disabled: + con.execute("DELETE FROM sessions WHERE user_id=?", (uid,)) + if password is not None: + check_password(password) + con.execute("UPDATE users SET password_hash=? WHERE id=?", (hash_password(password), uid)) + con.execute("DELETE FROM sessions WHERE user_id=?", (uid,)) + return get_user(uid) + + +def delete_user(uid: int, actor: dict): + target = get_user(uid) + if uid == actor["id"]: + raise HTTPException(409, "you cannot delete your own account") + with db() as con: + if target["role"] == "admin" and _active_admins(con, uid) == 0: + raise HTTPException(409, "cannot delete the last active admin") + con.execute("DELETE FROM users WHERE id=?", (uid,)) + + +def change_own_password(user: dict, current: str, new: str, keep_token_hash: str | None): + with db() as con: + row = con.execute("SELECT password_hash FROM users WHERE id=?", (user["id"],)).fetchone() + if not verify_password(current, row["password_hash"]): + raise HTTPException(403, "current password is incorrect") + check_password(new) + with db() as con: + con.execute("UPDATE users SET password_hash=? WHERE id=?", (hash_password(new), user["id"])) + # sign out other sessions, keep this one + con.execute("DELETE FROM sessions WHERE user_id=? AND token_hash<>?", (user["id"], keep_token_hash or "")) + + +# ------------------------------------------------------------------ login throttling + +_fails: dict[str, list[float]] = {} +MAX_FAILS, WINDOW = 5, 300 + + +def _throttle_key(username: str, ip: str) -> str: + return f"{username.lower()}|{ip}" + + +def check_throttle(username: str, ip: str): + now = time.time() + hits = [t for t in _fails.get(_throttle_key(username, ip), []) if now - t < WINDOW] + _fails[_throttle_key(username, ip)] = hits + if len(hits) >= MAX_FAILS: + raise HTTPException(429, f"too many failed sign-in attempts; try again in {int(WINDOW - (now - hits[0])) + 1} s") + + +def record_fail(username: str, ip: str): + _fails.setdefault(_throttle_key(username, ip), []).append(time.time()) + + +# ------------------------------------------------------------------ sessions + +def login(username: str, password: str, ip: str) -> tuple[str, dict]: + check_throttle(username, ip) + with db() as con: + row = con.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone() + ok = verify_password(password, row["password_hash"] if row else _DUMMY_HASH) + if not row or not ok or row["disabled"]: + record_fail(username, ip) + raise HTTPException(401, "invalid username or password") + _fails.pop(_throttle_key(username, ip), None) + token = secrets.token_urlsafe(32) + now = int(time.time()) + with db() as con: + con.execute("INSERT INTO sessions VALUES (?,?,?,?)", (_sha(token), row["id"], now, now + int(SESSION_HOURS * 3600))) + con.execute("UPDATE users SET last_login=? WHERE id=?", (now, row["id"])) + return token, _user_out(row) + + +def logout(token: str | None): + if token: + with db() as con: + con.execute("DELETE FROM sessions WHERE token_hash=?", (_sha(token),)) + + +def _session_user(token: str) -> dict | None: + with db() as con: + row = con.execute( + "SELECT u.* FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=? AND s.expires_at>? AND u.disabled=0", + (_sha(token), int(time.time()))).fetchone() + return _user_out(row) if row else None + + +# ------------------------------------------------------------------ API keys + +def _key_out(row, owner: str | None = None) -> dict: + d = dict(id=row["id"], user_id=row["user_id"], name=row["name"], prefix=f"cmk_{row['prefix']}_…", + created_at=row["created_at"], expires_at=row["expires_at"], last_used=row["last_used"], + expired=bool(row["expires_at"] and row["expires_at"] < time.time())) + if owner is not None: + d["username"] = owner + return d + + +def create_key(user_id: int, name: str, expires_days: int | None) -> tuple[str, dict]: + name = (name or "").strip()[:100] or "API key" + get_user(user_id) + prefix = secrets.token_hex(4) + secret = secrets.token_urlsafe(32) + key = f"cmk_{prefix}_{secret}" + now = int(time.time()) + exp = now + expires_days * 86400 if expires_days else None + with db() as con: + cur = con.execute("INSERT INTO api_keys (user_id, name, prefix, key_hash, created_at, expires_at) VALUES (?,?,?,?,?,?)", + (user_id, name, prefix, _sha(key), now, exp)) + row = con.execute("SELECT * FROM api_keys WHERE id=?", (cur.lastrowid,)).fetchone() + return key, _key_out(row) + + +def list_keys(user_id: int | None = None) -> list[dict]: + q = "SELECT k.*, u.username FROM api_keys k JOIN users u ON u.id=k.user_id" + args: tuple = () + if user_id is not None: + q += " WHERE k.user_id=?" + args = (user_id,) + with db() as con: + rows = con.execute(q + " ORDER BY k.id", args).fetchall() + return [_key_out(r, r["username"]) for r in rows] + + +def delete_key(key_id: int, actor: dict): + with db() as con: + row = con.execute("SELECT user_id FROM api_keys WHERE id=?", (key_id,)).fetchone() + if not row or (actor["role"] != "admin" and row["user_id"] != actor["id"]): + raise HTTPException(404, "API key not found") + con.execute("DELETE FROM api_keys WHERE id=?", (key_id,)) + + +def _key_user(key: str) -> dict | None: + parts = key.split("_") + if len(parts) < 3 or parts[0] != "cmk": + return None + now = int(time.time()) + with db() as con: + row = con.execute( + "SELECT k.id AS kid, k.key_hash, k.expires_at, u.* FROM api_keys k JOIN users u ON u.id=k.user_id " + "WHERE k.prefix=? AND u.disabled=0", (parts[1],)).fetchone() + if not row or not hmac.compare_digest(row["key_hash"], _sha(key)) or (row["expires_at"] and row["expires_at"] < now): + return None + con.execute("UPDATE api_keys SET last_used=? WHERE id=?", (now, row["kid"])) + return _user_out(row) + + +# ------------------------------------------------------------------ FastAPI dependencies + +_key_header = APIKeyHeader(name="X-API-Key", auto_error=False, description="API key created under Account → API keys") +_bearer = HTTPBearer(auto_error=False, description="Same API key, sent as Authorization: Bearer ") + + +def current_user(request: Request, x_api_key: str | None = Depends(_key_header), + bearer: HTTPAuthorizationCredentials | None = Depends(_bearer)) -> dict: + key = x_api_key or (bearer.credentials.strip() if bearer else None) + if key: + user = _key_user(key) + if not user: + raise HTTPException(401, "invalid, expired or revoked API key", headers={"WWW-Authenticate": "Bearer"}) + user["auth"] = "api_key" + return user + token = request.cookies.get(SESSION_COOKIE) + user = _session_user(token) if token else None + if not user: + raise HTTPException(401, "sign in or send an API key (header X-API-Key)", headers={"WWW-Authenticate": "Bearer"}) + if request.method not in ("GET", "HEAD", "OPTIONS") and request.headers.get(CSRF_HEADER) != "1": + raise HTTPException(403, f"missing {CSRF_HEADER} header on a browser-session request") + user["auth"] = "session" + user["token_hash"] = _sha(token) + return user + + +def require_admin(user: dict = Depends(current_user)) -> dict: + if user["role"] != "admin": + raise HTTPException(403, "admin role required") + return user diff --git a/app/data/__init__.py b/app/data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/data/cities.py b/app/data/cities.py new file mode 100644 index 0000000..7922193 --- /dev/null +++ b/app/data/cities.py @@ -0,0 +1,49 @@ +"""Latency target cities: (id, name, country, lat, lon, extra_ms). + +extra_ms is a last-mile / peering penalty added to the physical estimate for +markets where traffic commonly takes indirect routes (e.g. West Africa via +Europe, Bangladesh via Singapore/India transit). +""" + +CITIES = [ + ("mex", "Mexico City", "MX", 19.43, -99.13, 5), + ("nyc", "New York City", "US", 40.71, -74.01, 0), + ("lax", "Los Angeles", "US", 34.05, -118.24, 0), + ("chi", "Chicago", "US", 41.88, -87.63, 0), + ("dfw", "Dallas/Fort Worth", "US", 32.90, -97.04, 0), + ("hou", "Houston", "US", 29.76, -95.37, 0), + ("tor", "Toronto", "CA", 43.65, -79.38, 0), + ("atl", "Atlanta", "US", 33.75, -84.39, 0), + ("was", "Washington DC", "US", 38.91, -77.04, 0), + ("mia", "Miami", "US", 25.76, -80.19, 0), + ("sao", "Sao Paulo", "BR", -23.55, -46.63, 0), + ("bue", "Buenos Aires", "AR", -34.60, -58.38, 5), + ("rio", "Rio de Janeiro", "BR", -22.91, -43.17, 0), + ("bog", "Bogota", "CO", 4.71, -74.07, 5), + ("lim", "Lima", "PE", -12.05, -77.04, 5), + ("scl", "Santiago", "CL", -33.45, -70.67, 0), + ("tyo", "Tokyo", "JP", 35.68, 139.69, 0), + ("jkt", "Jakarta", "ID", -6.21, 106.85, 5), + ("del", "Delhi", "IN", 28.61, 77.21, 5), + ("sha", "Shanghai", "CN", 31.23, 121.47, 0), # cross-border penalty applied in latency.py + ("mnl", "Manila", "PH", 14.60, 120.98, 8), + ("dac", "Dhaka", "BD", 23.81, 90.41, 15), + ("sel", "Seoul", "KR", 37.57, 126.98, 0), + ("syd", "Sydney", "AU", -33.87, 151.21, 0), + ("per", "Perth", "AU", -31.95, 115.86, 0), + ("mel", "Melbourne", "AU", -37.81, 144.96, 0), + ("tpe", "Taipei", "TW", 25.03, 121.57, 0), + ("cai", "Cairo", "EG", 30.04, 31.24, 10), + ("los", "Lagos", "NG", 6.52, 3.38, 20), + ("jnb", "Johannesburg", "ZA", -26.20, 28.05, 0), + ("par", "Paris", "FR", 48.86, 2.35, 0), + ("mad", "Madrid", "ES", 40.42, -3.70, 0), + ("muc", "Munich", "DE", 48.14, 11.58, 0), + ("bcn", "Barcelona", "ES", 41.39, 2.17, 0), + ("mil", "Milan", "IT", 45.46, 9.19, 0), + ("ber", "Berlin", "DE", 52.52, 13.40, 0), + ("rom", "Rome", "IT", 41.90, 12.50, 0), + ("ath", "Athens", "GR", 37.98, 23.73, 3), + ("rtm", "Rotterdam", "NL", 51.92, 4.48, 0), + ("jrs", "Jerusalem", "IL", 31.77, 35.21, 0), +] diff --git a/app/data/providers.py b/app/data/providers.py new file mode 100644 index 0000000..fbdd586 --- /dev/null +++ b/app/data/providers.py @@ -0,0 +1,705 @@ +"""Cloud provider catalog (static baseline). + +Prices are USD/month list prices (on-demand / monthly, Linux, no commitment) +for each plan's *baseline* region; other regions apply `mult`. Where a live +adapter exists (see app/live.py) the live API data replaces these numbers. + +price_confidence: + high - checked against provider API/pricing page during catalog build + medium - from published price lists; regional multipliers approximate + low - estimate; provider has no public machine-readable pricing, verify + before quoting + +Compliance values: "yes" (attested/certified for IaaS compute, BAA available +for HIPAA), "partial" (only some products/regions or self-declared), "no" +(no attestation found). GDPR "yes" means a DPA is offered and EU hosting is +available. Always confirm scope on the provider's compliance page. +""" + +NA, SA, EU, AS, AF, AU = "North America", "South America", "Europe", "Asia", "Africa", "Australia" +CONTINENTS = [NA, EU, AS, AU, AF, SA] + +H = 730 # hours per month + + +def _r(code, label, cc, cont, lat, lon, mult=1.0, ping=None, tags=None): + return dict(code=code, label=label, country=cc, continent=cont, lat=lat, lon=lon, + mult=mult, ping_host=ping, tags=tags) + + +def _p(model, vcpu, ram, disk, price, cpu="shared", arch="x86_64", tag=None, note=""): + return dict(model=model, vcpu=vcpu, ram_gb=ram, disk_gb=disk, price=round(price, 2), + cpu_type=cpu, arch=arch, tag=tag, note=note) + + +PROVIDERS = [ + # ------------------------------------------------------------------ AWS + dict( + id="aws", name="Amazon Web Services (EC2)", + website="https://aws.amazon.com/ec2/", + pricing_url="https://aws.amazon.com/ec2/pricing/on-demand/", + api_docs="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Welcome.html", + pricing_api="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html", + compliance_url="https://aws.amazon.com/compliance/services-in-scope/", + price_confidence="high", + compliance=dict(hipaa="yes", soc2="yes", pci="yes", gdpr="yes"), + compliance_note="EC2 and EBS are HIPAA-eligible (sign the AWS BAA in AWS Artifact), SOC 1/2/3, PCI DSS Level 1.", + storage=dict(kind="block", price_gb=0.08, name="EBS gp3"), + ipv4_monthly=3.65, + egress=dict(included_gb=100, per_gb=0.09), + smtp25="on request", + live=None, + plans=[ + _p("t3.small", 2, 2, 0, 0.0208 * H, "burstable"), + _p("t3.medium", 2, 4, 0, 0.0416 * H, "burstable"), + _p("t3.large", 2, 8, 0, 0.0832 * H, "burstable"), + _p("t3.xlarge", 4, 16, 0, 0.1664 * H, "burstable"), + _p("t3.2xlarge", 8, 32, 0, 0.3328 * H, "burstable"), + _p("t4g.medium", 2, 4, 0, 0.0336 * H, "burstable", "arm64"), + _p("t4g.large", 2, 8, 0, 0.0672 * H, "burstable", "arm64"), + _p("t4g.xlarge", 4, 16, 0, 0.1344 * H, "burstable", "arm64"), + _p("t4g.2xlarge", 8, 32, 0, 0.2688 * H, "burstable", "arm64"), + _p("m7i.large", 2, 8, 0, 0.1008 * H, "dedicated"), + _p("m7i.xlarge", 4, 16, 0, 0.2016 * H, "dedicated"), + _p("m7i.2xlarge", 8, 32, 0, 0.4032 * H, "dedicated"), + _p("c7i.xlarge", 4, 8, 0, 0.1785 * H, "dedicated"), + _p("c7i.2xlarge", 8, 16, 0, 0.357 * H, "dedicated"), + _p("r7i.large", 2, 16, 0, 0.1323 * H, "dedicated"), + _p("r7i.xlarge", 4, 32, 0, 0.2646 * H, "dedicated"), + ], + regions=[ + _r("us-east-1", "N. Virginia", "US", NA, 38.95, -77.45, 1.0, "ec2.us-east-1.amazonaws.com"), + _r("us-east-2", "Ohio", "US", NA, 39.96, -83.0, 1.0, "ec2.us-east-2.amazonaws.com"), + _r("us-west-1", "N. California", "US", NA, 37.35, -121.96, 1.19, "ec2.us-west-1.amazonaws.com"), + _r("us-west-2", "Oregon", "US", NA, 45.84, -119.7, 1.0, "ec2.us-west-2.amazonaws.com"), + _r("ca-central-1", "Montreal", "CA", NA, 45.5, -73.57, 1.1, "ec2.ca-central-1.amazonaws.com"), + _r("ca-west-1", "Calgary", "CA", NA, 51.05, -114.07, 1.1, "ec2.ca-west-1.amazonaws.com"), + _r("mx-central-1", "Queretaro", "MX", NA, 20.59, -100.39, 1.15, "ec2.mx-central-1.amazonaws.com"), + _r("sa-east-1", "Sao Paulo", "BR", SA, -23.55, -46.63, 1.6, "ec2.sa-east-1.amazonaws.com"), + _r("eu-central-1", "Frankfurt", "DE", EU, 50.11, 8.68, 1.16, "ec2.eu-central-1.amazonaws.com"), + _r("eu-west-1", "Ireland", "IE", EU, 53.35, -6.26, 1.09, "ec2.eu-west-1.amazonaws.com"), + _r("eu-west-2", "London", "GB", EU, 51.51, -0.13, 1.13, "ec2.eu-west-2.amazonaws.com"), + _r("eu-west-3", "Paris", "FR", EU, 48.86, 2.35, 1.14, "ec2.eu-west-3.amazonaws.com"), + _r("eu-south-1", "Milan", "IT", EU, 45.46, 9.19, 1.17, "ec2.eu-south-1.amazonaws.com"), + _r("eu-south-2", "Spain (Aragon)", "ES", EU, 41.65, -0.88, 1.12, "ec2.eu-south-2.amazonaws.com"), + _r("eu-central-2", "Zurich", "CH", EU, 47.37, 8.54, 1.27, "ec2.eu-central-2.amazonaws.com"), + _r("eu-north-1", "Stockholm", "SE", EU, 59.33, 18.07, 1.04, "ec2.eu-north-1.amazonaws.com"), + _r("il-central-1", "Tel Aviv", "IL", AS, 32.08, 34.78, 1.2, "ec2.il-central-1.amazonaws.com"), + _r("me-central-1", "UAE", "AE", AS, 25.2, 55.27, 1.2, "ec2.me-central-1.amazonaws.com"), + _r("af-south-1", "Cape Town", "ZA", AF, -33.92, 18.42, 1.3, "ec2.af-south-1.amazonaws.com"), + _r("ap-northeast-1", "Tokyo", "JP", AS, 35.68, 139.69, 1.25, "ec2.ap-northeast-1.amazonaws.com"), + _r("ap-northeast-2", "Seoul", "KR", AS, 37.57, 126.98, 1.2, "ec2.ap-northeast-2.amazonaws.com"), + _r("ap-east-2", "Taipei", "TW", AS, 25.03, 121.57, 1.25, "ec2.ap-east-2.amazonaws.com"), + _r("ap-east-1", "Hong Kong", "HK", AS, 22.32, 114.17, 1.31, "ec2.ap-east-1.amazonaws.com"), + _r("ap-southeast-1", "Singapore", "SG", AS, 1.35, 103.82, 1.2, "ec2.ap-southeast-1.amazonaws.com"), + _r("ap-southeast-3", "Jakarta", "ID", AS, -6.21, 106.85, 1.2, "ec2.ap-southeast-3.amazonaws.com"), + _r("ap-southeast-5", "Malaysia", "MY", AS, 3.14, 101.69, 1.15, "ec2.ap-southeast-5.amazonaws.com"), + _r("ap-south-1", "Mumbai", "IN", AS, 19.08, 72.88, 1.05, "ec2.ap-south-1.amazonaws.com"), + _r("ap-south-2", "Hyderabad", "IN", AS, 17.39, 78.49, 1.05, "ec2.ap-south-2.amazonaws.com"), + _r("ap-southeast-2", "Sydney", "AU", AU, -33.87, 151.21, 1.24, "ec2.ap-southeast-2.amazonaws.com"), + _r("ap-southeast-4", "Melbourne", "AU", AU, -37.81, 144.96, 1.24, "ec2.ap-southeast-4.amazonaws.com"), + ], + ), + # ---------------------------------------------------------------- Azure + dict( + id="azure", name="Microsoft Azure", + website="https://azure.microsoft.com/products/virtual-machines/", + pricing_url="https://azure.microsoft.com/pricing/details/virtual-machines/linux/", + api_docs="https://learn.microsoft.com/rest/api/compute/virtual-machines", + pricing_api="https://learn.microsoft.com/rest/api/cost-management/retail-prices/azure-retail-prices", + compliance_url="https://learn.microsoft.com/azure/compliance/", + price_confidence="high", + compliance=dict(hipaa="yes", soc2="yes", pci="yes", gdpr="yes"), + compliance_note="BAA included in Microsoft Product Terms; SOC 1/2/3; PCI DSS Level 1.", + storage=dict(kind="block", price_gb=0.075, name="Standard SSD managed disk (approx. per GB)"), + ipv4_monthly=3.65, + egress=dict(included_gb=100, per_gb=0.087), + smtp25="blocked", + live="azure", + plans=[ + _p("Standard_B2s", 2, 4, 0, 0.0416 * H, "burstable"), + _p("Standard_B2ms", 2, 8, 0, 0.0832 * H, "burstable"), + _p("Standard_B4ms", 4, 16, 0, 0.166 * H, "burstable"), + _p("Standard_B8ms", 8, 32, 0, 0.333 * H, "burstable"), + _p("Standard_D2s_v5", 2, 8, 0, 0.096 * H, "dedicated"), + _p("Standard_D4s_v5", 4, 16, 0, 0.192 * H, "dedicated"), + _p("Standard_D8s_v5", 8, 32, 0, 0.384 * H, "dedicated"), + _p("Standard_E2s_v5", 2, 16, 0, 0.126 * H, "dedicated"), + _p("Standard_E4s_v5", 4, 32, 0, 0.252 * H, "dedicated"), + _p("Standard_F4s_v2", 4, 8, 0, 0.169 * H, "dedicated"), + _p("Standard_F8s_v2", 8, 16, 0, 0.338 * H, "dedicated"), + ], + regions=[ + _r("eastus", "Virginia", "US", NA, 36.67, -78.39, 1.0), + _r("centralus", "Iowa", "US", NA, 41.59, -93.62, 1.2), + _r("southcentralus", "Texas", "US", NA, 29.42, -98.49, 1.2), + _r("westus2", "Washington", "US", NA, 47.23, -119.85, 1.0), + _r("westus", "California", "US", NA, 37.78, -122.42, 1.19), + _r("canadacentral", "Toronto", "CA", NA, 43.65, -79.38, 1.12), + _r("mexicocentral", "Queretaro", "MX", NA, 20.59, -100.39, 1.1), + _r("brazilsouth", "Sao Paulo", "BR", SA, -23.55, -46.63, 1.62), + _r("chilecentral", "Santiago", "CL", SA, -33.45, -70.67, 1.4), + _r("westeurope", "Netherlands", "NL", EU, 52.37, 4.9, 1.15), + _r("northeurope", "Ireland", "IE", EU, 53.35, -6.26, 1.08), + _r("uksouth", "London", "GB", EU, 51.51, -0.13, 1.13), + _r("francecentral", "Paris", "FR", EU, 48.86, 2.35, 1.13), + _r("germanywestcentral", "Frankfurt", "DE", EU, 50.11, 8.68, 1.15), + _r("spaincentral", "Madrid", "ES", EU, 40.42, -3.7, 1.1), + _r("italynorth", "Milan", "IT", EU, 45.46, 9.19, 1.15), + _r("polandcentral", "Warsaw", "PL", EU, 52.23, 21.01, 1.15), + _r("israelcentral", "Israel", "IL", AS, 32.08, 34.78, 1.15), + _r("uaenorth", "Dubai", "AE", AS, 25.2, 55.27, 1.2), + _r("southafricanorth", "Johannesburg", "ZA", AF, -26.2, 28.05, 1.3), + _r("japaneast", "Tokyo", "JP", AS, 35.68, 139.69, 1.31), + _r("koreacentral", "Seoul", "KR", AS, 37.57, 126.98, 1.25), + _r("eastasia", "Hong Kong", "HK", AS, 22.32, 114.17, 1.4), + _r("southeastasia", "Singapore", "SG", AS, 1.35, 103.82, 1.27), + _r("indonesiacentral", "Jakarta", "ID", AS, -6.21, 106.85, 1.14), + _r("malaysiawest", "Kuala Lumpur", "MY", AS, 3.14, 101.69, 1.14), + _r("centralindia", "Pune", "IN", AS, 18.52, 73.86, 1.08), + _r("australiaeast", "Sydney", "AU", AU, -33.87, 151.21, 1.27), + _r("australiasoutheast", "Melbourne", "AU", AU, -37.81, 144.96, 1.27), + ], + ), + # ------------------------------------------------------------------ GCP + dict( + id="gcp", name="Google Cloud (Compute Engine)", + website="https://cloud.google.com/compute", + pricing_url="https://cloud.google.com/compute/vm-instance-pricing", + api_docs="https://cloud.google.com/compute/docs/reference/rest/v1", + pricing_api="https://cloud.google.com/billing/docs/reference/rest/v1/services.skus/list", + compliance_url="https://cloud.google.com/security/compliance", + price_confidence="medium", + compliance=dict(hipaa="yes", soc2="yes", pci="yes", gdpr="yes"), + compliance_note="Compute Engine covered by Google Cloud BAA; SOC 1/2/3; PCI DSS.", + storage=dict(kind="block", price_gb=0.10, name="pd-balanced"), + ipv4_monthly=3.65, + egress=dict(included_gb=0, per_gb=0.12), + smtp25="blocked", + live=None, + plans=[ + _p("e2-medium", 2, 4, 0, 24.46, "burstable"), + _p("e2-standard-2", 2, 8, 0, 48.92), + _p("e2-standard-4", 4, 16, 0, 97.84), + _p("e2-standard-8", 8, 32, 0, 195.67), + _p("e2-highmem-2", 2, 16, 0, 66.01), + _p("e2-highmem-4", 4, 32, 0, 132.02), + _p("e2-highcpu-4", 4, 4, 0, 72.24), + _p("e2-highcpu-8", 8, 8, 0, 144.48), + _p("n2-standard-2", 2, 8, 0, 70.90, "dedicated"), + _p("n2-standard-4", 4, 16, 0, 141.80, "dedicated"), + _p("n2-standard-8", 8, 32, 0, 283.60, "dedicated"), + _p("t2a-standard-2", 2, 8, 0, 56.21, "dedicated", "arm64"), + _p("t2a-standard-4", 4, 16, 0, 112.42, "dedicated", "arm64"), + ], + regions=[ + _r("us-central1", "Iowa", "US", NA, 41.26, -95.86, 1.0), + _r("us-east1", "South Carolina", "US", NA, 33.2, -80.01, 1.0), + _r("us-east4", "N. Virginia", "US", NA, 39.04, -77.49, 1.13), + _r("us-south1", "Dallas", "US", NA, 32.78, -96.8, 1.18), + _r("us-west1", "Oregon", "US", NA, 45.6, -121.18, 1.0), + _r("us-west2", "Los Angeles", "US", NA, 34.05, -118.24, 1.2), + _r("northamerica-northeast2", "Toronto", "CA", NA, 43.65, -79.38, 1.1), + _r("northamerica-south1", "Queretaro", "MX", NA, 20.59, -100.39, 1.15), + _r("southamerica-east1", "Sao Paulo", "BR", SA, -23.55, -46.63, 1.59), + _r("southamerica-west1", "Santiago", "CL", SA, -33.45, -70.67, 1.28), + _r("europe-west1", "Belgium", "BE", EU, 50.45, 3.82, 1.1), + _r("europe-west2", "London", "GB", EU, 51.51, -0.13, 1.21), + _r("europe-west3", "Frankfurt", "DE", EU, 50.11, 8.68, 1.2), + _r("europe-west4", "Netherlands", "NL", EU, 53.44, 6.84, 1.1), + _r("europe-west8", "Milan", "IT", EU, 45.46, 9.19, 1.2), + _r("europe-west9", "Paris", "FR", EU, 48.86, 2.35, 1.16), + _r("europe-west10", "Berlin", "DE", EU, 52.52, 13.4, 1.24), + _r("europe-west12", "Turin", "IT", EU, 45.07, 7.69, 1.25), + _r("europe-southwest1", "Madrid", "ES", EU, 40.42, -3.7, 1.18), + _r("me-west1", "Tel Aviv", "IL", AS, 32.08, 34.78, 1.18), + _r("africa-south1", "Johannesburg", "ZA", AF, -26.2, 28.05, 1.27), + _r("asia-northeast1", "Tokyo", "JP", AS, 35.68, 139.69, 1.29), + _r("asia-northeast3", "Seoul", "KR", AS, 37.57, 126.98, 1.29), + _r("asia-east1", "Changhua, Taiwan", "TW", AS, 24.07, 120.54, 1.16), + _r("asia-east2", "Hong Kong", "HK", AS, 22.32, 114.17, 1.4), + _r("asia-southeast1", "Singapore", "SG", AS, 1.35, 103.82, 1.23), + _r("asia-southeast2", "Jakarta", "ID", AS, -6.21, 106.85, 1.33), + _r("asia-south1", "Mumbai", "IN", AS, 19.08, 72.88, 1.2), + _r("asia-south2", "Delhi", "IN", AS, 28.61, 77.21, 1.2), + _r("australia-southeast1", "Sydney", "AU", AU, -33.87, 151.21, 1.38), + _r("australia-southeast2", "Melbourne", "AU", AU, -37.81, 144.96, 1.38), + ], + ), + # ------------------------------------------------------- Oracle Cloud + dict( + id="oci", name="Oracle Cloud Infrastructure", + website="https://www.oracle.com/cloud/compute/", + pricing_url="https://www.oracle.com/cloud/price-list/", + api_docs="https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/", + pricing_api="https://docs.oracle.com/en-us/iaas/Content/Billing/Concepts/pricingoverview.htm", + compliance_url="https://www.oracle.com/corporate/cloud-compliance/", + price_confidence="medium", + compliance=dict(hipaa="yes", soc2="yes", pci="yes", gdpr="yes"), + compliance_note="Same price in every commercial region. 10 TB/month egress free. BAA available.", + storage=dict(kind="block", price_gb=0.0425, name="Block Volume (balanced, 10 VPU)"), + ipv4_monthly=0.0, + egress=dict(included_gb=10240, per_gb=0.0085), + smtp25="on request", + live=None, + # E5.Flex: $0.03/OCPU-h (1 OCPU = 2 vCPU) + $0.002/GB-h + plans=[ + _p(f"VM.Standard.E5.Flex ({o} OCPU/{m} GB)", o * 2, m, 0, (o * 0.03 + m * 0.002) * H, "dedicated") + for o, m in [(1, 4), (1, 8), (1, 16), (2, 8), (2, 16), (2, 32), (4, 16), (4, 32), (4, 64)] + ] + [ + _p(f"VM.Standard.A1.Flex ({o} OCPU/{m} GB)", o, m, 0, (o * 0.01 + m * 0.0015) * H, "dedicated", "arm64") + for o, m in [(2, 8), (2, 12), (4, 16), (4, 24), (8, 32)] + ], + regions=[ + _r("us-ashburn-1", "Ashburn", "US", NA, 39.04, -77.49), + _r("us-chicago-1", "Chicago", "US", NA, 41.88, -87.63), + _r("us-phoenix-1", "Phoenix", "US", NA, 33.45, -112.07), + _r("us-sanjose-1", "San Jose", "US", NA, 37.34, -121.89), + _r("ca-toronto-1", "Toronto", "CA", NA, 43.65, -79.38), + _r("ca-montreal-1", "Montreal", "CA", NA, 45.5, -73.57), + _r("mx-queretaro-1", "Queretaro", "MX", NA, 20.59, -100.39), + _r("mx-monterrey-1", "Monterrey", "MX", NA, 25.69, -100.32), + _r("sa-saopaulo-1", "Sao Paulo", "BR", SA, -23.55, -46.63), + _r("sa-vinhedo-1", "Vinhedo", "BR", SA, -23.03, -46.98), + _r("sa-santiago-1", "Santiago", "CL", SA, -33.45, -70.67), + _r("sa-valparaiso-1", "Valparaiso", "CL", SA, -33.05, -71.62), + _r("sa-bogota-1", "Bogota", "CO", SA, 4.71, -74.07), + _r("eu-frankfurt-1", "Frankfurt", "DE", EU, 50.11, 8.68), + _r("eu-paris-1", "Paris", "FR", EU, 48.86, 2.35), + _r("eu-marseille-1", "Marseille", "FR", EU, 43.3, 5.37), + _r("eu-madrid-1", "Madrid", "ES", EU, 40.42, -3.7), + _r("eu-milan-1", "Milan", "IT", EU, 45.46, 9.19), + _r("eu-amsterdam-1", "Amsterdam", "NL", EU, 52.37, 4.9), + _r("uk-london-1", "London", "GB", EU, 51.51, -0.13), + _r("eu-stockholm-1", "Stockholm", "SE", EU, 59.33, 18.07), + _r("eu-zurich-1", "Zurich", "CH", EU, 47.37, 8.54), + _r("il-jerusalem-1", "Jerusalem", "IL", AS, 31.77, 35.21), + _r("me-dubai-1", "Dubai", "AE", AS, 25.2, 55.27), + _r("af-johannesburg-1", "Johannesburg", "ZA", AF, -26.2, 28.05), + _r("ap-tokyo-1", "Tokyo", "JP", AS, 35.68, 139.69), + _r("ap-osaka-1", "Osaka", "JP", AS, 34.69, 135.5), + _r("ap-seoul-1", "Seoul", "KR", AS, 37.57, 126.98), + _r("ap-chuncheon-1", "Chuncheon", "KR", AS, 37.88, 127.73), + _r("ap-singapore-1", "Singapore", "SG", AS, 1.35, 103.82), + _r("ap-mumbai-1", "Mumbai", "IN", AS, 19.08, 72.88), + _r("ap-hyderabad-1", "Hyderabad", "IN", AS, 17.39, 78.49), + _r("ap-sydney-1", "Sydney", "AU", AU, -33.87, 151.21), + _r("ap-melbourne-1", "Melbourne", "AU", AU, -37.81, 144.96), + ], + ), + # --------------------------------------------------------- Alibaba Cloud + dict( + id="alibaba", name="Alibaba Cloud (ECS)", + website="https://www.alibabacloud.com/product/ecs", + pricing_url="https://www.alibabacloud.com/product/ecs/pricing", + api_docs="https://www.alibabacloud.com/help/en/ecs/developer-reference/api-ecs-2014-05-26-overview", + pricing_api="https://www.alibabacloud.com/help/en/bss-openapi/", + compliance_url="https://www.alibabacloud.com/trust-center", + price_confidence="low", + compliance=dict(hipaa="partial", soc2="yes", pci="yes", gdpr="yes"), + compliance_note="SOC 1/2/3, PCI DSS for international regions. HIPAA: self-assessed, BAA not generally offered. Mainland China regions need an ICP filing for public websites.", + storage=dict(kind="block", price_gb=0.05, name="ESSD Entry"), + ipv4_monthly=0.0, + egress=dict(included_gb=0, per_gb=0.08), + smtp25="blocked", + live=None, + plans=[ + _p("ecs.e-c1m2.large", 2, 4, 0, 21.0, "shared"), + _p("ecs.e-c1m4.large", 2, 8, 0, 36.0, "shared"), + _p("ecs.e-c1m4.xlarge", 4, 16, 0, 72.0, "shared"), + _p("ecs.e-c1m4.2xlarge", 8, 32, 0, 144.0, "shared"), + _p("ecs.g7.large", 2, 8, 0, 69.0, "dedicated"), + _p("ecs.g7.xlarge", 4, 16, 0, 138.0, "dedicated"), + _p("ecs.g7.2xlarge", 8, 32, 0, 276.0, "dedicated"), + _p("ecs.r7.large", 2, 16, 0, 92.0, "dedicated"), + ], + regions=[ + _r("us-east-1", "Virginia", "US", NA, 38.95, -77.45, 1.0), + _r("us-west-1", "Silicon Valley", "US", NA, 37.35, -121.96, 1.0), + _r("na-south-1", "Mexico (Queretaro)", "MX", NA, 20.59, -100.39, 1.1), + _r("eu-central-1", "Frankfurt", "DE", EU, 50.11, 8.68, 1.1), + _r("eu-west-1", "London", "GB", EU, 51.51, -0.13, 1.1), + _r("me-east-1", "Dubai", "AE", AS, 25.2, 55.27, 1.2), + _r("cn-shanghai", "Shanghai (mainland, ICP)", "CN", AS, 31.23, 121.47, 0.8), + _r("cn-hangzhou", "Hangzhou (mainland, ICP)", "CN", AS, 30.27, 120.15, 0.8), + _r("cn-hongkong", "Hong Kong", "HK", AS, 22.32, 114.17, 1.15), + _r("ap-northeast-1", "Tokyo", "JP", AS, 35.68, 139.69, 1.15), + _r("ap-northeast-2", "Seoul", "KR", AS, 37.57, 126.98, 1.15), + _r("ap-southeast-1", "Singapore", "SG", AS, 1.35, 103.82, 1.1), + _r("ap-southeast-3", "Kuala Lumpur", "MY", AS, 3.14, 101.69, 1.0), + _r("ap-southeast-5", "Jakarta", "ID", AS, -6.21, 106.85, 1.05), + _r("ap-southeast-6", "Manila", "PH", AS, 14.6, 120.98, 1.05), + _r("ap-southeast-7", "Bangkok", "TH", AS, 13.76, 100.5, 1.05), + ], + ), + # --------------------------------------------------------- DigitalOcean + dict( + id="digitalocean", name="DigitalOcean", + website="https://www.digitalocean.com/products/droplets", + pricing_url="https://www.digitalocean.com/pricing/droplets", + api_docs="https://docs.digitalocean.com/reference/api/digitalocean/", + pricing_api="https://docs.digitalocean.com/reference/api/digitalocean/#tag/Sizes", + compliance_url="https://www.digitalocean.com/trust/certification-reports", + price_confidence="high", + compliance=dict(hipaa="yes", soc2="yes", pci="partial", gdpr="yes"), + compliance_note="SOC 2 Type II / SOC 3; HIPAA BAA available for eligible products; PCI: DO is a PCI-compliant service provider for some products only.", + storage=dict(kind="block", price_gb=0.10, name="Volumes"), + ipv4_monthly=0.0, + egress=dict(included_gb=None, per_gb=0.01, note="500 GB-10 TB pooled transfer included per droplet"), + smtp25="blocked", + live="digitalocean", + plans=[ + _p("s-1vcpu-2gb", 1, 2, 50, 12), + _p("s-2vcpu-2gb", 2, 2, 60, 18), + _p("s-2vcpu-4gb", 2, 4, 80, 24), + _p("s-4vcpu-8gb", 4, 8, 160, 48), + _p("s-8vcpu-16gb", 8, 16, 320, 96), + _p("g-2vcpu-8gb", 2, 8, 25, 63, "dedicated"), + _p("g-4vcpu-16gb", 4, 16, 50, 126, "dedicated"), + _p("g-8vcpu-32gb", 8, 32, 100, 252, "dedicated"), + _p("m-2vcpu-16gb", 2, 16, 50, 84, "dedicated"), + _p("m-4vcpu-32gb", 4, 32, 100, 168, "dedicated"), + ], + regions=[ + _r("nyc3", "New York", "US", NA, 40.71, -74.01), + _r("atl1", "Atlanta", "US", NA, 33.75, -84.39), + _r("sfo3", "San Francisco", "US", NA, 37.77, -122.42), + _r("tor1", "Toronto", "CA", NA, 43.65, -79.38), + _r("ams3", "Amsterdam", "NL", EU, 52.37, 4.9), + _r("lon1", "London", "GB", EU, 51.51, -0.13), + _r("fra1", "Frankfurt", "DE", EU, 50.11, 8.68), + _r("blr1", "Bangalore", "IN", AS, 12.97, 77.59), + _r("sgp1", "Singapore", "SG", AS, 1.35, 103.82), + _r("syd1", "Sydney", "AU", AU, -33.87, 151.21), + ], + ), + # ---------------------------------------------------------------- Vultr + dict( + id="vultr", name="Vultr", + website="https://www.vultr.com/products/cloud-compute/", + pricing_url="https://www.vultr.com/pricing/", + api_docs="https://www.vultr.com/api/", + pricing_api="https://www.vultr.com/api/#tag/plans", + compliance_url="https://www.vultr.com/legal/compliance/", + price_confidence="high", + compliance=dict(hipaa="partial", soc2="yes", pci="yes", gdpr="yes"), + compliance_note="SOC 2 Type II, PCI DSS, ISO 27001. HIPAA: compliant infrastructure claimed; confirm BAA with sales.", + storage=dict(kind="block", price_gb=0.10, name="Block Storage NVMe (HDD tier $0.025/GB)"), + ipv4_monthly=0.0, + egress=dict(included_gb=None, per_gb=0.01, note="2 TB+ pooled bandwidth included"), + smtp25="on request", + live="vultr", + plans=[ + _p("vc2-1c-2gb", 1, 2, 55, 10), + _p("vc2-2c-2gb", 2, 2, 65, 15), + _p("vc2-2c-4gb", 2, 4, 80, 20), + _p("vc2-4c-8gb", 4, 8, 160, 40), + _p("vc2-6c-16gb", 6, 16, 320, 80), + _p("vc2-8c-32gb", 8, 32, 640, 160), + _p("vhf-2c-4gb", 2, 4, 128, 24), + _p("vhf-3c-8gb", 3, 8, 256, 48), + _p("vhf-4c-16gb", 4, 16, 384, 96), + ], + regions=[ + _r(c, l, cc, cont, la, lo) for (c, l, cc, cont, la, lo) in [ + ("ewr", "New Jersey", "US", NA, 40.74, -74.17), ("ord", "Chicago", "US", NA, 41.88, -87.63), + ("dfw", "Dallas", "US", NA, 32.78, -96.8), ("lax", "Los Angeles", "US", NA, 34.05, -118.24), + ("mia", "Miami", "US", NA, 25.76, -80.19), ("atl", "Atlanta", "US", NA, 33.75, -84.39), + ("sea", "Seattle", "US", NA, 47.61, -122.33), ("sjc", "Silicon Valley", "US", NA, 37.34, -121.89), + ("hnl", "Honolulu", "US", NA, 21.31, -157.86), ("yto", "Toronto", "CA", NA, 43.65, -79.38), + ("mex", "Mexico City", "MX", NA, 19.43, -99.13), ("sao", "Sao Paulo", "BR", SA, -23.55, -46.63), + ("scl", "Santiago", "CL", SA, -33.45, -70.67), ("ams", "Amsterdam", "NL", EU, 52.37, 4.9), + ("fra", "Frankfurt", "DE", EU, 50.11, 8.68), ("cdg", "Paris", "FR", EU, 48.86, 2.35), + ("mad", "Madrid", "ES", EU, 40.42, -3.7), ("mxp", "Milan", "IT", EU, 45.46, 9.19), + ("lhr", "London", "GB", EU, 51.51, -0.13), ("man", "Manchester", "GB", EU, 53.48, -2.24), + ("sto", "Stockholm", "SE", EU, 59.33, 18.07), ("waw", "Warsaw", "PL", EU, 52.23, 21.01), + ("tlv", "Tel Aviv", "IL", AS, 32.08, 34.78), ("jnb", "Johannesburg", "ZA", AF, -26.2, 28.05), + ("nrt", "Tokyo", "JP", AS, 35.68, 139.69), ("itm", "Osaka", "JP", AS, 34.69, 135.5), + ("icn", "Seoul", "KR", AS, 37.57, 126.98), ("sgp", "Singapore", "SG", AS, 1.35, 103.82), + ("bom", "Mumbai", "IN", AS, 19.08, 72.88), ("del", "Delhi NCR", "IN", AS, 28.61, 77.21), + ("blr", "Bangalore", "IN", AS, 12.97, 77.59), ("syd", "Sydney", "AU", AU, -33.87, 151.21), + ("mel", "Melbourne", "AU", AU, -37.81, 144.96), + ] + ], + ), + # ------------------------------------------------------- Akamai/Linode + dict( + id="linode", name="Akamai Cloud (Linode)", + website="https://www.linode.com/products/shared/", + pricing_url="https://www.linode.com/pricing/", + api_docs="https://techdocs.akamai.com/linode-api/reference/api", + pricing_api="https://techdocs.akamai.com/linode-api/reference/get-linode-types", + compliance_url="https://www.akamai.com/legal/compliance", + price_confidence="high", + compliance=dict(hipaa="partial", soc2="yes", pci="yes", gdpr="yes"), + compliance_note="SOC 2 Type II, PCI DSS (Akamai). HIPAA: contact sales for BAA scope.", + storage=dict(kind="block", price_gb=0.10, name="Block Storage"), + ipv4_monthly=0.0, + egress=dict(included_gb=None, per_gb=0.005, note="1 TB+ pooled transfer included per plan"), + smtp25="on request", + live="linode", + plans=[ + _p("g6-standard-1", 1, 2, 50, 12), + _p("g6-standard-2", 2, 4, 80, 24), + _p("g6-standard-4", 4, 8, 160, 48), + _p("g6-standard-6", 6, 16, 320, 96), + _p("g6-standard-8", 8, 32, 640, 192), + _p("g6-dedicated-2", 2, 4, 80, 36, "dedicated"), + _p("g6-dedicated-4", 4, 8, 160, 72, "dedicated"), + _p("g6-dedicated-8", 8, 16, 320, 144, "dedicated"), + ], + regions=[ + _r("us-east", "Newark", "US", NA, 40.74, -74.17), + _r("us-southeast", "Atlanta", "US", NA, 33.75, -84.39), + _r("us-central", "Dallas", "US", NA, 32.78, -96.8), + _r("us-west", "Fremont", "US", NA, 37.55, -121.99), + _r("us-ord", "Chicago", "US", NA, 41.88, -87.63), + _r("us-iad", "Washington DC", "US", NA, 38.91, -77.04), + _r("us-sea", "Seattle", "US", NA, 47.61, -122.33), + _r("us-mia", "Miami", "US", NA, 25.76, -80.19), + _r("us-lax", "Los Angeles", "US", NA, 34.05, -118.24), + _r("ca-central", "Toronto", "CA", NA, 43.65, -79.38), + _r("br-gru", "Sao Paulo", "BR", SA, -23.55, -46.63, 1.4), + _r("eu-west", "London", "GB", EU, 51.51, -0.13), + _r("eu-central", "Frankfurt", "DE", EU, 50.11, 8.68), + _r("fr-par", "Paris", "FR", EU, 48.86, 2.35), + _r("nl-ams", "Amsterdam", "NL", EU, 52.37, 4.9), + _r("es-mad", "Madrid", "ES", EU, 40.42, -3.7), + _r("it-mil", "Milan", "IT", EU, 45.46, 9.19), + _r("se-sto", "Stockholm", "SE", EU, 59.33, 18.07), + _r("ap-northeast", "Tokyo", "JP", AS, 35.68, 139.69), + _r("jp-osa", "Osaka", "JP", AS, 34.69, 135.5), + _r("ap-south", "Singapore", "SG", AS, 1.35, 103.82), + _r("id-cgk", "Jakarta", "ID", AS, -6.21, 106.85, 1.2), + _r("ap-west", "Mumbai", "IN", AS, 19.08, 72.88), + _r("in-maa", "Chennai", "IN", AS, 13.08, 80.27), + _r("ap-southeast", "Sydney", "AU", AU, -33.87, 151.21), + _r("au-mel", "Melbourne", "AU", AU, -37.81, 144.96), + ], + ), + # -------------------------------------------------------------- Hetzner + dict( + id="hetzner", name="Hetzner Cloud", + website="https://www.hetzner.com/cloud/", + pricing_url="https://www.hetzner.com/cloud/#pricing", + api_docs="https://docs.hetzner.cloud/", + pricing_api="https://docs.hetzner.cloud/reference/cloud#pricing", + compliance_url="https://www.hetzner.com/unternehmen/zertifizierung/", + price_confidence="medium", + compliance=dict(hipaa="no", soc2="no", pci="no", gdpr="yes"), + compliance_note="ISO/IEC 27001 (German DCs). EU company with GDPR DPA. No SOC 2, PCI or BAA. Prices in EUR, converted; set HCLOUD_TOKEN for live pricing.", + storage=dict(kind="block", price_gb=0.057, name="Volumes"), + ipv4_monthly=0.60, + egress=dict(included_gb=20480, per_gb=0.0013, note="20 TB EU / 1 TB US & SG included"), + smtp25="on request", + live="hetzner", + plans=[ + _p("CX23", 2, 4, 40, 4.49, tag="eu"), + _p("CX33", 4, 8, 80, 6.99, tag="eu"), + _p("CX43", 8, 16, 160, 11.99, tag="eu"), + _p("CX53", 16, 32, 320, 21.99, tag="eu"), + _p("CAX21", 4, 8, 80, 7.99, "shared", "arm64", tag="eu"), + _p("CAX31", 8, 16, 160, 15.99, "shared", "arm64", tag="eu"), + _p("CPX21", 3, 4, 80, 9.99), + _p("CPX31", 4, 8, 160, 17.99), + _p("CPX41", 8, 16, 240, 33.49), + _p("CPX51", 16, 32, 360, 68.99), + _p("CCX13", 2, 8, 80, 15.99, "dedicated"), + _p("CCX23", 4, 16, 160, 31.49, "dedicated"), + _p("CCX33", 8, 32, 240, 62.49, "dedicated"), + ], + regions=[ + _r("fsn1", "Falkenstein", "DE", EU, 50.48, 12.37, 1.0, "fsn1-speed.hetzner.com", tags={"eu", None}), + _r("nbg1", "Nuremberg", "DE", EU, 49.45, 11.08, 1.0, "nbg1-speed.hetzner.com", tags={"eu", None}), + _r("hel1", "Helsinki", "FI", EU, 60.17, 24.94, 1.0, "hel1-speed.hetzner.com", tags={"eu", None}), + _r("ash", "Ashburn", "US", NA, 39.04, -77.49, 1.1, "ash-speed.hetzner.com", tags={None}), + _r("hil", "Hillsboro", "US", NA, 45.52, -122.99, 1.1, "hil-speed.hetzner.com", tags={None}), + _r("sin", "Singapore", "SG", AS, 1.35, 103.82, 1.25, "sin-speed.hetzner.com", tags={None}), + ], + ), + # -------------------------------------------------------------- Contabo + dict( + id="contabo", name="Contabo", + website="https://contabo.com/en/vps/", + pricing_url="https://contabo.com/en/vps/", + api_docs="https://api.contabo.com/", + pricing_api=None, + compliance_url="https://contabo.com/en/legal/", + price_confidence="medium", + compliance=dict(hipaa="no", soc2="no", pci="no", gdpr="yes"), + compliance_note="German company, GDPR DPA available. No SOC 2/PCI/HIPAA. Prices are maintained by hand (Edit Contabo prices button); non-EU locations may add a monthly location fee, modelled as a % surcharge per region.", + storage=dict(kind="none", price_gb=None, name="No block volumes; Object Storage EUR 2.49 / 250 GB-month (S3)", object_price_gb=0.0116), + ipv4_monthly=0.0, + egress=dict(included_gb=None, per_gb=None, note="Unmetered (32 TB fair use)"), + smtp25="open", + live=None, + # Hand-maintained price sheet. Plans/setup fee: Contabo Cloud VPS lineup (en-us page and + # configurator, checked 2026-12-01; codes V153-V158 from the North America East listing). + # Surcharges: us-east 0% per that listing; the other non-EU values are estimates. + manual_defaults=dict( + currency="EUR", fx=1.16, setup_fee=2.00, updated_at="2026-12-01", + setup_fee_note="One-time setup fee on 1-month terms (waived on 3+ month terms). Confirmed for Cloud VPS 4; assumed for the others.", + plans=[ + dict(code="V153", name="Cloud VPS 4", vcpu=4, ram_gb=8, disk_gb=100, price=5.50, note="SSD, 200 Mbit/s"), + dict(code="V154", name="Cloud VPS 6", vcpu=6, ram_gb=12, disk_gb=200, price=7.50, note="SSD, 300 Mbit/s"), + dict(code="V155", name="Cloud VPS 8", vcpu=8, ram_gb=24, disk_gb=300, price=14.00, note="SSD, 600 Mbit/s"), + dict(code="V156", name="Cloud VPS 12", vcpu=12, ram_gb=48, disk_gb=400, price=25.00, note="SSD, 800 Mbit/s"), + dict(code="V157", name="Cloud VPS 16", vcpu=16, ram_gb=64, disk_gb=500, price=37.00, note="SSD, 1 Gbit/s"), + dict(code="V158", name="Cloud VPS 18", vcpu=18, ram_gb=96, disk_gb=600, price=49.00, note="SSD, 1 Gbit/s"), + ], + region_surcharge_pct={"eu-de-nue": 0, "eu-de-dus": 0, "uk-lon": 10, "us-central": 20, "us-east": 0, + "us-west": 20, "sin": 40, "jpn": 40, "ind": 35, "aus": 45}, + ), + plans=[], # built from manual_defaults / saved manual sheet, see app/manual.py + regions=[ + _r("eu-de-nue", "Nuremberg", "DE", EU, 49.45, 11.08), + _r("eu-de-dus", "Dusseldorf", "DE", EU, 51.23, 6.78), + _r("uk-lon", "Portsmouth (UK)", "GB", EU, 50.8, -1.09), + _r("us-central", "St. Louis", "US", NA, 38.63, -90.2), + _r("us-east", "New York (NA East)", "US", NA, 40.71, -74.01), + _r("us-west", "Seattle", "US", NA, 47.61, -122.33), + _r("sin", "Singapore", "SG", AS, 1.35, 103.82), + _r("jpn", "Tokyo", "JP", AS, 35.68, 139.69), + _r("ind", "Mumbai", "IN", AS, 19.08, 72.88), + _r("aus", "Sydney", "AU", AU, -33.87, 151.21), + ], + ), + # ------------------------------------------------------------- OVHcloud + dict( + id="ovh", name="OVHcloud (VPS)", + website="https://www.ovhcloud.com/en/vps/", + pricing_url="https://www.ovhcloud.com/en/vps/", + api_docs="https://api.ovh.com/console/", + pricing_api="https://api.ovh.com/console/#/order/catalog/public", + compliance_url="https://www.ovhcloud.com/en/compliance/", + price_confidence="medium", + compliance=dict(hipaa="partial", soc2="partial", pci="partial", gdpr="yes"), + compliance_note="SOC 2, PCI DSS and HIPAA cover Hosted Private Cloud / some Bare Metal, not VPS. HDS (French health data) and SecNumCloud on selected offers. Strong GDPR posture.", + storage=dict(kind="block", price_gb=0.05, name="Additional disk / Block Storage"), + ipv4_monthly=0.0, + egress=dict(included_gb=None, per_gb=None, note="Unmetered traffic"), + smtp25="open", + live=None, + plans=[ + _p("VPS-1", 4, 8, 75, 6.46), + _p("VPS-2", 6, 12, 100, 10.15), + _p("VPS-3", 8, 24, 200, 18.45), + _p("VPS-4", 12, 48, 300, 33.21), + _p("VPS-5", 16, 64, 350, 46.13), + ], + regions=[ + _r("bhs", "Beauharnois", "CA", NA, 45.31, -73.87, 1.0, "bhs.proof.ovh.ca"), + _r("us-east-vin", "Vint Hill", "US", NA, 38.75, -77.67, 1.1, "vin.proof.ovh.us"), + _r("us-west-hil", "Hillsboro", "US", NA, 45.52, -122.99, 1.1, "hil.proof.ovh.us"), + _r("gra", "Gravelines", "FR", EU, 50.99, 2.13, 1.0, "gra.proof.ovh.net"), + _r("sbg", "Strasbourg", "FR", EU, 48.58, 7.75, 1.0, "sbg.proof.ovh.net"), + _r("de", "Frankfurt", "DE", EU, 50.11, 8.68, 1.0), + _r("uk", "London", "GB", EU, 51.51, -0.13, 1.0), + _r("waw", "Warsaw", "PL", EU, 52.23, 21.01, 1.0), + _r("sgp", "Singapore", "SG", AS, 1.35, 103.82, 1.45, "sgp.proof.ovh.net"), + _r("syd", "Sydney", "AU", AU, -33.87, 151.21, 1.45, "syd.proof.ovh.net"), + _r("ynm", "Mumbai", "IN", AS, 19.08, 72.88, 1.35), + ], + ), + # ------------------------------------------------------------ Scaleway + dict( + id="scaleway", name="Scaleway", + website="https://www.scaleway.com/en/virtual-instances/", + pricing_url="https://www.scaleway.com/en/pricing/virtual-instances/", + api_docs="https://www.scaleway.com/en/developers/api/instance/", + pricing_api="https://www.scaleway.com/en/developers/api/instance/#path-instance-types-list-instance-types", + compliance_url="https://www.scaleway.com/en/security-and-resilience/", + price_confidence="medium", + compliance=dict(hipaa="no", soc2="no", pci="no", gdpr="yes"), + compliance_note="ISO 27001, HDS (French health data hosting). EU-only, GDPR DPA. No SOC 2/PCI/BAA found. Prices in EUR, converted.", + storage=dict(kind="block", price_gb=0.095, name="Block Storage (5K IOPS)"), + ipv4_monthly=3.40, + egress=dict(included_gb=None, per_gb=None, note="Unmetered (bandwidth caps per type)"), + smtp25="on request", + live=None, + plans=[ + _p("DEV1-S", 2, 2, 20, 7.99), + _p("DEV1-M", 3, 4, 40, 16.40), + _p("DEV1-L", 4, 8, 80, 33.60), + _p("DEV1-XL", 4, 12, 120, 50.10), + _p("PLAY2-NANO", 4, 8, 0, 46.70), + _p("PRO2-XXS", 2, 8, 0, 44.10), + _p("PRO2-XS", 4, 16, 0, 88.00), + _p("PRO2-S", 8, 32, 0, 176.00), + _p("POP2-2C-8G", 2, 8, 0, 58.40, "dedicated"), + _p("POP2-4C-16G", 4, 16, 0, 116.80, "dedicated"), + _p("COPARM1-4C-16G", 4, 16, 0, 86.00, "dedicated", "arm64"), + ], + regions=[ + _r("fr-par", "Paris", "FR", EU, 48.86, 2.35), + _r("nl-ams", "Amsterdam", "NL", EU, 52.37, 4.9), + _r("pl-waw", "Warsaw", "PL", EU, 52.23, 21.01), + ], + ), + # ------------------------------------------------------------ Hostinger + dict( + id="hostinger", name="Hostinger (KVM VPS)", + website="https://www.hostinger.com/vps-hosting", + pricing_url="https://www.hostinger.com/vps-hosting", + api_docs="https://developers.hostinger.com/", + pricing_api="https://developers.hostinger.com/#tag/billing-catalog", + compliance_url="https://www.hostinger.com/legal/privacy-policy", + price_confidence="low", + compliance=dict(hipaa="no", soc2="no", pci="no", gdpr="yes"), + compliance_note="Prices shown are 24-month prepaid promotional rates; renewal and monthly-term prices are roughly 2x. GDPR DPA (Lithuanian company). No SOC 2/PCI/BAA.", + storage=dict(kind="none", price_gb=None, name="No add-on block storage; upgrade plan"), + ipv4_monthly=0.0, + egress=dict(included_gb=None, per_gb=None, note="4-32 TB included"), + smtp25="open", + live=None, + plans=[ + _p("KVM 1", 1, 4, 50, 6.49, note="24-mo promo"), + _p("KVM 2", 2, 8, 100, 8.99, note="24-mo promo"), + _p("KVM 4", 4, 16, 200, 12.99, note="24-mo promo"), + _p("KVM 8", 8, 32, 400, 25.99, note="24-mo promo"), + ], + regions=[ + _r("us-bos", "Boston", "US", NA, 42.36, -71.06), + _r("us-phx", "Phoenix", "US", NA, 33.45, -112.07), + _r("br-sao", "Sao Paulo", "BR", SA, -23.55, -46.63), + _r("fr-par", "Paris", "FR", EU, 48.86, 2.35), + _r("de-fra", "Frankfurt", "DE", EU, 50.11, 8.68), + _r("lt-vno", "Vilnius", "LT", EU, 54.69, 25.28), + _r("gb-lon", "London", "GB", EU, 51.51, -0.13), + _r("in-bom", "Mumbai", "IN", AS, 19.08, 72.88), + _r("my-kul", "Kuala Lumpur", "MY", AS, 3.14, 101.69), + ], + ), + # ------------------------------------------------------------ HostAfrica + dict( + id="hostafrica", name="HostAfrica (Cloud VPS)", + website="https://www.hostafrica.com/vps-hosting/", + pricing_url="https://www.hostafrica.com/vps-hosting/", + api_docs="https://www.hostafrica.com/", + api_docs_note="No public IaaS API found; provisioning via WHMCS client area. Ask HostAfrica for reseller API access.", + pricing_api=None, + compliance_url="https://www.hostafrica.com/legal/", + price_confidence="low", + compliance=dict(hipaa="no", soc2="no", pci="no", gdpr="partial"), + compliance_note="POPIA (South Africa) aligned; GDPR DPA not confirmed. No SOC 2/PCI/BAA. Prices are estimates from ZAR list prices - verify.", + storage=dict(kind="none", price_gb=None, name="Upgrade plan for more disk"), + ipv4_monthly=0.0, + egress=dict(included_gb=None, per_gb=None, note="Unmetered / fair use"), + smtp25="open", + live=None, + plans=[ + _p("VPS 2GB", 1, 2, 40, 8.0), + _p("VPS 4GB", 2, 4, 80, 15.0), + _p("VPS 8GB", 4, 8, 160, 29.0), + _p("VPS 16GB", 8, 16, 320, 55.0), + _p("VPS 32GB", 8, 32, 640, 99.0), + ], + regions=[ + _r("za-jnb", "Johannesburg", "ZA", AF, -26.2, 28.05), + _r("za-cpt", "Cape Town", "ZA", AF, -33.92, 18.42), + ], + ), +] + +FX_NOTE = "EUR-priced providers converted at EUR_USD (default 1.16, override with env EUR_USD)." +CATALOG_DATE = "2026-12-01" diff --git a/app/data/software.py b/app/data/software.py new file mode 100644 index 0000000..d70d341 --- /dev/null +++ b/app/data/software.py @@ -0,0 +1,196 @@ +"""Federated Computer software catalog with resource profiles. + +Source of the app list: https://federated.computer/product/software-library/ +and https://federated.computer/pricing/ (read 2026-12-01). + +Resource figures are engineering estimates for a containerised deployment +(vendor minimums + observed footprints), not vendor guarantees: + + ram_mb steady-state RAM at idle (MB) + ram_pu extra RAM per *concurrent* user (MB) + cpu steady-state vCPU share + cpu_pu extra vCPU per *concurrent* user + disk_gb install + database + cache footprint (GB) + disk_pu data growth per *named* user (GB) + deps shared services the app needs (sized once, see SHARED) +""" + +# fmt: off +# (id, name, category, tier, ram_mb, ram_pu, cpu, cpu_pu, disk_gb, disk_pu, deps, note) +_RAW = [ + # --- Federated Core: always installed in every tier --------------------- + ("traefik", "Traefik", "Dev & Data", "core", 128, 2, 0.05, 0.01, 1, 0, [], "Reverse proxy / TLS for every app."), + ("authelia", "Authelia", "Integration", "core", 128, 4, 0.05, 0.01, 1, 0, ["redis"], "SSO for every app."), + ("powerdns", "PowerDNS", "Dev & Data", "core", 128, 0, 0.05, 0.0, 1, 0, ["postgres"], "Authoritative DNS."), + + # --- Files, Documents and Groupware ------------------------------------ + ("nextcloud", "Nextcloud", "Files, Documents and Groupware", "library", 512, 128, 0.25, 0.15, 5, 5, ["postgres", "redis"], "Disk grows with user files; 5 GB/user assumed (use Extra disk for more)."), + ("collabora", "Collabora Online", "Files, Documents and Groupware", "library", 1024, 300, 0.5, 0.3, 2, 0, [], "Each open document is a process; CPU-heavy while editing."), + ("calcom", "Cal.com", "Files, Documents and Groupware", "library", 768, 32, 0.25, 0.05, 2, 0.05, ["postgres"], ""), + ("docuseal", "Docuseal", "Files, Documents and Groupware", "library", 384, 32, 0.1, 0.05, 2, 0.2, ["postgres"], ""), + ("immich", "Immich", "Files, Documents and Groupware", "library", 2048, 128, 0.5, 0.2, 10, 5, ["postgres", "redis"], "Machine-learning container (faces/CLIP) needs ~1.5 GB RAM and bursts CPU on upload; 5 GB photos/user assumed."), + ("erpnext", "ERPNext", "Files, Documents and Groupware", "library", 2048, 128, 0.5, 0.15, 10, 0.5, ["mariadb", "redis"], "Frappe workers + scheduler; vendor recommends 4 GB+."), + ("jitsi", "Jitsi", "Files, Documents and Groupware", "library", 1536, 100, 0.5, 0.35, 5, 0, [], "JVB is CPU and bandwidth bound: ~2-4 Mbps per participant. Watch egress."), + ("kimai", "Kimai", "Files, Documents and Groupware", "library", 256, 16, 0.1, 0.02, 1, 0.05, ["mariadb"], ""), + ("plane", "Plane", "Files, Documents and Groupware", "library", 2048, 64, 0.5, 0.05, 5, 0.5, ["postgres", "redis"], "Many microservices (api, worker, beat, web, space, admin, minio)."), + ("vaultwarden", "Vaultwarden", "Files, Documents and Groupware", "library", 64, 4, 0.05, 0.01, 1, 0.01, [], ""), + + # --- Communication ------------------------------------------------------ + ("element", "Element (Matrix/Synapse)", "Communication", "library", 1024, 64, 0.5, 0.1, 5, 1, ["postgres"], "Federating with large public rooms can need far more RAM."), + ("roundcube", "Roundcube", "Communication", "library", 128, 16, 0.05, 0.02, 1, 0, ["mariadb"], ""), + ("superpanel", "Superpanel", "Integration", "library", 256, 8, 0.1, 0.01, 2, 0, [], "Federated Core dashboard and app management."), + ("email", "eMail server (SMTP/IMAP/AV)", "Integration", "library", 1536, 32, 0.25, 0.05, 5, 2, [], "ClamAV alone needs ~1.2 GB RAM. Requires outbound TCP 25 (check 'SMTP 25' column)."), + + # --- Community & Support ------------------------------------------------ + ("bookstack", "BookStack", "Community & Support", "library", 256, 16, 0.1, 0.02, 2, 0.2, ["mariadb"], ""), + ("discourse", "Discourse", "Community & Support", "library", 2048, 64, 0.5, 0.1, 10, 0.2, ["postgres", "redis"], "Vendor minimum 2 GB RAM."), + ("freescout", "FreeScout", "Community & Support", "library", 256, 32, 0.1, 0.03, 2, 0.5, ["mariadb"], ""), + + # --- Marketing and Publishing ------------------------------------------ + ("listmonk", "Listmonk", "Marketing and Publishing", "library", 128, 8, 0.1, 0.01, 1, 0, ["postgres"], "Bulk sending via an external SMTP relay recommended."), + ("matomo", "Matomo", "Marketing and Publishing", "library", 512, 32, 0.25, 0.05, 5, 0.1, ["mariadb"], "DB grows with tracked traffic, not users."), + ("mautic", "Mautic", "Marketing and Publishing", "library", 1024, 64, 0.5, 0.1, 5, 0.1, ["mariadb"], "Cron-driven campaigns spike CPU."), + ("plausible", "Plausible Analytics", "Marketing and Publishing", "library", 512, 16, 0.25, 0.02, 3, 0, ["postgres", "clickhouse"], ""), + ("castopod", "Castopod", "Marketing and Publishing", "library", 512, 32, 0.25, 0.05, 5, 1, ["mariadb", "redis"], "Media files; consider object storage."), + ("wordpress", "WordPress", "Marketing and Publishing", "library", 512, 64, 0.25, 0.1, 5, 0.2, ["mariadb"], ""), + + # --- Sales & CRM -------------------------------------------------------- + ("espocrm", "EspoCRM", "Sales & CRM", "library", 384, 32, 0.15, 0.03, 2, 0.2, ["mariadb"], ""), + ("woocommerce", "WooCommerce", "Sales & CRM", "library", 512, 64, 0.25, 0.1, 3, 0.2, ["mariadb"], "Runs inside WordPress; WordPress is added automatically."), + + # --- Dev & Data --------------------------------------------------------- + ("baserow", "Baserow", "Dev & Data", "library", 1536, 64, 0.5, 0.1, 5, 0.5, ["postgres", "redis"], ""), + ("gitea", "Gitea", "Dev & Data", "library", 256, 32, 0.25, 0.1, 5, 0.5, ["postgres"], "CI runners are extra: budget 1-2 vCPU / 2 GB per concurrent job."), + ("jupyter", "Jupyter Notebooks", "Dev & Data", "library", 2048, 1024, 0.5, 0.5, 10, 2, [], "Local AI models need much more RAM (7B model ~ 8 GB) or a GPU."), + ("n8n", "n8n", "Dev & Data", "library", 512, 32, 0.25, 0.05, 2, 0.1, ["postgres"], ""), + ("grafana", "Grafana + Prometheus", "Dev & Data", "library", 768, 16, 0.25, 0.02, 10, 0, [], "Prometheus TSDB retention drives disk."), + ("headscale", "Headscale", "Dev & Data", "library", 64, 2, 0.05, 0.005, 1, 0, [], ""), + + # --- Agentic Development ------------------------------------------------ + ("superbrain", "Superbrain", "Agentic Development", "library", 512, 32, 0.2, 0.03, 5, 0.2, ["postgres"], "AI bookmark workspace."), + ("hermes", "Hermes", "Agentic Development", "library", 1024, 128, 0.5, 0.1, 5, 0.5, [], "Assumes remote model APIs; local inference needs GPU or 16 GB+ RAM."), + ("opencode", "OpenCode", "Agentic Development", "library", 512, 256, 0.25, 0.25, 2, 1, [], "Assumes remote model APIs."), + ("claudecode", "Claude Code", "Agentic Development", "library", 512, 256, 0.25, 0.25, 2, 1, [], "Uses Anthropic API; sandboxed builds add CPU."), +] + +# On-demand ("Ask") apps: lighter-touch generic profiles. +_ON_DEMAND = [ + ("appflowy", "AppFlowy", 1024, 64, 0.25, 0.05, 3, 0.5, ["postgres", "redis"]), + ("appsmith", "Appsmith", 2048, 64, 0.5, 0.05, 5, 0, ["mongodb", "redis"]), + ("beam", "Beam", 1024, 64, 0.5, 0.1, 5, 0, []), + ("bigbluebutton", "Big Blue Button", 8192, 200, 2.0, 0.4, 50, 1, ["redis", "mongodb"]), + ("blackcandy", "BlackCandy", 256, 16, 0.1, 0.05, 2, 5, []), + ("briefer", "Briefer", 1024, 128, 0.5, 0.1, 5, 0.5, ["postgres"]), + ("caddy", "Caddy", 64, 2, 0.05, 0.01, 1, 0, []), + ("clickhouse_app", "Clickhouse", 0, 0, 0, 0, 0, 0, ["clickhouse"]), + ("cloudanix", "Cloudanix", 512, 32, 0.25, 0.05, 2, 0, []), + ("copyparty", "Copyparty", 128, 16, 0.1, 0.05, 1, 20, []), + ("crontogo", "CrontoGo", 64, 0, 0.05, 0, 1, 0, []), + ("docmost", "Docmost", 512, 32, 0.25, 0.03, 2, 0.2, ["postgres", "redis"]), + ("documenso", "Documenso", 512, 32, 0.2, 0.05, 2, 1, ["postgres"]), + ("excalidraw", "Excalidraw", 64, 8, 0.05, 0.02, 1, 0, []), + ("flarum", "Flarum", 256, 32, 0.1, 0.03, 2, 0.1, ["mariadb"]), + ("fleetdm", "FleetDM", 512, 16, 0.25, 0.02, 3, 0, ["mariadb", "redis"]), + ("freepbx", "FreePBX", 1024, 32, 0.5, 0.1, 10, 0.5, ["mariadb"]), + ("ghost", "GhostCMS", 512, 32, 0.2, 0.05, 3, 0.2, ["mariadb"]), + ("hievents", "Hi.Events", 512, 32, 0.2, 0.05, 2, 0, ["postgres", "redis"]), + ("infisical", "Infisical", 512, 16, 0.25, 0.02, 2, 0, ["postgres", "redis"]), + ("inngest", "Inngest", 512, 16, 0.25, 0.05, 2, 0, ["postgres", "redis"]), + ("ironmq", "IronMQ", 256, 8, 0.1, 0.02, 2, 0, []), + ("kafka", "Kafka", 2048, 0, 1.0, 0.05, 20, 0, []), + ("kaneo", "Kaneo", 256, 16, 0.1, 0.02, 1, 0.1, ["postgres"]), + ("linkwarden", "Linkwarden", 512, 32, 0.2, 0.05, 2, 1, ["postgres"]), + ("logtail", "Logtail", 512, 0, 0.25, 0.02, 20, 0, []), + ("loomio", "Loomio", 1024, 32, 0.25, 0.05, 3, 0.1, ["postgres", "redis"]), + ("maybe", "Maybe Finance", 512, 32, 0.2, 0.03, 2, 0.05, ["postgres", "redis"]), + ("metabase", "Metabase", 1536, 64, 0.5, 0.1, 2, 0, ["postgres"]), + ("mongodb_app", "MongoDB", 0, 0, 0, 0, 0, 0, ["mongodb"]), + ("moodle", "Moodle", 1024, 64, 0.5, 0.1, 10, 1, ["postgres"]), + ("mysql_app", "MySQL", 0, 0, 0, 0, 0, 0, ["mariadb"]), + ("nginx", "Nginx", 64, 2, 0.05, 0.01, 1, 0, []), + ("nocodb", "NocoDB", 512, 32, 0.25, 0.05, 2, 0.2, ["postgres"]), + ("nodered", "NodeRed", 256, 16, 0.1, 0.02, 1, 0, []), + ("onlyoffice", "OnlyOffice", 2048, 256, 1.0, 0.3, 5, 0, ["postgres", "redis"]), + ("onyx", "Onyx", 4096, 128, 1.0, 0.2, 20, 0.5, ["postgres", "redis"]), + ("openpanel", "Open Panel", 1024, 16, 0.25, 0.02, 5, 0, ["postgres", "redis", "clickhouse"]), + ("openreplay", "Open Replay", 8192, 64, 2.0, 0.1, 50, 0, ["postgres", "redis", "clickhouse"]), + ("openclassify", "OpenClassify", 512, 32, 0.2, 0.05, 3, 0.1, ["mariadb"]), + ("openfaas", "OpenFaaS", 1024, 64, 0.5, 0.1, 5, 0, []), + ("openproject", "OpenProject", 2048, 64, 0.5, 0.1, 5, 0.5, ["postgres"]), + ("opensearch_app", "OpenSearch", 0, 0, 0, 0, 0, 0, ["opensearch"]), + ("openwhisk", "OpenWhisk", 2048, 64, 1.0, 0.1, 5, 0, []), + ("owncast", "Owncast", 512, 16, 1.0, 0.1, 5, 0, []), + ("paperless", "Paperless", 1024, 64, 0.5, 0.1, 5, 2, ["postgres", "redis"]), + ("peertube", "Peertube", 2048, 64, 1.0, 0.2, 20, 5, ["postgres", "redis"]), + ("penpot", "Penpot", 2048, 128, 0.5, 0.1, 5, 1, ["postgres", "redis"]), + ("pixelfed", "Pixelfed", 1024, 64, 0.5, 0.1, 5, 2, ["mariadb", "redis"]), + ("pocketbase", "Pocketbase", 64, 8, 0.05, 0.02, 1, 0, []), + ("postgres_app", "Postgresql", 0, 0, 0, 0, 0, 0, ["postgres"]), + ("rallly", "Rallly", 256, 16, 0.1, 0.02, 1, 0, ["postgres"]), + ("redis_app", "Redis", 0, 0, 0, 0, 0, 0, ["redis"]), + ("resourcespace", "ResourceSpace", 512, 64, 0.25, 0.1, 5, 5, ["mariadb"]), + ("revolt", "Revolt", 1024, 32, 0.25, 0.05, 3, 0.5, ["mongodb", "redis"]), + ("rustdesk", "RustDesk", 128, 8, 0.1, 0.05, 1, 0, []), + ("snapify", "Snapify", 512, 32, 0.25, 0.1, 3, 2, ["postgres"]), + ("sogo", "Sogo", 512, 32, 0.2, 0.03, 2, 0.1, ["postgres"]), + ("sqlite_app", "SQLite", 0, 0, 0, 0, 0, 0, []), + ("superproductivity", "Super Productivity", 128, 8, 0.05, 0.01, 1, 0, []), + ("superset", "Superset", 2048, 128, 0.5, 0.1, 5, 0, ["postgres", "redis"]), + ("twenty", "Twenty", 1024, 32, 0.25, 0.05, 3, 0.2, ["postgres", "redis"]), + ("umami", "Umami", 256, 8, 0.1, 0.02, 2, 0, ["postgres"]), + ("valkey_app", "valkey", 0, 0, 0, 0, 0, 0, ["redis"]), + ("vdoninja", "VDO.ninja", 128, 8, 0.1, 0.1, 1, 0, []), + ("wazuh", "Wazuh", 8192, 32, 2.0, 0.05, 50, 0, []), + ("webstudio", "Webstudio", 1024, 32, 0.25, 0.05, 3, 0, ["postgres"]), + ("wger", "WGER", 512, 16, 0.1, 0.02, 2, 0.05, ["postgres"]), +] + +# Shared backing services: sized once no matter how many apps use them. +SHARED = { + "postgres": dict(name="PostgreSQL (shared)", ram_mb=512, ram_pu=24, cpu=0.25, cpu_pu=0.04, disk_gb=3, disk_pu=0.05), + "mariadb": dict(name="MariaDB (shared)", ram_mb=512, ram_pu=24, cpu=0.25, cpu_pu=0.04, disk_gb=3, disk_pu=0.05), + "redis": dict(name="Redis/Valkey (shared)", ram_mb=128, ram_pu=4, cpu=0.05, cpu_pu=0.01, disk_gb=1, disk_pu=0), + "mongodb": dict(name="MongoDB (shared)", ram_mb=1024, ram_pu=32, cpu=0.25, cpu_pu=0.05, disk_gb=5, disk_pu=0.1), + "clickhouse": dict(name="ClickHouse (shared)", ram_mb=1536, ram_pu=16, cpu=0.5, cpu_pu=0.05, disk_gb=10, disk_pu=0), + "opensearch": dict(name="OpenSearch (shared)", ram_mb=2048, ram_pu=32, cpu=0.5, cpu_pu=0.05, disk_gb=10, disk_pu=0), +} + +# Host OS + Docker + Federated system utilities (Federated reserves 30 GB). +BASE = dict(name="OS, Docker & system utilities", ram_mb=1024, ram_pu=0, cpu=0.2, cpu_pu=0, disk_gb=30, disk_pu=0) + +# App-level implied requirements. +IMPLIES = {"woocommerce": ["wordpress"]} +# fmt: on + +CATEGORY_ORDER = [ + "Files, Documents and Groupware", + "Communication", + "Community & Support", + "Marketing and Publishing", + "Sales & CRM", + "Dev & Data", + "Agentic Development", + "Integration", + "On Demand", +] + +APPS: dict[str, dict] = {} +for (i, n, cat, tier, r, rpu, c, cpu, d, dpu, deps, note) in _RAW: + APPS[i] = dict(id=i, name=n, category=cat, tier=tier, ram_mb=r, ram_pu=rpu, cpu=c, cpu_pu=cpu, + disk_gb=d, disk_pu=dpu, deps=deps, note=note) +for (i, n, r, rpu, c, cpu, d, dpu, deps) in _ON_DEMAND: + APPS[i] = dict(id=i, name=n, category="On Demand", tier="on_demand", ram_mb=r, ram_pu=rpu, cpu=c, cpu_pu=cpu, + disk_gb=d, disk_pu=dpu, deps=deps, note="On-demand app (ask Federated); generic profile.") + +# Federated tiers. Every tier also includes the core apps above (Traefik, PowerDNS, Authelia). +# Good/Better/Best and their prices: https://federated.computer/pricing/ +_BASE = ["email", "headscale"] +_GOOD = ["email", "roundcube", "nextcloud", "wordpress", "vaultwarden", "headscale", "immich", "docuseal", "gitea", "kimai", "listmonk"] +_BETTER = _GOOD + ["calcom", "element", "espocrm", "jitsi", "plausible", "n8n", "mautic"] +_BEST = _BETTER + ["plane", "bookstack", "baserow", "freescout"] +PRESETS = { + "base": dict(label="Federated Base", apps=_BASE, federated_price=19, storage_gb=30), + "good": dict(label="Federated Good", apps=_GOOD, federated_price=70, storage_gb=60), + "better": dict(label="Federated Better", apps=_BETTER, federated_price=145, storage_gb=130), + "best": dict(label="Federated Best", apps=_BEST, federated_price=290, storage_gb=200), +} diff --git a/app/engine.py b/app/engine.py new file mode 100644 index 0000000..f5d5eaf --- /dev/null +++ b/app/engine.py @@ -0,0 +1,200 @@ +"""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 diff --git a/app/live.py b/app/live.py new file mode 100644 index 0000000..cecdb33 --- /dev/null +++ b/app/live.py @@ -0,0 +1,203 @@ +"""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 diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..5f82e79 --- /dev/null +++ b/app/main.py @@ -0,0 +1,105 @@ +"""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} diff --git a/app/manual.py b/app/manual.py new file mode 100644 index 0000000..236863d --- /dev/null +++ b/app/manual.py @@ -0,0 +1,98 @@ +"""Hand-maintained price sheets for providers without a pricing API (currently Contabo). + +A provider opts in by defining `manual_defaults` in app/data/providers.py. Edits made in +the UI are saved to $DATA_DIR/manual_prices.json and take precedence over the defaults. +""" + +from __future__ import annotations + +import copy +import json +import os +import time +from pathlib import Path + +from pydantic import BaseModel, Field + +DATA_DIR = Path(os.environ.get("DATA_DIR", "/data")) +STORE = DATA_DIR / "manual_prices.json" + + +class ManualPlan(BaseModel): + code: str = "" + name: str = Field(min_length=1) + vcpu: int = Field(ge=1, le=512) + ram_gb: float = Field(gt=0, le=4096) + disk_gb: float = Field(ge=0, le=100000) + price: float = Field(ge=0, le=100000) + cpu_type: str = "shared" + note: str = "" + + +class ManualSheet(BaseModel): + currency: str = Field("EUR", pattern="^(EUR|USD)$") + fx: float = Field(1.16, gt=0, le=10) # USD per 1 unit of currency + setup_fee: float = Field(0, ge=0, le=10000) + setup_fee_note: str = "" + plans: list[ManualPlan] = Field(min_length=1) + region_surcharge_pct: dict[str, float] = {} + updated_at: str = "" + + +def _load() -> dict: + try: + return json.loads(STORE.read_text()) + except (FileNotFoundError, json.JSONDecodeError): + return {} + + +def get_sheet(provider: dict) -> tuple[dict, bool]: + """Return (sheet, is_default).""" + saved = _load().get(provider["id"]) + if saved: + return saved, False + return copy.deepcopy(provider["manual_defaults"]), True + + +def save_sheet(provider: dict, sheet: ManualSheet) -> dict: + data = _load() + d = sheet.model_dump() + d["updated_at"] = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime()) + known = {r["code"] for r in provider["regions"]} + d["region_surcharge_pct"] = {k: v for k, v in d["region_surcharge_pct"].items() if k in known} + data[provider["id"]] = d + DATA_DIR.mkdir(parents=True, exist_ok=True) + tmp = STORE.with_suffix(".tmp") + tmp.write_text(json.dumps(data, indent=2)) + tmp.replace(STORE) + return d + + +def reset_sheet(provider: dict): + data = _load() + if data.pop(provider["id"], None) is not None: + tmp = STORE.with_suffix(".tmp") + tmp.write_text(json.dumps(data, indent=2)) + tmp.replace(STORE) + + +def apply(provider: dict) -> dict: + """Return a copy of provider with plans/regions/setup fee built from its price sheet.""" + sheet, is_default = get_sheet(provider) + fx = sheet["fx"] if sheet["currency"] != "USD" else 1.0 + p = copy.copy(provider) + p["plans"] = [ + dict(model=f"{pl['name']} ({pl['code']})" if pl.get("code") else pl["name"], + vcpu=pl["vcpu"], ram_gb=pl["ram_gb"], disk_gb=pl["disk_gb"], price=round(pl["price"] * fx, 2), + cpu_type=pl.get("cpu_type", "shared"), arch="x86_64", tag=None, note=pl.get("note", "")) + for pl in sheet["plans"] + ] + pct = sheet.get("region_surcharge_pct", {}) + p["regions"] = [dict(r, mult=1 + pct.get(r["code"], 0) / 100) for r in provider["regions"]] + if sheet.get("setup_fee"): + p["setup_fee"] = dict(usd=round(sheet["setup_fee"] * fx, 2), + note=f"{sheet['currency']} {sheet['setup_fee']:.2f} one-time. {sheet.get('setup_fee_note', '')}".strip()) + else: + p.pop("setup_fee", None) + p["price_source"] = f"manual sheet {sheet.get('updated_at', '')}" + (" (defaults)" if is_default else "") + return p diff --git a/app/state.py b/app/state.py new file mode 100644 index 0000000..6dc9d33 --- /dev/null +++ b/app/state.py @@ -0,0 +1,35 @@ +"""Shared runtime state: live-price cache and the effective (live/manual/catalog) provider list.""" + +from __future__ import annotations + +import copy +import logging + +from app import live, manual +from app.data.providers import CATALOG_DATE, PROVIDERS + +log = logging.getLogger("coremarket") +live_cache: dict = {} + + +def effective_providers() -> list[dict]: + out = [] + for p in PROVIDERS: + if p.get("manual_defaults"): + out.append(manual.apply(p)) + continue + p2 = copy.copy(p) + lc = live_cache.get(p["id"]) + if lc and lc.get("plans"): + p2["plans"] = lc["plans"] + p2["price_source"] = f"live API {lc['fetched_at']}" + else: + p2["price_source"] = f"catalog {CATALOG_DATE}" + out.append(p2) + return out + + +async def refresh_live() -> dict: + await live.refresh(live_cache) + log.info("live pricing: %s", live_cache.get("_status")) + return live_cache.get("_status", {}) diff --git a/app/static/app.js b/app/static/app.js new file mode 100644 index 0000000..bbc9da4 --- /dev/null +++ b/app/static/app.js @@ -0,0 +1,621 @@ +"use strict"; +const $ = (s, el = document) => el.querySelector(s); +const $$ = (s, el = document) => [...el.querySelectorAll(s)]; +const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +const usd = (n) => (n == null ? "-" : "$" + Number(n).toFixed(2)); + +const S = { + cat: null, apps: new Set(), cont: new Set(), comp: new Set(), prov: new Set(), + cities: new Set(["nyc", "chi", "lax", "dfw"]), data: null, sort: { key: "total", dir: 1 }, + override: {}, preset: null, +}; +const COMP = [["hipaa", "HIPAA"], ["soc2", "SOC2"], ["pci", "PCI DSS"], ["gdpr", "GDPR"]]; + +const API = "/api/v1"; + +// Calls the Coremarket API with the browser session. The X-Coremarket header marks the request as +// coming from this page (the server rejects cookie-authenticated writes without it). +async function api(path, body, method) { + const r = await fetch(API + path, { + method: method || (body !== undefined ? "POST" : "GET"), + headers: { "Content-Type": "application/json", "X-Coremarket": "1" }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + if (r.status === 401 && !path.startsWith("/auth/")) { // session expired + location.href = "/login?next=" + encodeURIComponent(location.pathname); + throw new Error("signed out"); + } + if (!r.ok) { + let msg = (await r.text()).slice(0, 400); + try { const d = JSON.parse(msg).detail; msg = typeof d === "string" ? d : d.map((x) => x.msg).join("; "); } catch (_) {} + throw new Error(msg); + } + return r.json(); +} + +function chip(container, label, on, toggle, title = "") { + const c = document.createElement("span"); + c.className = "chip" + (on ? " on" : ""); + c.textContent = label; + c.title = title; + c.onclick = () => { toggle(); c.classList.toggle("on"); }; + container.appendChild(c); +} + +// ------------------------------------------------------------------ init +async function init() { + S.me = await api("/auth/me"); + applyRole(); + initAccountMenu(); + S.cat = await api("/catalog"); + $("#coreList").textContent = S.cat.core.join(", "); + renderLiveStatus(); + + const sel = $("#tierSelect"); + sel.innerHTML = `` + Object.entries(S.cat.presets).map(([k, p]) => + ``).join(""); + sel.onchange = () => { + S.preset = sel.value || null; + if (S.preset) S.apps = new Set(S.cat.presets[S.preset].apps); + renderApps(); requote(); + }; + $("#clearApps").onclick = () => { S.apps.clear(); setPreset(null); renderApps(); requote(); }; + + S.cat.continents.forEach((c) => chip($("#contFilter"), c, false, () => tog(S.cont, c))); + COMP.forEach(([k, l]) => chip($("#compFilter"), l, false, () => tog(S.comp, k))); + S.cat.providers.forEach((p) => chip($("#provFilter"), p.name.replace(/ \(.*\)/, ""), false, () => tog(S.prov, p.id))); + S.cat.cities.forEach((c) => chip($("#cityFilter"), c.name, S.cities.has(c.id), () => { tog(S.cities, c.id, false); render(); })); + + $("#appSearch").oninput = renderApps; + $$("#concurrent,#named,#headroom,#growth,#extraDisk,#allowBurst,#dedicatedOnly,#allowArm,#allowPartial,#needSmtp") + .forEach((el) => (el.onchange = () => requote())); + $("#bestPerProvider").onchange = render; + $("#maxRtt").oninput = render; + $$(".tabs button[data-tab]").forEach((b) => (b.onclick = () => { + $$(".tabs button[data-tab]").forEach((x) => x.classList.toggle("active", x === b)); + $$(".tab").forEach((t) => t.classList.toggle("hidden", t.id !== "tab-" + b.dataset.tab)); + })); + $("#csvBtn").onclick = exportCsv; + $("#refreshBtn").onclick = refreshLive; + $("#editContaboBtn").onclick = () => openEditor("contabo"); + + S.apps = new Set(S.cat.presets.good.apps); setPreset("good"); + renderApps(); + renderNotes(); + requote(); +} + +function setPreset(k) { S.preset = k; $("#tierSelect").value = k || ""; } + +function tog(set, v, re = true) { set.has(v) ? set.delete(v) : set.add(v); if (re) requote(); } + +function renderLiveStatus() { + const st = S.cat.live_status; + const live = S.cat.providers.filter((p) => p.price_source.startsWith("live")).map((p) => p.name.split(" ")[0]); + $("#liveStatus").textContent = live.length ? `Live prices: ${live.join(", ")}` : `Catalog prices as of ${S.cat.catalog_date}`; + $("#liveStatus").title = st ? Object.entries(st).map(([k, v]) => `${k}: ${v}`).join("\n") : ""; +} + +async function refreshLive() { + const b = $("#refreshBtn"); + b.disabled = true; b.textContent = "Refreshing..."; + try { + const r = await api("/prices/refresh", {}); + S.cat = await api("/catalog"); + renderLiveStatus(); renderNotes(); requote(); + alert("Live price refresh:\n" + Object.entries(r.status).map(([k, v]) => `${k}: ${v}`).join("\n")); + } catch (e) { alert("Refresh failed: " + e.message); } + b.disabled = false; b.textContent = "Refresh live prices"; +} + +function renderApps() { + const q = $("#appSearch").value.toLowerCase(); + const box = $("#appList"); + box.innerHTML = ""; + for (const cat of S.cat.categories) { + const apps = cat.apps.filter((a) => !q || a.name.toLowerCase().includes(q)); + if (!apps.length) continue; + const d = document.createElement("details"); + d.className = "cat"; + const n = apps.filter((a) => S.apps.has(a.id)).length; + d.open = !!q || (cat.name !== "On Demand") ; + d.innerHTML = `${esc(cat.name)} ${n}/${apps.length}`; + for (const a of apps) { + const l = document.createElement("label"); + l.className = "app"; + l.innerHTML = `${esc(a.name)}${a.note ? `${esc(a.note)}` : ""}`; + l.querySelector("input").onchange = (e) => { e.target.checked ? S.apps.add(a.id) : S.apps.delete(a.id); setPreset(null); requote(); }; + d.appendChild(l); + } + box.appendChild(d); + } +} + +// ------------------------------------------------------------------ quote +let qTimer; +function requote() { clearTimeout(qTimer); qTimer = setTimeout(doQuote, 150); } + +async function doQuote() { + const body = { + apps: [...S.apps], + concurrent: +$("#concurrent").value || 5, + named: +$("#named").value || 10, + headroom: (+$("#headroom").value || 0) / 100, + disk_growth: (+$("#growth").value || 0) / 100, + extra_disk_gb: +$("#extraDisk").value || 0, + allow_burstable: $("#allowBurst").checked, + dedicated_only: $("#dedicatedOnly").checked, + allow_arm: $("#allowArm").checked, + allow_partial_compliance: $("#allowPartial").checked, + require_smtp: $("#needSmtp").checked, + continents: [...S.cont], compliance: [...S.comp], providers: [...S.prov], + override: S.override, + }; + try { S.data = await api("/quote", body); } catch (e) { $("#sizing").textContent = "Error: " + e.message; return; } + renderSizing(); + render(); +} + +function renderSizing() { + const { sizing, need } = S.data; + const preset = S.preset && S.cat.presets[S.preset]; + const ovr = (k, v) => ``; + $("#sizing").innerHTML = ` +
+
+
vCPU${need.vcpu}${ovr("vcpu", sizing.need.vcpu)}
+
RAM GB${need.ram_gb}${ovr("ram_gb", sizing.need.ram_gb)}
+
Disk GB${need.disk_gb}${ovr("disk_gb", sizing.need.disk_gb)}
+
+

Raw demand ${sizing.raw.cpu} vCPU / ${sizing.raw.ram_gb} GB / ${sizing.raw.disk_gb} GB, plus headroom and growth.
+ Shape: ${esc(sizing.family)}. Nearest standard size: ${sizing.standard.vcpu} vCPU / ${sizing.standard.ram_gb} GB.

+ ${preset && preset.federated_price ? `

Compare: ${esc(preset.label)} hosted by Federated is $${preset.federated_price}/mo (${preset.storage_gb ? `${preset.storage_gb} GB storage, ` : ""}managed, backups included).

` : ""} + ${sizing.needs_smtp ? `
The email server needs outbound TCP 25. Check the SMTP column: "blocked" clouds need an external relay (e.g. SES, Postmark, Mailgun).
` : ""} +
+
+ + ${sizing.lines.map((l) => ` + `).join("")} +
ComponentRAM MBvCPUDisk GB
${esc(l.name)} ${l.kind === "core" ? 'core' : l.kind === "shared" ? 'shared' : ""}${Math.round(l.ram_mb)}${l.cpu.toFixed(2)}${l.disk_gb.toFixed(1)}
+ ${sizing.notes.length ? `
Sizing notes (${sizing.notes.length})
    ${sizing.notes.map((n) => `
  • ${esc(n)}
  • `).join("")}
` : ""} +
`; + $$(".ovr").forEach((el) => (el.onchange = () => { + const v = +el.value; v ? (S.override[el.dataset.k] = v) : delete S.override[el.dataset.k]; requote(); + })); +} + +// ------------------------------------------------------------------ render +function latStats(r) { + const ids = [...S.cities]; + if (!ids.length) return { avg: null, max: null }; + const v = ids.map((id) => r.latency[id]); + return { avg: Math.round(v.reduce((a, b) => a + b, 0) / v.length), max: Math.max(...v) }; +} + +function filtered() { + if (!S.data) return []; + const max = +$("#maxRtt").value; + return S.data.results.map((r) => ({ ...r, ...latStats(r) })).filter((r) => !max || r.max == null || r.max <= max); +} + +function sorted(rows) { + const { key, dir } = S.sort; + return [...rows].sort((a, b) => ((a[key] > b[key]) - (a[key] < b[key])) * dir || a.total - b.total); +} + +const badges = (c) => COMP.map(([k, l]) => `${l.split(" ")[0]}`).join(""); +const latColor = (ms) => `hsl(${Math.max(0, 130 - ms * 0.6)}, 60%, 45%)`; + +const COLS = [ + ["provider", "Provider"], ["location", "Location"], ["region", "Region code"], ["model", "VM model"], + ["vcpu", "vCPU", 1], ["ram_gb", "RAM GB", 1], ["disk_gb", "Disk GB", 1], ["base_price", "VM $/mo", 1], + ["extra_storage_cost", "+Storage $/mo", 1], ["ipv4", "IPv4 $/mo", 1], ["recurring", "Monthly $/mo", 1], ["setup_fee", "Setup $ (one-time)", 1], + ["total", "Total $ (1st month)", 1], + ["storage_price_gb", "Add'l storage $/GB-mo", 1], ["compliance", "Compliance"], ["smtp25", "SMTP 25"], + ["avg", "RTT avg ms", 1], ["max", "RTT worst ms", 1], +]; + +function table(rows) { + const head = COLS.map(([k, l, n]) => `${l}${S.sort.key === k ? (S.sort.dir > 0 ? " ▲" : " ▼") : ""}`).join(""); + const body = rows.map((r, i) => ` + ${esc(r.provider)}${esc(r.location)}, ${esc(r.country)}${esc(r.region)} + ${esc(r.model)} ${r.cpu_type === "dedicated" ? "ded" : r.cpu_type === "burstable" ? "burst" : ""}${r.arch !== "x86_64" ? " arm" : ""} + ${r.vcpu}${r.ram_gb} + ${r.disk_gb || "-"}${r.extra_storage_gb ? ` +${r.extra_storage_gb}` : ""} + ${usd(r.base_price)}${r.extra_storage_cost ? usd(r.extra_storage_cost) : "-"} + ${r.ipv4 ? usd(r.ipv4) : "-"} + ${usd(r.recurring)}${r.setup_fee ? usd(r.setup_fee) : "-"} + ${usd(r.total)}${r.price_confidence === "low" ? "*" : ""} + ${r.storage_price_gb != null ? "$" + r.storage_price_gb.toFixed(3) : `n/a`} + ${badges(r.compliance)}${esc(r.smtp25)} + ${r.avg ?? "-"}${r.max ?? "-"} + `).join(""); + return `${head}${body}
`; +} + +function wire(container, rows) { + $$("th[data-k]", container).forEach((th) => (th.onclick = () => { + const k = th.dataset.k; + S.sort = { key: k, dir: S.sort.key === k ? -S.sort.dir : 1 }; + render(); + })); + $$("tr.row", container).forEach((tr) => (tr.onclick = () => showDetail(rows[+tr.dataset.i]))); +} + +function render() { + const rows = filtered(); + $("#count").textContent = `${rows.length} region options`; + + // by region + const br = $("#tab-byregion"); + br.innerHTML = ""; + const onlyBest = $("#bestPerProvider").checked; + for (const cont of S.cat.continents) { + let rs = sorted(rows.filter((r) => r.continent === cont)); + if (onlyBest) { + const seen = new Set(); + rs = [...rs].sort((a, b) => a.total - b.total).filter((r) => !seen.has(r.provider_id) && seen.add(r.provider_id)); + rs = sorted(rs); + } + const sec = document.createElement("div"); + sec.innerHTML = `

${esc(cont)} ${rs.length ? `from ${usd(Math.min(...rs.map((r) => r.total)))} first month` : "no matching options"}

${rs.length ? table(rs) : ""}`; + br.appendChild(sec); + wire(sec, rs); + } + if (S.cat.continents.includes("Asia")) { + br.insertAdjacentHTML("beforeend", `

Asia includes the Middle East (Israel, UAE). * = low price confidence (estimate, verify with provider).

`); + } + + // all + const all = sorted(rows); + $("#tab-all").innerHTML = table(all); + wire($("#tab-all"), all); + + // matrix + const top = sorted(rows).slice(0, 120); + const cities = S.cat.cities; + $("#tab-matrix").innerHTML = `

Estimated round-trip time (ms) from each VM region to each city. Model: great-circle distance x 1.3 route factor at 204 km/ms in fibre + 3 ms, plus per-market penalties and +35 ms across the mainland-China border. Use the detail view to measure real RTT for regions with a probe endpoint. Showing ${top.length} rows in current sort order.

+ ${cities.map((c) => ``).join("")} + ${top.map((r, i) => ` + ${cities.map((c) => { const v = r.latency[c.id]; return ``; }).join("")}`).join("")} +
ProviderLocation$/mo${esc(c.name)}
${esc(r.provider.split(" (")[0])}${esc(r.location)}${usd(r.total)}${v}
`; + $$("tr.row", $("#tab-matrix")).forEach((tr) => (tr.onclick = () => showDetail(top[+tr.dataset.i]))); +} + +// ------------------------------------------------------------------ detail +function showDetail(r) { + const p = S.cat.providers.find((x) => x.id === r.provider_id); + const cities = S.cat.cities; + $("#detailBody").innerHTML = ` +

${esc(r.provider)}: ${esc(r.location)}, ${esc(r.country)} (${esc(r.region)})

+

${esc(r.model)} | ${r.vcpu} vCPU (${esc(r.cpu_type)}, ${esc(r.arch)}) | ${r.ram_gb} GB RAM | ${r.disk_gb || 0} GB included disk + ${r.extra_storage_gb ? `+ ${r.extra_storage_gb} GB ${esc(r.storage_name)}` : ""}
+ VM ${usd(r.base_price)} + storage ${usd(r.extra_storage_cost)} + IPv4 ${usd(r.ipv4)} = ${usd(r.recurring)}/month + ${r.setup_fee ? ` + ${usd(r.setup_fee)} one-time setup = ${usd(r.total)} first month` : ""} + (${(r.recurring * 12 + r.setup_fee).toFixed(0)} USD first year; price source: ${esc(r.price_source)}, confidence ${esc(r.price_confidence)})

+

Additional storage: ${r.storage_price_gb != null ? `$${r.storage_price_gb.toFixed(3)}/GB-month (${esc(r.storage_name)})` : esc(r.storage_name)}. + Egress: ${esc(r.egress.note || (r.egress.per_gb != null ? `$${r.egress.per_gb}/GB after ${r.egress.included_gb ?? 0} GB` : "-"))}. SMTP port 25: ${esc(r.smtp25)}.

+

${badges(r.compliance)} ${esc(p.compliance_note)}

+ ${r.alternatives.length ? `

Next-best plans in this region

+ ${r.alternatives.map((a) => ``).join("")}
ModelvCPURAMDiskTotal $ (1st month)
${esc(a.model)} ${esc(a.cpu_type)}${a.vcpu}${a.ram_gb}${a.disk_gb}${a.extra_storage_gb ? "+" + a.extra_storage_gb : ""}${usd(a.total)}
` : ""} +

Latency to all cities (estimated RTT ms)

+ ${r.ping_host ? `

Real measurement uses Globalping community probes (TCP ping to ${esc(r.ping_host)}). Free tier is rate-limited.

` : `

No public probe endpoint is configured for this region, so only estimates are shown.

`} + ${r.ping_host ? "" : ""} + ${cities.map((c) => ` + ${r.ping_host ? `` : ""}`).join("")} +
CityEst. RTTMeasured
${esc(c.name)}, ${esc(c.country)}${r.latency[c.id]}
`; + $$(".meas", $("#detailBody")).forEach((b) => (b.onclick = async () => { + const out = $("#m-" + b.dataset.c); + b.disabled = true; out.textContent = "measuring..."; + try { + const m = await api("/latency/measure", { host: r.ping_host, city: b.dataset.c }); + out.innerHTML = `${m.min_ms} ms${m.probe_scope === "country" ? ' (no probe in this city; country-level)' : ""} ${m.results.map((x) => esc(x.probe) + ": " + x.avg_ms).join("; ")}`; + } catch (e) { out.textContent = "failed: " + e.message.slice(0, 120); } + b.disabled = false; + })); + $("#detail").showModal(); +} + +// ------------------------------------------------------------------ notes +function renderNotes() { + const ps = S.cat.providers; + $("#tab-notes").innerHTML = `
+

Methodology

+
    +
  • Sizing: each app has an idle footprint plus per-concurrent-user RAM/CPU and per-named-user disk. Shared databases (PostgreSQL, MariaDB, Redis, etc.) are counted once. OS + Docker reserve 1 GB RAM and 30 GB disk (Federated reserves 30 GB). Headroom and growth are then applied, and the minimum is 2 vCPU / 2 GB / 40 GB.
  • +
  • Matching: in every region, the cheapest plan with at least the required vCPU and RAM wins. If its bundled disk is too small, block storage is added at that provider's rate. Providers without block storage must fit the disk in the plan. Public IPv4 charges are included in the total.
  • +
  • Prices: USD per month, on-demand. "Total (1st month)" adds any one-time setup fee (currently Contabo only) to the monthly cost, Linux, before tax/VAT, no commitment discounts (1-3 year reservations typically save 30-60% on AWS/Azure/GCP/OCI). Live API pricing is used where available (${ps.filter((p) => p.live).map((p) => esc(p.name)).join(", ")}). Otherwise the catalog is dated ${esc(S.cat.catalog_date)}. ${esc(S.cat.fx_note)}
  • +
  • Latency: modelled from geography (see Latency matrix tab). Real routes vary by ISP. Use "measure" in the detail view for live probes.
  • +
  • Compliance: provider-level attestations for IaaS compute. "yes" = attested, with a BAA available for HIPAA. "partial" = only some products/regions, or self-declared. You remain responsible for your own controls, and HIPAA requires a signed BAA.
  • +
+

Providers: API documentation and references

+ + ${ps.map((p) => ` + + + + + + + + + + + `).join("")} +
ProviderAPI docsPricing APIPricing pageCompliancePrice sourceAdd'l storageIPv4EgressSMTP 25
${esc(p.name)}
${p.region_count} regions
API reference${p.api_docs_note ? `
${esc(p.api_docs_note)}` : ""}
${p.pricing_api ? `pricing API` : 'none public'}pricing${badges(p.compliance)}
compliance page
${esc(p.price_source)}
confidence: ${p.price_confidence}${p.manual && isAdmin() ? `
` : ""}
${p.setup_fee ? `Setup fee ${usd(p.setup_fee.usd)}: ${esc(p.setup_fee.note)}
` : ""}${p.storage.price_gb != null ? `$${p.storage.price_gb}/GB-mo` : ""} ${esc(p.storage.name)}
${p.ipv4_monthly ? usd(p.ipv4_monthly) : "incl."}${esc(p.egress.note || (p.egress.per_gb != null ? `$${p.egress.per_gb}/GB (${p.egress.included_gb ?? 0} GB free)` : ""))}${esc(p.smtp25)}
${esc(p.compliance_note)}
`; + $$(".edit-manual").forEach((b) => (b.onclick = () => openEditor(b.dataset.p))); +} + +// ------------------------------------------------------------------ manual price editor +const num = (v) => { const m = String(v ?? "").replace(/,/g, ".").match(/-?\d+(\.\d+)?/); return m ? +m[0] : NaN; }; + +function parsePastedTable(text) { + // Accepts markdown/pipe, tab or CSV tables with a header row naming the columns. + const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !/^\|?\s*:?-{2,}/.test(l)); + const split = (l) => (l.includes("|") ? l.replace(/^\|/, "").replace(/\|$/, "").split("|") : l.includes("\t") ? l.split("\t") : l.split(",")).map((c) => c.trim()); + const hi = lines.findIndex((l) => /vcpu|cpu|core/i.test(l) && /ram|memory/i.test(l)); + if (hi < 0) throw new Error("No header row with vCPU and RAM columns found."); + const hdr = split(lines[hi]).map((h) => h.toLowerCase()); + const col = (re) => hdr.findIndex((h) => re.test(h)); + const c = { code: col(/code|id|sku/), name: col(/name|plan|product/), vcpu: col(/vcpu|cpu|core/), ram: col(/ram|memory/), + disk: col(/storage|disk|ssd|nvme/), price: col(/price|€|\$|cost|month/), speed: col(/speed|port|bandwidth|network/) }; + if (c.price < 0) throw new Error("No price column found."); + const plans = []; + for (const l of lines.slice(hi + 1)) { + const r = split(l); + const p = { code: c.code >= 0 ? r[c.code] : "", name: c.name >= 0 ? r[c.name] : "", vcpu: num(r[c.vcpu]), ram_gb: num(r[c.ram]), + disk_gb: c.disk >= 0 ? num(r[c.disk]) : 0, price: num(r[c.price]), cpu_type: "shared", + note: [c.disk >= 0 && /ssd|nvme/i.test(r[c.disk]) ? (r[c.disk].match(/ssd|nvme/i) || [""])[0].toUpperCase() : "", c.speed >= 0 ? r[c.speed] : ""].filter(Boolean).join(", ") }; + if (!p.name) p.name = p.code || `Plan ${plans.length + 1}`; + if ([p.vcpu, p.ram_gb, p.price].some(isNaN)) continue; + plans.push(p); + } + if (!plans.length) throw new Error("No plan rows could be parsed."); + const cur = /€|eur/i.test(text) ? "EUR" : /\$|usd/i.test(text) ? "USD" : null; + return { plans, currency: cur }; +} + +async function openEditor(pid) { + const d = await api(`/providers/${pid}/price-sheet`); + const sh = d.sheet; + const body = $("#editorBody"); + const planRow = (p = {}) => ` + + + + + `; + body.innerHTML = ` +

Edit ${esc(d.provider)} prices

+

${d.is_default ? "Showing the built-in price sheet." : `Saved sheet, last updated ${esc(sh.updated_at)}.`} + Prices are per month before VAT. Saved changes apply to all quotes immediately.

+
+ + + + +
+

Plans

+ + ${sh.plans.map(planRow).join("")}
CodeNamevCPURAM GBDisk GBPrice/moCPUNote
+ +
Paste a table (markdown, tab-separated or CSV, with a header row; replaces the plans above) + + +
+

Location surcharge per region (%)

+

Added to every plan price in that region. 0 = same price as the sheet.

+ + ${d.regions.map((r) => ` + `).join("")} +
RegionCodeSurcharge %
${esc(r.label)}, ${esc(r.country)}${esc(r.code)}
+

+
+
`; + const wireDel = () => $$(".del", body).forEach((b) => (b.onclick = () => b.closest("tr").remove())); + wireDel(); + $("#edAdd").onclick = () => { $("#edPlans tbody").insertAdjacentHTML("beforeend", planRow()); wireDel(); }; + $("#edParse").onclick = () => { + try { + const { plans, currency } = parsePastedTable($("#edPaste").value); + $("#edPlans tbody").innerHTML = plans.map(planRow).join(""); wireDel(); + if (currency) $("#edCur").value = currency; + $("#edParseMsg").textContent = `Loaded ${plans.length} plans${currency ? ` (${currency})` : ""}. Review, then Save.`; + } catch (e) { $("#edParseMsg").textContent = e.message; } + }; + $("#edCancel").onclick = () => $("#editor").close(); + $("#edReset").onclick = async () => { + if (!confirm("Discard saved Contabo prices and go back to the built-in sheet?")) return; + try { await api(`/providers/${pid}/price-sheet`, undefined, "DELETE"); } catch (e) { alert("Not reset: " + e.message); return; } + $("#editor").close(); await afterPriceChange(); + }; + $("#edSave").onclick = async () => { + const plans = $$("#edPlans tbody tr").map((tr) => { + const o = {}; + $$("[data-f]", tr).forEach((el) => { const f = el.dataset.f; o[f] = ["vcpu", "ram_gb", "disk_gb", "price"].includes(f) ? num(el.value) : el.value.trim(); }); + return o; + }); + const bad = plans.findIndex((p) => !p.name || [p.vcpu, p.ram_gb, p.price].some(isNaN)); + if (bad >= 0) { $("#edErr").textContent = `Plan row ${bad + 1}: name, vCPU, RAM and price are required.`; return; } + plans.forEach((p) => { if (isNaN(p.disk_gb)) p.disk_gb = 0; }); + const pct = {}; $$(".edPct", body).forEach((el) => (pct[el.dataset.r] = num(el.value) || 0)); + const sheet = { currency: $("#edCur").value, fx: num($("#edFx").value), setup_fee: num($("#edSetup").value) || 0, + setup_fee_note: $("#edSetupNote").value.trim(), plans, region_surcharge_pct: pct }; + try { await api(`/providers/${pid}/price-sheet`, sheet, "PUT"); } + catch (e) { $("#edErr").textContent = "Not saved: " + e.message; return; } + $("#editor").close(); await afterPriceChange(); + }; + $("#editor").showModal(); +} + +async function afterPriceChange() { + S.cat = await api("/catalog"); + renderLiveStatus(); renderNotes(); requote(); +} + +// ------------------------------------------------------------------ accounts +const isAdmin = () => S.me?.role === "admin"; +const when = (t) => (t ? new Date(t * 1000).toLocaleString() : "never"); + +function applyRole() { + $$(".admin-only").forEach((el) => el.classList.toggle("hidden", !isAdmin())); + $("#userBtn").textContent = `${S.me.username} ▾`; + $("#userInfo").textContent = `Signed in as ${S.me.username} (${S.me.role})`; +} + +function initAccountMenu() { + const btn = $("#userBtn"), menu = $("#userMenu"); + const close = () => { menu.classList.add("hidden"); btn.setAttribute("aria-expanded", "false"); }; + btn.onclick = (e) => { e.stopPropagation(); menu.classList.toggle("hidden"); btn.setAttribute("aria-expanded", String(!menu.classList.contains("hidden"))); }; + document.addEventListener("click", close); + document.addEventListener("keydown", (e) => e.key === "Escape" && close()); + $$("#userMenu [data-act]").forEach((b) => (b.onclick = async () => { + close(); + const act = b.dataset.act; + if (act === "keys") openKeys(); + else if (act === "users") openUsers(); + else if (act === "password") openPassword(); + else if (act === "docs") window.open("/docs", "_blank", "noopener"); + else if (act === "logout") { try { await api("/auth/logout", {}); } catch (_) {} location.href = "/login"; } + })); +} + +function accountDialog(html) { + $("#accountBody").innerHTML = html; + if (!$("#account").open) $("#account").showModal(); + return $("#accountBody"); +} + +async function openKeys(showAll = false, fresh = null) { + let keys, users = []; + try { + keys = await api(showAll ? "/keys?all=true" : "/keys"); + if (isAdmin()) users = await api("/users"); + } catch (e) { alert(e.message); return; } + const body = accountDialog(` +

API keys

+

Send a key in the X-API-Key header (or Authorization: Bearer). A key acts with its + owner's role${isAdmin() ? "" : " (yours: user)"}. Keys are shown once, when created. Store them somewhere safe.

+ ${fresh ? `
New key "${esc(fresh.name)}"${fresh.username ? ` for ${esc(fresh.username)}` : ""}: copy it now, it won't be shown again. +
${esc(fresh.key)}
` : ""} +

Create a key

+
+ + + ${isAdmin() ? `` : ""} + +
+

+

${showAll ? "All keys" : "Your keys"} ${isAdmin() ? `` : ""}

+ ${keys.length ? `${showAll ? "" : ""} + ${keys.map((k) => `${showAll ? `` : ""} + + `).join("")} +
NameKeyAccountCreatedExpiresLast used
${esc(k.name)}${esc(k.prefix)}${esc(k.username)}${when(k.created_at)}${k.expires_at ? when(k.expires_at) + (k.expired ? ' expired' : "") : "never"}${when(k.last_used)}
` : '

No keys yet.

'}`); + $("#copyKey")?.addEventListener("click", async () => { + try { await navigator.clipboard.writeText(fresh.key); $("#copyMsg").textContent = "Copied."; } + catch (_) { $("#copyMsg").textContent = "Select the key and copy it manually."; } + }); + $("#kAll")?.addEventListener("change", (e) => openKeys(e.target.checked, fresh)); + $("#kCreate").onclick = async () => { + const req = { name: $("#kName").value.trim() || "API key" }; + const days = +$("#kDays").value; if (days) req.expires_days = days; + if (isAdmin()) req.user_id = +$("#kUser").value; + try { const k = await api("/keys", req); openKeys(showAll, k); } + catch (e) { $("#kErr").textContent = e.message; } + }; + $$(".revoke", body).forEach((b) => (b.onclick = async () => { + if (!confirm(`Revoke API key "${b.dataset.name}"? Anything using it will stop working immediately.`)) return; + try { await api(`/keys/${b.dataset.id}`, undefined, "DELETE"); openKeys(showAll); } catch (e) { alert(e.message); } + })); +} + +async function openUsers(note = "") { + let users; + try { users = await api("/users"); } catch (e) { alert(e.message); return; } + const body = accountDialog(` +

Users

+

Admins manage accounts, all API keys and prices. Users can use Coremarket and manage their own API keys. + Disabled accounts can't sign in and their API keys stop working.

+

Create an account

+
+ + + + +
+

${esc(note)}

+ + ${users.map((u) => { + const me = u.id === S.me.id; + return ` + + + + + `; + }).join("")} +
UsernameRoleStatusAPI keysLast sign-inCreated
${esc(u.username)}${me ? ' you' : ""}${me ? u.role : ``}${u.disabled ? 'disabled' : "active"}${u.api_keys}${when(u.last_login)}${when(u.created_at)}${me ? "" : ` + `}
`); + const act = async (fn, okMsg) => { try { await fn(); openUsers(okMsg); } catch (e) { openUsers("Error: " + e.message); } }; + $("#uCreate").onclick = () => act(() => api("/users", { username: $("#uName").value.trim(), password: $("#uPass").value, role: $("#uRole").value }), + `Created account "${$("#uName").value.trim()}".`); + $$("tr[data-id]", body).forEach((tr) => { + const id = tr.dataset.id, name = tr.dataset.name; + tr.querySelector(".uRoleSel")?.addEventListener("change", (e) => act(() => api(`/users/${id}`, { role: e.target.value }, "PATCH"), `${name} is now ${e.target.value}.`)); + tr.querySelector(".uToggle")?.addEventListener("click", (e) => { + const dis = e.target.textContent === "Disable"; + act(() => api(`/users/${id}`, { disabled: dis }, "PATCH"), `${name} ${dis ? "disabled" : "enabled"}.`); + }); + tr.querySelector(".uReset")?.addEventListener("click", () => { + const pw = prompt(`New password for ${name} (min 10 characters). They will be signed out everywhere:`); + if (pw) act(() => api(`/users/${id}`, { password: pw }, "PATCH"), `Password for ${name} reset.`); + }); + tr.querySelector(".uDelete")?.addEventListener("click", () => { + if (confirm(`Delete account "${name}" and all its API keys? This cannot be undone.`)) + act(() => api(`/users/${id}`, undefined, "DELETE"), `Deleted ${name}.`); + }); + }); +} + +function openPassword() { + accountDialog(` +

Change password

+

Your other signed-in sessions will be signed out. API keys keep working.

+
+ + + + +
+

`); + $("#pSave").onclick = async () => { + const msg = $("#pMsg"); + if ($("#pNew").value !== $("#pNew2").value) { msg.className = "small err"; msg.textContent = "The new passwords don't match."; return; } + try { + await api("/auth/password", { current_password: $("#pCur").value, new_password: $("#pNew").value }); + msg.className = "small ok"; msg.textContent = "Password changed."; + $$("#accountBody input").forEach((i) => (i.value = "")); + } catch (e) { msg.className = "small err"; msg.textContent = e.message; } + }; +} + +// ------------------------------------------------------------------ csv +function exportCsv() { + const rows = sorted(filtered()); + const cities = S.cat.cities; + const hdr = ["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", ...cities.map((c) => "rtt_ms_" + c.name)]; + const q = (v) => `"${String(v ?? "").replace(/"/g, '""')}"`; + const lines = [hdr.map(q).join(",")].concat(rows.map((r) => [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, ...cities.map((c) => r.latency[c.id])].map(q).join(","))); + const a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob([lines.join("\n")], { type: "text/csv" })); + a.download = `coremarket-${new Date().toISOString().slice(0, 10)}.csv`; + a.click(); +} + +init(); diff --git a/app/static/index.html b/app/static/index.html new file mode 100644 index 0000000..eb044f8 --- /dev/null +++ b/app/static/index.html @@ -0,0 +1,113 @@ + + + + + +Coremarket: Federated Core VM sizing & cloud pricing + + + +
+

Coremarket

+ Size a Federated Core stack, then price the VM across clouds and regions + + + + + +
+ +
+ + +
+
+

2. Workload

+
+ + + + + + + + +
+
+
+ +
+

3. Filters

+
+
Regions
+
Must have compliance +
+ +
+
Other + + +
+
Providers
+
+
+
Latency focus cities (columns show avg / worst estimated RTT to these) +
+
+
Max RTT to focus cities + +
+
+
+ +
+
+ + + + + + + +
+
+ + + +
+
+
+ +
+
+ +
+
+
+
+ + + diff --git a/app/static/login.html b/app/static/login.html new file mode 100644 index 0000000..2ee4b62 --- /dev/null +++ b/app/static/login.html @@ -0,0 +1,45 @@ + + + + + +Sign in: Coremarket + + + + + + + diff --git a/app/static/style.css b/app/static/style.css new file mode 100644 index 0000000..f3eeb16 --- /dev/null +++ b/app/static/style.css @@ -0,0 +1,102 @@ +:root { + --bg: #f6f7f9; --card: #fff; --fg: #1d2330; --muted: #6b7385; --line: #e2e5eb; + --accent: #2f6fde; --yes: #1f8a4c; --partial: #b7791f; --no: #b8bcc6; +} +@media (prefers-color-scheme: dark) { + :root { --bg: #14171d; --card: #1c2029; --fg: #e6e9ef; --muted: #98a0b3; --line: #2c3240; + --accent: #6b9cff; --yes: #4cc483; --partial: #e0a84a; --no: #555c6b; } +} +* { box-sizing: border-box; } +body { margin: 0; font: 14px/1.45 system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: var(--bg); color: var(--fg); } +header { display: flex; align-items: center; gap: 1rem; padding: .7rem 1.2rem; border-bottom: 1px solid var(--line); background: var(--card); position: sticky; top: 0; z-index: 5; } +header h1 { margin: 0; font-size: 1.3rem; } +.sub { color: var(--muted); } +.spacer { flex: 1; } +.layout { display: grid; grid-template-columns: 300px 1fr; gap: 1rem; padding: 1rem; } +aside { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .8rem; max-height: calc(100vh - 90px); overflow: auto; position: sticky; top: 70px; } +main { min-width: 0; } +.card { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .9rem 1rem; margin-bottom: 1rem; } +h2 { font-size: 1rem; margin: 0 0 .6rem; } +h3 { font-size: .95rem; margin: 1rem 0 .4rem; } +.muted { color: var(--muted); } .small { font-size: 12px; } +input[type=number], input[type=search] { padding: .3rem .4rem; border: 1px solid var(--line); border-radius: 5px; background: var(--bg); color: var(--fg); } +input[type=search] { width: 100%; margin: .4rem 0; } +label { display: flex; flex-direction: column; gap: .2rem; font-size: 12px; color: var(--muted); } +label.chk { flex-direction: row; align-items: center; gap: .35rem; color: var(--fg); } +button { cursor: pointer; border: 1px solid var(--accent); background: var(--accent); color: #fff; border-radius: 5px; padding: .3rem .7rem; font: inherit; } +button.ghost { background: transparent; color: var(--accent); } +button:disabled { opacity: .5; cursor: wait; } +.grid4 { display: grid; grid-template-columns: repeat(4, minmax(140px, 1fr)); gap: .6rem 1rem; } +.presets { display: flex; gap: .4rem; align-items: end; } +.presets .tier { flex: 1; } +.presets select { width: 100%; padding: .3rem .4rem; border: 1px solid var(--line); border-radius: 5px; background: var(--bg); color: var(--fg); font: inherit; font-size: 13px; } +.presets button { font-size: 12px; padding: .3rem .6rem; } +details.cat { margin: .3rem 0; } +details.cat summary { cursor: pointer; font-weight: 600; } +.app { display: flex; flex-direction: row; gap: .4rem; align-items: flex-start; padding: .1rem 0 .1rem .4rem; font-size: 13px; } +.app small { color: var(--muted); display: block; } +.sizing { margin-top: .8rem; display: grid; grid-template-columns: 300px 1fr; gap: 1rem; } +.spec { display: flex; gap: .6rem; } +.spec div { flex: 1; text-align: center; border: 1px solid var(--line); border-radius: 8px; padding: .5rem; } +.spec b { display: block; font-size: 1.5rem; } +.spec .ovr { width: 4.5em; text-align: center; margin-top: .2rem; } +.breakdown { max-height: 240px; overflow: auto; } +.filters { display: flex; flex-wrap: wrap; gap: 1rem 2rem; margin-bottom: .6rem; } +.filters .wide { flex: 1 1 600px; } +.chips { display: flex; flex-wrap: wrap; gap: .25rem; margin-top: .3rem; } +.chip { border: 1px solid var(--line); border-radius: 12px; padding: .1rem .55rem; cursor: pointer; user-select: none; font-size: 12px; } +.chip.on { background: var(--accent); border-color: var(--accent); color: #fff; } +.tabs { display: flex; gap: .3rem; align-items: center; border-bottom: 1px solid var(--line); padding-bottom: .5rem; margin-bottom: .6rem; } +.tabs button[data-tab] { background: transparent; color: var(--fg); border-color: transparent; } +.tabs button[data-tab].active { border-color: var(--accent); color: var(--accent); } +.hidden { display: none; } +.tab { overflow-x: auto; } +table { border-collapse: collapse; width: 100%; font-size: 12.5px; } +th, td { padding: .3rem .45rem; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; } +th { position: sticky; top: 0; background: var(--card); cursor: pointer; font-weight: 600; } +td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } +tr.row:hover { background: color-mix(in srgb, var(--accent) 7%, transparent); cursor: pointer; } +.total { font-weight: 700; } +.badge { display: inline-block; min-width: 2.6em; text-align: center; border-radius: 4px; padding: 0 .25rem; margin-right: 2px; font-size: 11px; color: #fff; } +.badge.yes { background: var(--yes); } .badge.partial { background: var(--partial); } .badge.no { background: var(--no); } +.conf-low { color: var(--partial); } .conf-medium { color: var(--muted); } +.lat { font-variant-numeric: tabular-nums; text-align: right; } +.matrix td.lat { min-width: 2.6em; font-size: 11.5px; } +.matrix th.city { writing-mode: vertical-rl; transform: rotate(180deg); height: 8em; font-weight: 500; } +dialog { max-width: 1000px; width: 92vw; border: 1px solid var(--line); border-radius: 10px; background: var(--card); color: var(--fg); } +dialog::backdrop { background: rgba(0,0,0,.4); } +.notes p, .notes li { max-width: 1000px; } +.warn { border-left: 3px solid var(--partial); padding: .3rem .7rem; background: color-mix(in srgb, var(--partial) 10%, transparent); margin: .5rem 0; } +.cmp { margin-top: .5rem; font-size: 13px; } +@media (max-width: 1000px) { .layout { grid-template-columns: 1fr; } aside { position: static; max-height: none; } .sizing { grid-template-columns: 1fr; } .grid4 { grid-template-columns: repeat(2, 1fr); } } + +#editor table select { min-width: 7.5em; } +#editor table input, #editor table select { width: 100%; min-width: 4em; padding: .2rem .3rem; border: 1px solid var(--line); border-radius: 4px; background: var(--bg); color: var(--fg); font: inherit; } +#editor table input.w-name { min-width: 9em; } #editor table input.w-note { min-width: 10em; } +#editor textarea { width: 100%; min-height: 7em; font: 12px ui-monospace, monospace; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 5px; } +#editor .row-inline { display: flex; gap: 1rem; flex-wrap: wrap; align-items: end; margin: .5rem 0; } +#editor .actions { display: flex; gap: .5rem; margin-top: 1rem; } +#editor .err { color: #c0392b; } +.dlg-close { display: flex; justify-content: flex-end; margin: .5rem 0 0; } +.dlg-close.top { float: right; margin: .9rem 0 0 1rem; } + +/* account menu & dialogs */ +.menu { position: relative; } +.menu-list { position: absolute; right: 0; top: calc(100% + 4px); background: var(--card); border: 1px solid var(--line); border-radius: 8px; box-shadow: 0 6px 20px rgba(0,0,0,.15); min-width: 190px; padding: .3rem; z-index: 10; display: flex; flex-direction: column; } +.menu-list.hidden { display: none; } +.menu-list button { background: transparent; color: var(--fg); border: 0; text-align: left; padding: .4rem .6rem; border-radius: 5px; } +.menu-list button:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); } +.menu-info { padding: .3rem .6rem .4rem; border-bottom: 1px solid var(--line); margin-bottom: .2rem; } +#account { max-width: 900px; } +#account input, #account select { padding: .3rem .4rem; border: 1px solid var(--line); border-radius: 5px; background: var(--bg); color: var(--fg); font: inherit; } +#account .row-inline { display: flex; gap: .8rem; flex-wrap: wrap; align-items: end; margin: .6rem 0; } +#account td button { font-size: 12px; padding: .15rem .5rem; } +.newkey { font: 13px ui-monospace, monospace; padding: .6rem; border: 1px dashed var(--accent); border-radius: 6px; word-break: break-all; background: var(--bg); } +.err { color: #c0392b; } .ok { color: var(--yes); } +.tag { font-size: 11px; border: 1px solid var(--line); border-radius: 4px; padding: 0 .3rem; } +/* login page */ +.login-page { display: grid; place-items: center; min-height: 100vh; } +.login-card { width: min(360px, 92vw); display: flex; flex-direction: column; gap: .7rem; padding: 1.6rem; } +.login-card h1 { margin: 0; } +.login-card input { padding: .5rem; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--fg); font: inherit; font-size: 14px; } +.login-card button { padding: .5rem; } diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0bcd051 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,26 @@ +services: + coremarket: + build: . + image: coremarket:latest + ports: + - "8080:8080" + environment: + LIVE_PRICING: "1" # 0 = use bundled catalog only + LIVE_REFRESH_HOURS: "24" + EUR_USD: "1.16" + # Optional tokens for providers whose price APIs need auth (read-only tokens are enough): + DIGITALOCEAN_TOKEN: ${DIGITALOCEAN_TOKEN:-} + HCLOUD_TOKEN: ${HCLOUD_TOKEN:-} + GLOBALPING_TOKEN: ${GLOBALPING_TOKEN:-} + # First run only: creates the admin account (the app will not start without them until an account exists). + ADMIN_USERNAME: ${ADMIN_USERNAME:-} + ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} + SESSION_HOURS: ${SESSION_HOURS:-12} # how long a browser sign-in lasts + COOKIE_SECURE: ${COOKIE_SECURE:-0} # set to 1 when served over HTTPS + # Comma-separated browser origins allowed to call the API cross-site (CORS), e.g. https://example.com + CORS_ORIGINS: ${CORS_ORIGINS:-} + volumes: + - coremarket-data:/data + restart: unless-stopped +volumes: + coremarket-data: diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..4147aca --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +fastapi==0.165.0 +uvicorn[standard]==0.55.0 +httpx==0.29.0 +pydantic==2.14.4