Initial commit: VMware vSphere API simulator scaffold.

Add the FastAPI app, PostgreSQL migrations, Docker/Helm packaging, API
contracts, docs, client examples, and the unit/integration/compatibility
test suite for local client and tooling labs without a real vCenter.
This commit is contained in:
2026-07-18 04:42:11 +03:00
commit f8d3cbdd59
422 changed files with 361335 additions and 0 deletions
View File
+21
View File
@@ -0,0 +1,21 @@
"""Static web console assets."""
from __future__ import annotations
from pathlib import Path
_WEB_ROOT = Path(__file__).parent
_CONSOLE_HTML = _WEB_ROOT / "index.html"
_COMPACT_CONSOLE_HTML = _WEB_ROOT / "console.html"
def console_html() -> str:
"""Return the latest lab UI markup from disk."""
return _CONSOLE_HTML.read_text(encoding="utf-8")
def compact_console_html() -> str:
"""Return the compact vSphere session console markup."""
return _COMPACT_CONSOLE_HTML.read_text(encoding="utf-8")
+77
View File
@@ -0,0 +1,77 @@
"""Catalog-scoped compatibility summaries for the web console."""
from __future__ import annotations
from app.compatibility import CompatibilityDimension, CompatibilityReport, build_report
from app.config import Settings
from app.contracts.model import Snapshot
from app.web.contract_catalog import major_release
MethodKey = tuple[str, str]
def compatibility_payload(
snapshot: Snapshot,
major: int,
*,
implemented_methods: frozenset[MethodKey] | None,
runtime_report: CompatibilityReport | None,
runtime_version: str | None,
settings: Settings | None,
) -> dict[str, object]:
"""Build a compatibility summary for the selected catalog major."""
declared = frozenset(
(contract_path.path, method.verb.upper())
for contract_path in snapshot.paths
for method in contract_path.methods
)
implemented = (implemented_methods or frozenset()) & declared
if runtime_report is not None and runtime_report.source_version == snapshot.source_version:
payload = runtime_report.as_json()
evidence_scope = "full"
else:
dimensions: dict[CompatibilityDimension, frozenset[MethodKey]] = {
CompatibilityDimension.ROUTE_METHOD: declared,
}
if runtime_report is not None:
for dimension, methods in runtime_report.dimensions.items():
if dimension == CompatibilityDimension.ROUTE_METHOD:
continue
dimensions[dimension] = methods & declared
else:
for dimension in CompatibilityDimension:
if dimension != CompatibilityDimension.ROUTE_METHOD:
dimensions[dimension] = frozenset()
empty: frozenset[MethodKey] = frozenset()
if runtime_report is None:
observed = empty
verified = empty
incompatible = empty
regressions = empty
else:
observed = runtime_report.observed & declared
verified = runtime_report.verified & declared
incompatible = runtime_report.incompatible & declared
regressions = runtime_report.regressions & declared
catalog_report = build_report(
snapshot,
implemented=implemented,
observed=observed,
verified=verified,
dimensions=dimensions,
incompatible=incompatible,
regressions=regressions,
)
payload = catalog_report.as_json()
evidence_scope = "catalog"
release = major_release(major, settings)
payload["major"] = major
payload["catalog_version"] = snapshot.source_version
payload["latest_version"] = release.latest_version
payload["runtime_version"] = runtime_version
payload["evidence_scope"] = evidence_scope
return payload
+342
View File
@@ -0,0 +1,342 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>VMware API Emulator · Console</title>
<style>
:root {
color-scheme: dark;
--bg: #0b1020;
--panel: #121a2f;
--panel-2: #18233d;
--border: #2a3555;
--text: #e8eefc;
--muted: #93a0c0;
--accent: #8EC368;
--accent-2: #A4DB6E;
--danger: #ff6b7a;
--ok: #4ade80;
--shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
--radius: 16px;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--sans: ui-sans-serif, system-ui, -apple-system, Segoe UI, sans-serif;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
font-family: var(--sans);
background:
radial-gradient(circle at top left, rgba(122, 193, 66, 0.20), transparent 28%),
radial-gradient(circle at top right, rgba(143, 209, 79, 0.12), transparent 24%),
var(--bg);
color: var(--text);
}
.wrap { max-width: 1180px; margin: 0 auto; padding: 32px 20px 48px; }
header {
display: flex; justify-content: space-between; align-items: flex-start;
gap: 16px; margin-bottom: 28px;
}
h1 { margin: 0 0 8px; font-size: clamp(1.6rem, 2vw, 2.2rem); }
.subtitle { color: var(--muted); max-width: 56ch; line-height: 1.5; }
.links { display: flex; gap: 10px; flex-wrap: wrap; }
.links a {
color: var(--text); text-decoration: none; border: 1px solid var(--border);
background: rgba(255,255,255,0.03); padding: 8px 12px; border-radius: 999px;
font-size: 0.92rem;
}
.grid {
display: grid; grid-template-columns: repeat(12, 1fr); gap: 18px;
}
.card {
background: linear-gradient(180deg, rgba(255,255,255,0.03), transparent), var(--panel);
border: 1px solid var(--border); border-radius: var(--radius); padding: 18px;
box-shadow: var(--shadow);
}
.span-4 { grid-column: span 4; }
.span-5 { grid-column: span 5; }
.span-7 { grid-column: span 7; }
.span-8 { grid-column: span 8; }
.span-12 { grid-column: span 12; }
@media (max-width: 900px) {
.span-4, .span-5, .span-7, .span-8 { grid-column: span 12; }
}
h2 { margin: 0 0 14px; font-size: 1rem; letter-spacing: 0.02em; }
label { display: block; font-size: 0.85rem; color: var(--muted); margin-bottom: 6px; }
input, select, textarea, button {
width: 100%; font: inherit; border-radius: 12px; border: 1px solid var(--border);
background: var(--panel-2); color: var(--text); padding: 11px 12px;
}
textarea { min-height: 120px; font-family: var(--mono); font-size: 0.88rem; resize: vertical; }
button {
cursor: pointer; background: linear-gradient(135deg, var(--accent), #6FA84A);
border: none; font-weight: 600; margin-top: 10px;
}
button.secondary {
background: transparent; border: 1px solid var(--border); font-weight: 500;
}
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
.stat {
background: var(--panel-2); border: 1px solid var(--border); border-radius: 14px;
padding: 14px;
}
.stat .label { color: var(--muted); font-size: 0.82rem; margin-bottom: 6px; }
.stat .value { font-size: 1.25rem; font-weight: 700; }
.pill {
display: inline-flex; align-items: center; gap: 8px; padding: 6px 10px;
border-radius: 999px; background: rgba(74, 222, 128, 0.12); color: var(--ok);
border: 1px solid rgba(74, 222, 128, 0.25); font-size: 0.85rem;
}
.pill.warn { color: #fbbf24; background: rgba(251, 191, 36, 0.12); border-color: rgba(251,191,36,0.25); }
pre {
margin: 0; padding: 14px; border-radius: 14px; background: #070b14;
border: 1px solid var(--border); overflow: auto; font-family: var(--mono);
font-size: 0.84rem; line-height: 1.45; min-height: 180px;
}
.actions { display: flex; gap: 10px; flex-wrap: wrap; }
.actions button { width: auto; flex: 1 1 140px; margin-top: 0; }
.hint { color: var(--muted); font-size: 0.85rem; margin-top: 8px; line-height: 1.4; }
.error { color: var(--danger); }
</style>
</head>
<body>
<div class="wrap">
<header>
<div>
<h1>VMware API Emulator</h1>
<p class="subtitle">
Lab console for the vSphere REST surface. Sign in with a session, inspect
inventory, and send requests using the <code>vmware-api-session-id</code> header.
</p>
</div>
<div class="links">
<a href="/" rel="noreferrer">Full lab UI</a>
<a href="/docs" target="_blank" rel="noreferrer">OpenAPI</a>
<a href="/health/ready" target="_blank" rel="noreferrer">Readiness</a>
</div>
</header>
<div class="grid">
<section class="card span-4">
<h2>Authentication</h2>
<label for="username">Username</label>
<input id="username" value="administrator@vsphere.local" autocomplete="username">
<label for="password">Password</label>
<input id="password" type="password" value="VMware1!" autocomplete="current-password">
<button id="login-btn">Create session</button>
<button id="logout-btn" class="secondary">Delete session</button>
<p class="hint">Default lab user: <code>administrator@vsphere.local</code> / <code>VMware1!</code>.</p>
<label for="session">vmware-api-session-id</label>
<input id="session" readonly>
<div id="auth-status" class="pill warn" style="margin-top:12px;">Not authenticated</div>
</section>
<section class="card span-8">
<h2>Inventory snapshot</h2>
<div class="stats">
<div class="stat"><div class="label">vCenter</div><div class="value" id="stat-version"></div></div>
<div class="stat"><div class="label">Hosts</div><div class="value" id="stat-hosts"></div></div>
<div class="stat"><div class="label">VMs</div><div class="value" id="stat-vms"></div></div>
</div>
<div class="actions" style="margin-top:14px;">
<button class="secondary" data-action="refresh">Refresh overview</button>
<button class="secondary" data-action="hosts">GET /api/vcenter/host</button>
<button class="secondary" data-action="vms">GET /api/vcenter/vm</button>
</div>
</section>
<section class="card span-5">
<h2>Quick request</h2>
<div class="row">
<div>
<label for="method">Method</label>
<select id="method">
<option>GET</option>
<option>POST</option>
<option>PUT</option>
<option>PATCH</option>
<option>DELETE</option>
</select>
</div>
<div>
<label for="path">Path</label>
<input id="path" value="/api/vcenter/vm">
</div>
</div>
<label for="body">Body (JSON)</label>
<textarea id="body"></textarea>
<button id="send-btn">Send request</button>
<p class="hint">Authenticated requests attach the session header automatically.</p>
</section>
<section class="card span-7">
<h2>Response</h2>
<pre id="output">Waiting for a request…</pre>
</section>
<section class="card span-12">
<h2>Task lookup</h2>
<div class="row">
<div>
<label for="task">Task id</label>
<input id="task" placeholder="task-… from a mutation">
</div>
<div>
<label for="vm">VM id (optional)</label>
<input id="vm" placeholder="vm-111">
</div>
</div>
<div class="actions" style="margin-top:10px;">
<button class="secondary" id="task-status-btn">GET /api/cis/tasks/{task}</button>
<button class="secondary" id="vm-get-btn">GET /api/vcenter/vm/{vm}</button>
</div>
</section>
</div>
</div>
<script>
const output = document.getElementById("output");
const sessionInput = document.getElementById("session");
const authStatus = document.getElementById("auth-status");
const LS_KEY = "vmware-console-session";
function show(data, status) {
output.textContent = JSON.stringify({ status, data }, null, 2);
output.classList.remove("error");
}
function sessionId() {
return (sessionInput.value || "").trim();
}
function setAuthUi(username) {
const sid = sessionId();
if (sid && username) {
authStatus.textContent = `Authenticated as ${username}`;
authStatus.classList.remove("warn");
document.cookie = `vmware-api-session-id=${encodeURIComponent(sid)}; path=/; SameSite=Strict`;
localStorage.setItem(LS_KEY, JSON.stringify({ ticket: sid, username }));
} else {
authStatus.textContent = "Not authenticated";
authStatus.classList.add("warn");
document.cookie = "vmware-api-session-id=; Max-Age=0; path=/; SameSite=Strict";
localStorage.removeItem(LS_KEY);
}
}
async function apiFetch(path, options = {}) {
const headers = new Headers(options.headers || {});
headers.set("Accept", "application/json");
const sid = sessionId();
if (sid) headers.set("vmware-api-session-id", sid);
const response = await fetch(path, { ...options, headers, credentials: "include" });
let data;
const text = await response.text();
try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; }
show(data, response.status);
return { response, data };
}
async function refreshOverview() {
const version = await apiFetch("/api/appliance/system/version");
document.getElementById("stat-version").textContent =
version.data?.version || "unknown";
if (!sessionId()) {
const demo = await fetch("/ui/api/demo/state").then((r) => r.json()).catch(() => null);
document.getElementById("stat-hosts").textContent = demo?.vsphere?.hosts ?? "—";
document.getElementById("stat-vms").textContent = demo?.vsphere?.vms ?? "—";
return;
}
const hosts = await apiFetch("/api/vcenter/host");
const demo = await fetch("/ui/api/demo/state").then((r) => r.json()).catch(() => null);
document.getElementById("stat-hosts").textContent =
Array.isArray(hosts.data) ? hosts.data.length : (demo?.vsphere?.hosts ?? "0");
document.getElementById("stat-vms").textContent = demo?.vsphere?.vms ?? "—";
}
document.getElementById("login-btn").addEventListener("click", async () => {
const username = document.getElementById("username").value.trim();
const password = document.getElementById("password").value;
const basic = btoa(`${username}:${password}`);
const result = await apiFetch("/api/session", {
method: "POST",
headers: { Authorization: `Basic ${basic}` },
});
let sid = typeof result.data === "string" ? result.data : result.data?.value || null;
sid = sid || result.response.headers.get("vmware-api-session-id");
if (result.response.ok && sid) {
sessionInput.value = sid;
setAuthUi(username);
await refreshOverview();
} else {
sessionInput.value = "";
setAuthUi(null);
authStatus.textContent = "Authentication failed";
authStatus.classList.add("warn");
}
});
document.getElementById("logout-btn").addEventListener("click", async () => {
if (sessionId()) {
await apiFetch("/api/session", { method: "DELETE" });
}
sessionInput.value = "";
setAuthUi(null);
await refreshOverview();
});
document.getElementById("send-btn").addEventListener("click", async () => {
const method = document.getElementById("method").value;
const path = document.getElementById("path").value.trim();
const rawBody = document.getElementById("body").value.trim();
const options = { method };
if (rawBody && method !== "GET" && method !== "DELETE") {
options.headers = { "Content-Type": "application/json" };
options.body = rawBody;
}
await apiFetch(path, options);
});
document.querySelector('[data-action="refresh"]').addEventListener("click", () => refreshOverview());
document.querySelector('[data-action="hosts"]').addEventListener("click", () =>
apiFetch("/api/vcenter/host"));
document.querySelector('[data-action="vms"]').addEventListener("click", () =>
apiFetch("/api/vcenter/vm"));
document.getElementById("task-status-btn").addEventListener("click", async () => {
const task = encodeURIComponent(document.getElementById("task").value.trim());
if (!task) {
show({ error: "Enter a task id" }, 0);
return;
}
await apiFetch(`/api/cis/tasks/${task}`);
});
document.getElementById("vm-get-btn").addEventListener("click", async () => {
const vm = encodeURIComponent(document.getElementById("vm").value.trim());
if (!vm) {
show({ error: "Enter a VM id" }, 0);
return;
}
await apiFetch(`/api/vcenter/vm/${vm}`);
});
try {
const stored = JSON.parse(localStorage.getItem(LS_KEY) || "null");
if (stored?.ticket) {
sessionInput.value = stored.ticket;
setAuthUi(stored.username || "session");
}
} catch {
/* ignore */
}
refreshOverview().catch((error) => {
output.textContent = String(error);
output.classList.add("error");
});
</script>
</body>
</html>
+358
View File
@@ -0,0 +1,358 @@
"""Lazy-loaded API contract catalog grouped by vSphere release labels.
Wire format keeps integer ``major`` ids (6-9) for hot-swap compatibility with the
console; each id maps to a vSphere version label (7.0...8.0 U2).
Bundled snapshots are temporary stubs carried from the Proxmox skeleton until
real vSphere REST/SOAP contracts land in a later iteration.
"""
from __future__ import annotations
import asyncio
import re
from dataclasses import dataclass
from datetime import UTC, datetime
from functools import lru_cache
from pathlib import Path
from app.api.openapi import contract_openapi_tag
from app.config import Settings
from app.contracts.examples import path_param_example, schema_example
from app.contracts.importer import RemoteSourceImporter
from app.contracts.model import Method, Parameter, Snapshot
from app.contracts.normalize import normalize_snapshot
from app.contracts.source import ApiViewerParser
from app.contracts.store import RevisionStore
_PATH_PARAM = re.compile(r"\{([^{}]+)\}")
@dataclass(frozen=True, slots=True)
class MajorReleaseMeta:
major: int
series: str
latest_version: str
bundled_revision: str | None = None
@dataclass(frozen=True, slots=True)
class MajorRelease:
major: int
series: str
latest_version: str
artifact_url: str
bundled_revision: str | None = None
# Integer majors are stable wire ids used by /ui/api/* and the console.
# Series names are the vSphere version labels shown in the UI.
_MAJOR_METADATA: tuple[MajorReleaseMeta, ...] = (
MajorReleaseMeta(
major=6,
series="vSphere 7.0",
latest_version="6.4-15", # stub contract revision label
bundled_revision="96cd7121e75cdb3efd58f79ca988f6b235a2f28e6f7eae276ae243f65d8a6724",
),
MajorReleaseMeta(
major=7,
series="vSphere 7.0 U3",
latest_version="7.4-16",
bundled_revision="2cf632fa6ea4939ca9cb7998ade688150db25b0684600f53ac0ca95730f1d99f",
),
MajorReleaseMeta(
major=8,
series="vSphere 8.0",
latest_version="8.4.5",
bundled_revision="fce6db0a784b3a9b447895895fc6ff4b4437c2dce82e5f3db99227af217726fa",
),
MajorReleaseMeta(
major=9,
series="vSphere 8.0 U2",
latest_version="9.2.3",
bundled_revision="e61a893e996d05d376579226e7dfbedbcfce8b71787adacffbc557e6e35901c1",
),
)
# Placeholder artifact URLs — temporary stubs until vSphere contracts are imported.
_DEFAULT_ARTIFACT_URLS: dict[int, str] = {
6: "stub://vmware/vsphere-7.0/api-contract",
7: "stub://vmware/vsphere-7.0u3/api-contract",
8: "stub://vmware/vsphere-8.0/api-contract",
9: "stub://vmware/vsphere-8.0u2/api-contract",
}
_SNAPSHOT_CACHE: dict[int, Snapshot] = {}
_SNAPSHOT_LOCK = asyncio.Lock()
_DEFAULT_STORE = Path("contracts")
def _artifact_urls(settings: Settings | None) -> dict[int, str]:
if settings is None:
return dict(_DEFAULT_ARTIFACT_URLS)
return settings.catalog_artifact_urls()
def get_major_releases(settings: Settings | None = None) -> tuple[MajorRelease, ...]:
urls = _artifact_urls(settings)
return tuple(
MajorRelease(
major=meta.major,
series=meta.series,
latest_version=meta.latest_version,
artifact_url=urls[meta.major],
bundled_revision=meta.bundled_revision,
)
for meta in _MAJOR_METADATA
)
def series_name(major: int, settings: Settings | None = None) -> str:
return major_release(major, settings).series
def major_release(major: int, settings: Settings | None = None) -> MajorRelease:
releases = {release.major: release for release in get_major_releases(settings)}
try:
return releases[major]
except KeyError as error:
raise ValueError(f"unsupported major version: {major}") from error
def list_majors(
*,
runtime_version: str | None,
settings: Settings | None = None,
) -> dict[str, object]:
return {
"runtime_version": runtime_version,
"majors": [
{
"major": release.major,
"series": release.series,
"latest_version": release.latest_version,
"artifact_url": release.artifact_url,
"bundled": release.bundled_revision is not None,
}
for release in get_major_releases(settings)
],
}
async def load_snapshot(
major: int,
store_root: Path | None = None,
*,
settings: Settings | None = None,
) -> Snapshot:
if major in _SNAPSHOT_CACHE:
return _SNAPSHOT_CACHE[major]
async with _SNAPSHOT_LOCK:
if major in _SNAPSHOT_CACHE:
return _SNAPSHOT_CACHE[major]
release = major_release(major, settings)
store = RevisionStore(store_root or _DEFAULT_STORE)
if release.bundled_revision is not None:
snapshot_path = store.root / release.bundled_revision / "snapshot.json"
if snapshot_path.is_file():
snapshot = Snapshot.model_validate_json(snapshot_path.read_bytes())
_SNAPSHOT_CACHE[major] = snapshot
return snapshot
existing = _find_cached_revision(store, release.latest_version)
if existing is not None:
snapshot = Snapshot.model_validate_json(existing.read_bytes())
_SNAPSHOT_CACHE[major] = snapshot
return snapshot
raw = await RemoteSourceImporter(release.artifact_url).load()
parsed = ApiViewerParser().parse(raw)
snapshot, manifest = normalize_snapshot(
parsed,
raw=raw,
source_version=release.latest_version,
retrieved_at=datetime.now(UTC),
)
try:
store.save(raw, snapshot, manifest)
except OSError:
pass
_SNAPSHOT_CACHE[major] = snapshot
return snapshot
def _find_cached_revision(store: RevisionStore, source_version: str) -> Path | None:
if not store.root.is_dir():
return None
for revision in store.list():
manifest = store.manifest(revision)
if manifest.source_version == source_version:
return store.root / revision / "snapshot.json"
return None
def _catalog_entry_path(entry: dict[str, object]) -> str:
return str(entry["path"])
def catalog_payload(
snapshot: Snapshot,
major: int,
*,
implemented_methods: frozenset[tuple[str, str]] | None = None,
settings: Settings | None = None,
) -> dict[str, object]:
grouped: dict[str, list[dict[str, object]]] = {}
for contract_path in snapshot.paths:
tag = contract_openapi_tag(contract_path.path)
methods = [
{
"verb": method.verb,
"name": method.name,
"description": method.description,
"protected": method.protected,
"implemented": (
(contract_path.path, method.verb.upper()) in implemented_methods
if implemented_methods is not None
else None
),
}
for method in contract_path.methods
]
entry: dict[str, object] = {
"path": contract_path.path,
"methods": methods,
}
grouped.setdefault(tag, []).append(entry)
categories: list[dict[str, object]] = []
for tag in sorted(grouped):
entries = grouped[tag]
categories.append(
{
"tag": tag,
"paths": sorted(entries, key=_catalog_entry_path),
}
)
release = major_release(major, settings)
return {
"major": major,
"series": release.series,
"source_version": snapshot.source_version,
"latest_version": release.latest_version,
"artifact_url": release.artifact_url,
"bundled": release.bundled_revision is not None,
"path_count": snapshot.path_count,
"method_count": snapshot.method_count,
"categories": categories,
}
def _path_param_names(path: str) -> tuple[str, ...]:
return tuple(match.group(1) for match in _PATH_PARAM.finditer(path))
def _parameter_payload(parameter: Parameter) -> dict[str, object]:
schema = parameter.definition
return {
"name": parameter.name,
"type": schema.type,
"description": schema.description,
"optional": bool(schema.optional),
"enum": list(schema.enum),
"example": schema_example(schema, name=parameter.name),
}
def method_payload(
snapshot: Snapshot,
*,
major: int,
path: str,
verb: str,
runtime_version: str | None,
implemented_methods: frozenset[tuple[str, str]] | None,
) -> dict[str, object]:
contract_path = next((item for item in snapshot.paths if item.path == path), None)
if contract_path is None:
raise KeyError(path)
method = next(
(item for item in contract_path.methods if item.verb.upper() == verb.upper()),
None,
)
if method is None:
raise KeyError(verb)
path_params = _path_param_names(path)
path_fields = [
_parameter_payload(parameter)
for parameter in method.parameters
if parameter.name in path_params
]
for name in path_params:
if name not in {field["name"] for field in path_fields}:
path_fields.append(
{
"name": name,
"type": "string",
"description": None,
"optional": False,
"enum": [],
"example": path_param_example(name) or name,
}
)
body_fields = [
_parameter_payload(parameter)
for parameter in method.parameters
if parameter.name not in path_params and "[n]" not in parameter.name
]
indexed_fields = [
_parameter_payload(parameter) for parameter in method.parameters if "[n]" in parameter.name
]
body_example = _body_example(method, path_params)
resolved_path = _resolve_path(path, path_fields)
implemented = (
(path, method.verb.upper()) in implemented_methods
if implemented_methods is not None
else None
)
return {
"major": major,
"source_version": snapshot.source_version,
"runtime_version": runtime_version,
"path": path,
"verb": method.verb.upper(),
"name": method.name,
"description": method.description,
"resolved_path": resolved_path,
"path_fields": path_fields,
"body_fields": body_fields,
"indexed_fields": indexed_fields,
"body_example": body_example,
"implemented": implemented,
}
def _resolve_path(path: str, path_fields: list[dict[str, object]]) -> str:
resolved = path
for field in path_fields:
name = str(field["name"])
example = field.get("example", name)
resolved = resolved.replace(f"{{{name}}}", str(example))
return resolved
def _body_example(method: Method, path_params: tuple[str, ...]) -> dict[str, object]:
body: dict[str, object] = {}
for parameter in method.parameters:
if parameter.name in path_params:
continue
if "[n]" in parameter.name:
concrete = parameter.name.replace("[n]", "0")
if not parameter.definition.optional:
body[concrete] = schema_example(parameter.definition, name=concrete)
continue
if parameter.definition.optional:
continue
body[parameter.name] = schema_example(parameter.definition, name=parameter.name)
return body
@lru_cache(maxsize=1)
def default_store_root() -> Path:
return _DEFAULT_STORE
+7014
View File
File diff suppressed because it is too large Load Diff
+340
View File
@@ -0,0 +1,340 @@
"""Browser console for exercising the simulator API."""
from __future__ import annotations
from pathlib import Path
from typing import Annotated
from asyncpg import Pool # type: ignore[import-untyped]
from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse
from app.api.registry import HandlerRegistry
from app.config import Settings
from app.contracts.runtime import apply_runtime_contract_locked, contract_store_root
from app.contracts.source import SourceError
from app.db.pool import AsyncpgDatabase
from app.dependencies import get_database
from app.simulation.seed import apply_seed, build_profile, simulation_state_summary
from app.web.assets import compact_console_html, console_html
from app.web.compatibility_catalog import compatibility_payload
from app.web.contract_catalog import catalog_payload, list_majors, load_snapshot, method_payload
router = APIRouter(tags=["Simulator"])
@router.get("/", response_class=HTMLResponse, include_in_schema=True)
async def console() -> HTMLResponse:
"""Interactive API console and cluster overview."""
return HTMLResponse(
console_html(),
headers={"Cache-Control": "no-store"},
)
@router.get("/console.html", response_class=HTMLResponse, include_in_schema=False)
async def compact_console() -> HTMLResponse:
"""Compact session console for quick REST smoke."""
return HTMLResponse(
compact_console_html(),
headers={"Cache-Control": "no-store"},
)
def _use_vsphere_plane(request: Request) -> bool:
settings = _settings(request)
return settings is None or not bool(getattr(settings, "enable_pve_stub", False))
@router.get("/ui/api/versions", include_in_schema=False)
async def ui_versions(request: Request) -> JSONResponse:
settings = _settings(request)
runtime_version = _runtime_version(request)
if _use_vsphere_plane(request):
from app.vsphere.contracts.catalog import list_vsphere_majors
return JSONResponse(list_vsphere_majors(runtime_version=runtime_version))
return JSONResponse(list_majors(runtime_version=runtime_version, settings=settings))
@router.get("/ui/api/catalog", include_in_schema=False)
async def ui_catalog(
request: Request,
major: Annotated[int, Query(ge=6, le=9)],
) -> JSONResponse:
if _use_vsphere_plane(request):
from app.vsphere.contracts.catalog import vsphere_catalog_payload
return JSONResponse(vsphere_catalog_payload(major))
settings = _settings(request)
try:
snapshot = await load_snapshot(major, _store_root(request), settings=settings)
except SourceError as error:
raise HTTPException(status_code=503, detail=str(error)) from error
implemented = getattr(request.app.state, "implemented_methods", None)
return JSONResponse(
catalog_payload(snapshot, major, implemented_methods=implemented, settings=settings)
)
@router.get("/ui/api/method", include_in_schema=False)
async def ui_method(
request: Request,
major: Annotated[int, Query(ge=6, le=9)],
path: Annotated[str, Query(min_length=1)],
verb: Annotated[str, Query(min_length=1)],
) -> JSONResponse:
if _use_vsphere_plane(request):
from app.vsphere.contracts.catalog import vsphere_method_payload
return JSONResponse(
vsphere_method_payload(
major=major,
path=path,
verb=verb,
runtime_version=_runtime_version(request),
)
)
settings = _settings(request)
try:
snapshot = await load_snapshot(major, _store_root(request), settings=settings)
except SourceError as error:
raise HTTPException(status_code=503, detail=str(error)) from error
runtime_version = _runtime_version(request)
implemented = getattr(request.app.state, "implemented_methods", None)
try:
payload = method_payload(
snapshot,
major=major,
path=path,
verb=verb,
runtime_version=runtime_version,
implemented_methods=implemented,
)
except KeyError as error:
raise HTTPException(status_code=404, detail=f"unknown contract method: {error}") from error
return JSONResponse(payload)
@router.get("/ui/api/compatibility", include_in_schema=False)
async def ui_compatibility(
request: Request,
major: Annotated[int, Query(ge=6, le=9)],
) -> JSONResponse:
if _use_vsphere_plane(request):
from app.vsphere.contracts.compatibility import vsphere_compatibility_payload
return JSONResponse(
vsphere_compatibility_payload(
major,
runtime_version=_runtime_version(request),
)
)
settings = _settings(request)
try:
snapshot = await load_snapshot(major, _store_root(request), settings=settings)
except SourceError as error:
raise HTTPException(status_code=503, detail=str(error)) from error
implemented = getattr(request.app.state, "implemented_methods", None)
runtime_report = getattr(request.app.state, "compatibility_report", None)
runtime_version = _runtime_version(request)
return JSONResponse(
compatibility_payload(
snapshot,
major,
implemented_methods=implemented,
runtime_report=runtime_report,
runtime_version=runtime_version,
settings=settings,
)
)
@router.post("/ui/api/contract/apply", include_in_schema=False)
async def ui_contract_apply(
request: Request,
major: Annotated[int, Query(ge=6, le=9)],
) -> JSONResponse:
"""Hot-swap the in-memory runtime contract to a catalog major (memory-only)."""
if _use_vsphere_plane(request):
from app.vsphere.contracts.matrix import VERSIONS, catalog_entries_for_major
meta = VERSIONS.get(major) or VERSIONS[9]
entries = catalog_entries_for_major(major)
request.app.state.vsphere_contract_major = major
request.app.state.runtime_source_version = meta["version"]
request.app.state.vsphere_implemented_methods = {(e["verb"], e["path"]) for e in entries}
return JSONResponse(
{
"ok": True,
"major": major,
"runtime_version": meta["version"],
"plane": "vsphere-rest",
"path_count": len({e["path"] for e in entries}),
"method_count": len(entries),
}
)
settings = _settings(request)
handlers = getattr(request.app.state, "handlers", None)
if (
settings is None
or settings.contract_snapshot is None
or not isinstance(handlers, HandlerRegistry)
):
raise HTTPException(status_code=503, detail="runtime contract is not available")
store_root = _store_root(request)
try:
snapshot = await load_snapshot(major, store_root, settings=settings)
except SourceError as error:
raise HTTPException(status_code=503, detail=str(error)) from error
await apply_runtime_contract_locked(
request.app,
snapshot,
handlers=handlers,
store_root=store_root,
fallback=settings.contract_fallback,
settings=settings,
require_evidence_match=False,
register_admin=True,
)
method_count = sum(len(path.methods) for path in snapshot.paths)
return JSONResponse(
{
"ok": True,
"major": major,
"runtime_version": snapshot.source_version,
"path_count": len(snapshot.paths),
"method_count": method_count,
}
)
@router.get("/ui/api/demo/state", include_in_schema=False)
async def ui_demo_state(request: Request) -> JSONResponse:
from app.vsphere.seed import vsphere_state_summary
settings = _settings(request)
try:
vsphere = await vsphere_state_summary(get_database(request))
except Exception as error:
raise HTTPException(status_code=503, detail=f"database is not ready: {error}") from error
if settings is not None and getattr(settings, "enable_pve_stub", False):
try:
pool = _database_pool(request)
except Exception as error:
raise HTTPException(status_code=503, detail=str(error)) from error
async with pool.acquire() as connection:
pve = await simulation_state_summary(connection)
return JSONResponse({"vsphere": vsphere, "proxmox_stub": pve})
return JSONResponse(
{
"vsphere": vsphere,
"loaded": vsphere.get("vms", 0) >= 100,
"label": f"{vsphere.get('hosts', 0)} hosts · {vsphere.get('vms', 0)} VMs",
}
)
@router.post("/ui/api/demo/load", include_in_schema=False)
async def ui_demo_load(request: Request) -> JSONResponse:
from app.vsphere.seed import seed_vsphere_inventory
settings = _settings(request)
summary: dict = {}
profile_name = "demo-cluster"
if settings is not None and getattr(settings, "enable_pve_stub", False):
pool = _database_pool(request)
profile = build_profile("demo-cluster")
async with pool.acquire() as connection:
await apply_seed(connection, profile)
summary = await simulation_state_summary(connection)
profile_name = profile.name
try:
vsphere = await seed_vsphere_inventory(
get_database(request), force=True, profile="demo-cluster"
)
except Exception as error:
raise HTTPException(status_code=503, detail=f"database is not ready: {error}") from error
return JSONResponse(
{"ok": True, "profile": profile_name, "summary": summary, "vsphere": vsphere}
)
@router.post("/ui/api/demo/unload", include_in_schema=False)
async def ui_demo_unload(request: Request) -> JSONResponse:
"""Reset seed, wiping API-created state first."""
from app.vsphere.seed import seed_vsphere_inventory
settings = _settings(request)
summary: dict = {}
profile_name = "small"
try:
if settings is not None and getattr(settings, "enable_pve_stub", False):
pool = _database_pool(request)
profile = build_profile("minimal")
async with pool.acquire() as connection:
await apply_seed(connection, profile)
summary = await simulation_state_summary(connection)
profile_name = profile.name
vsphere = await seed_vsphere_inventory(get_database(request), force=True, profile="small")
except HTTPException:
raise
except Exception as error:
raise HTTPException(
status_code=503, detail=f"failed to remove demo data: {error}"
) from error
return JSONResponse(
{"ok": True, "profile": profile_name, "summary": summary, "vsphere": vsphere}
)
@router.post("/ui/api/vsphere/seed", include_in_schema=False)
async def ui_vsphere_seed(request: Request) -> JSONResponse:
"""(Re)seed native vSphere inventory used by /api and /sdk."""
from app.vsphere.seed import seed_vsphere_inventory
profile = request.query_params.get("profile") or "large"
try:
result = await seed_vsphere_inventory(get_database(request), force=True, profile=profile)
except Exception as error:
raise HTTPException(status_code=500, detail=str(error)) from error
return JSONResponse({"ok": True, **result})
def _database_pool(request: Request) -> Pool:
database = get_database(request)
if not isinstance(database, AsyncpgDatabase):
raise HTTPException(status_code=503, detail="database is not available")
return database.pool
def _settings(request: Request) -> Settings | None:
return getattr(request.app.state, "settings", None)
def _runtime_version(request: Request) -> str | None:
active = getattr(request.app.state, "runtime_source_version", None)
if isinstance(active, str) and active:
return active
settings = _settings(request)
if settings is None or settings.contract_snapshot is None:
return None
from app.contracts.model import Snapshot
snapshot = Snapshot.model_validate_json(settings.contract_snapshot.read_bytes())
return snapshot.source_version
def _store_root(request: Request) -> Path:
stored = getattr(request.app.state, "contract_store_root", None)
if isinstance(stored, Path):
return stored
settings = _settings(request)
if settings is not None:
return contract_store_root(settings)
return Path("contracts")
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

+14
View File
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
<defs>
<linearGradient id="vmGreen" x1="8" y1="6" x2="56" y2="58" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#C4F07E"/>
<stop offset="1" stop-color="#7CB84A"/>
</linearGradient>
</defs>
<g stroke="url(#vmGreen)" stroke-width="6.5" stroke-linejoin="round">
<rect x="6.25" y="6.25" width="33.5" height="33.5" rx="8"/>
<rect x="24.25" y="24.25" width="33.5" height="33.5" rx="8"/>
</g>
<rect x="15" y="15" width="13.5" height="13.5" rx="3" fill="#F7E56A"/>
<rect x="35.5" y="35.5" width="13.5" height="13.5" rx="3" fill="#F7E56A"/>
</svg>

After

Width:  |  Height:  |  Size: 667 B