1
0
forked from wrenn/wrenn

Add live stats page with metrics sampling and route split

- New sandbox_metrics_snapshots table sampled every 10s (60-day retention)
- Background MetricsSampler goroutine wired into control plane startup
- GET /v1/sandboxes/stats?range=5m|1h|6h|24h|30d endpoint with adaptive
  polling intervals; reserved CPU/RAM uses ceil(paused/2) formula
- StatsPanel component: 4 stat cards + 2 Chart.js line charts (straight
  lines, integer y-axis for running count, dual-axis for CPU/RAM)
- Range filter persisted in URL query param; polls update data silently
  (no blink — loading state only shown on initial mount)
- Split /dashboard/capsules into /list and /stats sub-routes with shared
  layout; capsuleRunningCount store syncs badge across routes
- CreateCapsuleDialog extracted as reusable component
This commit is contained in:
2026-03-25 14:41:05 +06:00
parent 2349f585ae
commit fee66bda50
21 changed files with 2059 additions and 1023 deletions

View File

@ -94,6 +94,10 @@ func main() {
monitor := api.NewHostMonitor(queries, hostPool, audit.New(queries), 30*time.Second) monitor := api.NewHostMonitor(queries, hostPool, audit.New(queries), 30*time.Second)
monitor.Start(ctx) monitor.Start(ctx)
// Start metrics sampler (records per-team sandbox stats every 10s).
sampler := api.NewMetricsSampler(queries, 10*time.Second)
sampler.Start(ctx)
httpServer := &http.Server{ httpServer := &http.Server{
Addr: cfg.ListenAddr, Addr: cfg.ListenAddr,
Handler: srv.Handler(), Handler: srv.Handler(),

View File

@ -0,0 +1,18 @@
-- +goose Up
CREATE TABLE sandbox_metrics_snapshots (
id BIGSERIAL PRIMARY KEY,
team_id TEXT NOT NULL,
sampled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
running_count INTEGER NOT NULL,
vcpus_reserved INTEGER NOT NULL,
memory_mb_reserved INTEGER NOT NULL
);
-- All queries filter on team_id first then range-scan sampled_at.
CREATE INDEX idx_metrics_snapshots_team_time
ON sandbox_metrics_snapshots (team_id, sampled_at DESC);
-- +goose Down
DROP TABLE sandbox_metrics_snapshots;

37
db/queries/metrics.sql Normal file
View File

@ -0,0 +1,37 @@
-- name: InsertMetricsSnapshot :exec
INSERT INTO sandbox_metrics_snapshots (team_id, running_count, vcpus_reserved, memory_mb_reserved)
VALUES ($1, $2, $3, $4);
-- name: GetCurrentMetrics :one
SELECT running_count, vcpus_reserved, memory_mb_reserved, sampled_at
FROM sandbox_metrics_snapshots
WHERE team_id = $1
ORDER BY sampled_at DESC
LIMIT 1;
-- name: GetPeakMetrics :one
SELECT
COALESCE(MAX(running_count), 0)::INTEGER AS peak_running_count,
COALESCE(MAX(vcpus_reserved), 0)::INTEGER AS peak_vcpus,
COALESCE(MAX(memory_mb_reserved), 0)::INTEGER AS peak_memory_mb
FROM sandbox_metrics_snapshots
WHERE team_id = $1
AND sampled_at > NOW() - INTERVAL '30 days';
-- name: PruneOldMetrics :exec
DELETE FROM sandbox_metrics_snapshots
WHERE sampled_at < NOW() - INTERVAL '60 days';
-- name: SampleSandboxMetrics :many
-- Aggregates per-team resource usage from the live sandboxes table.
-- paused sandboxes count at 50% (ceil) for capacity reservation.
SELECT
team_id,
(COUNT(*) FILTER (WHERE status IN ('running', 'starting')))::INTEGER AS running_count,
(COALESCE(SUM(vcpus) FILTER (WHERE status IN ('running', 'starting')), 0)
+ CEIL(COALESCE(SUM(vcpus) FILTER (WHERE status = 'paused'), 0)::NUMERIC / 2))::INTEGER AS vcpus_reserved,
(COALESCE(SUM(memory_mb) FILTER (WHERE status IN ('running', 'starting')), 0)
+ CEIL(COALESCE(SUM(memory_mb) FILTER (WHERE status = 'paused'), 0)::NUMERIC / 2))::INTEGER AS memory_mb_reserved
FROM sandboxes
WHERE status IN ('running', 'starting', 'paused')
GROUP BY team_id;

View File

@ -26,5 +26,8 @@
"tailwindcss": "^4.2.1", "tailwindcss": "^4.2.1",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"vite": "^7.3.1" "vite": "^7.3.1"
},
"dependencies": {
"chart.js": "^4.5.1"
} }
} }

View File

@ -7,6 +7,10 @@ settings:
importers: importers:
.: .:
dependencies:
chart.js:
specifier: ^4.5.1
version: 4.5.1
devDependencies: devDependencies:
'@fontsource-variable/jetbrains-mono': '@fontsource-variable/jetbrains-mono':
specifier: ^5.2.8 specifier: ^5.2.8
@ -249,6 +253,9 @@ packages:
'@jridgewell/trace-mapping@0.3.31': '@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@kurkle/color@0.3.4':
resolution: {integrity: sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==}
'@polka/url@1.0.0-next.29': '@polka/url@1.0.0-next.29':
resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
@ -547,6 +554,10 @@ packages:
'@internationalized/date': ^3.8.1 '@internationalized/date': ^3.8.1
svelte: ^5.33.0 svelte: ^5.33.0
chart.js@4.5.1:
resolution: {integrity: sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==}
engines: {pnpm: '>=8'}
chokidar@4.0.3: chokidar@4.0.3:
resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
engines: {node: '>= 14.16.0'} engines: {node: '>= 14.16.0'}
@ -980,6 +991,8 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2 '@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5 '@jridgewell/sourcemap-codec': 1.5.5
'@kurkle/color@0.3.4': {}
'@polka/url@1.0.0-next.29': {} '@polka/url@1.0.0-next.29': {}
'@rollup/rollup-android-arm-eabi@4.59.0': '@rollup/rollup-android-arm-eabi@4.59.0':
@ -1203,6 +1216,10 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- '@sveltejs/kit' - '@sveltejs/kit'
chart.js@4.5.1:
dependencies:
'@kurkle/color': 0.3.4
chokidar@4.0.3: chokidar@4.0.3:
dependencies: dependencies:
readdirp: 4.1.2 readdirp: 4.1.2

View File

@ -0,0 +1,44 @@
import { apiFetch, type ApiResult } from '$lib/api/client';
export type TimeRange = '5m' | '1h' | '6h' | '24h' | '30d';
export type StatsResponse = {
range: TimeRange;
current: {
running_count: number;
vcpus_reserved: number;
memory_mb_reserved: number;
sampled_at?: string;
};
peaks: {
running_count: number;
vcpus: number;
memory_mb: number;
};
series: {
labels: string[];
running: number[];
vcpus: number[];
memory_mb: number[];
};
};
export async function fetchStats(range: TimeRange): Promise<ApiResult<StatsResponse>> {
return apiFetch('GET', `/api/v1/sandboxes/stats?range=${range}`);
}
export const POLL_INTERVALS: Record<TimeRange, number> = {
'5m': 15_000,
'1h': 30_000,
'6h': 60_000,
'24h': 120_000,
'30d': 300_000,
};
export const RANGE_LABELS: Record<TimeRange, string> = {
'5m': '5m',
'1h': '1h',
'6h': '6h',
'24h': '24h',
'30d': '30d',
};

View File

@ -0,0 +1,3 @@
// Shared state written by the list page and read by the capsules layout
// for the running count badge in the header.
export const capsuleRunningCount = $state({ value: 0 });

View File

@ -0,0 +1,124 @@
<script lang="ts">
import { createCapsule, type Capsule, type CreateCapsuleParams } from '$lib/api/capsules';
type Props = {
open: boolean;
onclose: () => void;
oncreated?: (capsule: Capsule) => void;
};
let { open, onclose, oncreated }: Props = $props();
let createForm = $state<CreateCapsuleParams>({ template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 });
let creating = $state(false);
let createError = $state<string | null>(null);
async function handleCreate() {
creating = true;
createError = null;
const result = await createCapsule(createForm);
if (result.ok) {
createForm = { template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 };
oncreated?.(result.data);
onclose();
} else {
createError = result.error;
}
creating = false;
}
</script>
{#if open}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!creating) onclose(); }}
onkeydown={(e) => { if (e.key === 'Escape' && !creating) onclose(); }}
></div>
<div class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)">
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">Launch Capsule</h2>
<p class="mt-1 text-ui text-[var(--color-text-tertiary)]">Configure resources and launch. The VM will be ready in under a second.</p>
{#if createError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-meta text-[var(--color-red)]">
{createError}
</div>
{/if}
<div class="mt-5 space-y-4">
<div>
<label class="mb-1.5 block text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-template">Template</label>
<input
id="create-template"
type="text"
bind:value={createForm.template}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-ui text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)]"
placeholder="minimal"
/>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="mb-1.5 block text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-vcpus">vCPUs</label>
<input
id="create-vcpus"
type="number"
min="1"
max="8"
bind:value={createForm.vcpus}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-ui text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
<div>
<label class="mb-1.5 block text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-memory">Memory (MB)</label>
<input
id="create-memory"
type="number"
min="128"
max="8192"
step="128"
bind:value={createForm.memory_mb}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-ui text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
</div>
<div>
<label class="mb-1.5 block text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="create-timeout">Idle timeout (seconds — 0 = never pause)</label>
<input
id="create-timeout"
type="number"
min="0"
bind:value={createForm.timeout_sec}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-ui text-[var(--color-text-bright)] outline-none transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
</div>
<div class="mt-6 flex justify-end gap-3">
<button
onclick={onclose}
disabled={creating}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleCreate}
disabled={creating}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if creating}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Launching...
{:else}
Launch
{/if}
</button>
</div>
</div>
</div>
{/if}

View File

@ -0,0 +1,395 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { goto } from '$app/navigation';
import { fetchStats, POLL_INTERVALS, type TimeRange, type StatsResponse } from '$lib/api/stats';
const RANGES: TimeRange[] = ['5m', '1h', '6h', '24h', '30d'];
type Props = { onlaunch?: () => void; launchDisabled?: boolean };
let { onlaunch, launchDisabled = false }: Props = $props();
let range = $state<TimeRange>('1h');
let stats = $state<StatsResponse | null>(null);
// loading is only true before the very first successful fetch; subsequent
// polls update data silently to avoid blanking the cards and charts.
let loading = $state(true);
let error = $state<string | null>(null);
let canvasRunning: HTMLCanvasElement;
let canvasResource: HTMLCanvasElement;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let chartRunning: any = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let chartResource: any = null;
let pollInterval: ReturnType<typeof setInterval> | null = null;
async function load() {
const result = await fetchStats(range);
if (result.ok) {
stats = result.data;
error = null;
} else {
error = result.error;
}
// Set loading=false before updateCharts so cards always render even if
// chart update throws (e.g. Chart.js not yet initialised on first tick).
loading = false;
updateCharts();
}
function updateCharts() {
if (!stats) return;
// Use Array.from to pass plain JS arrays to Chart.js — Svelte 5 $state
// wraps arrays in reactive proxies which Chart.js can't iterate reliably.
const labels = formatLabels(Array.from(stats.series.labels), range);
if (chartRunning) {
chartRunning.data.labels = labels;
chartRunning.data.datasets[0].data = Array.from(stats.series.running);
chartRunning.update();
}
if (chartResource) {
chartResource.data.labels = labels;
chartResource.data.datasets[0].data = Array.from(stats.series.vcpus);
chartResource.data.datasets[1].data = Array.from(stats.series.memory_mb).map((mb) => +(mb / 1024).toFixed(2));
chartResource.update();
}
}
function formatLabels(labels: string[], r: TimeRange): string[] {
return labels.map((iso) => {
const d = new Date(iso);
if (r === '5m' || r === '1h') {
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: r === '5m' ? '2-digit' : undefined });
}
if (r === '6h' || r === '24h') {
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// 30d
return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
});
}
function restartPolling() {
if (pollInterval) clearInterval(pollInterval);
load();
pollInterval = setInterval(load, POLL_INTERVALS[range]);
}
function setRange(r: TimeRange) {
range = r;
goto(`?range=${r}`, { replaceState: true, noScroll: true, keepFocus: true });
restartPolling();
}
// Chart colors (resolved from CSS vars, must match app.css)
const C_ACCENT = '#5e8c58';
const C_ACCENT_FILL = 'rgba(94,140,88,0.08)';
const C_AMBER = '#d4a73c';
const C_AMBER_FILL = 'rgba(212,167,60,0.06)';
const C_GRID = 'rgba(255,255,255,0.04)';
const C_TICK = '#454340';
const FONT_MONO = "'JetBrains Mono', monospace";
const BASE_CHART_OPTIONS = {
responsive: true,
maintainAspectRatio: false,
animation: false as const,
interaction: { mode: 'index' as const, intersect: false },
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: '#141817',
borderColor: '#1f2321',
borderWidth: 1,
titleColor: '#454340',
bodyColor: '#d4cfc8',
titleFont: { family: FONT_MONO, size: 10 },
bodyFont: { family: FONT_MONO, size: 11 },
padding: 10,
},
},
scales: {
x: {
grid: { color: C_GRID },
ticks: { color: C_TICK, font: { family: FONT_MONO, size: 10 }, maxTicksLimit: 6, maxRotation: 0 },
border: { color: C_GRID },
},
y: {
grid: { color: C_GRID },
ticks: { color: C_TICK, font: { family: FONT_MONO, size: 10 }, precision: 0 },
border: { color: C_GRID },
beginAtZero: true,
},
},
};
onMount(async () => {
// Read range from URL query param; fall back to '1h'.
const urlRange = new URLSearchParams(window.location.search).get('range');
if (urlRange && RANGES.includes(urlRange as TimeRange)) {
range = urlRange as TimeRange;
}
const { Chart } = await import('chart.js/auto');
chartRunning = new Chart(canvasRunning, {
type: 'line',
data: {
labels: [],
datasets: [{
data: [],
borderColor: C_ACCENT,
backgroundColor: C_ACCENT_FILL,
borderWidth: 1.5,
fill: true,
tension: 0,
pointRadius: 0,
pointHoverRadius: 4,
pointHoverBackgroundColor: C_ACCENT,
}],
},
options: BASE_CHART_OPTIONS,
});
chartResource = new Chart(canvasResource, {
type: 'line',
data: {
labels: [],
datasets: [
{
label: 'vCPUs',
data: [],
borderColor: C_ACCENT,
backgroundColor: C_ACCENT_FILL,
borderWidth: 1.5,
fill: false,
tension: 0,
pointRadius: 0,
pointHoverRadius: 4,
pointHoverBackgroundColor: C_ACCENT,
yAxisID: 'y',
},
{
label: 'RAM (GB)',
data: [],
borderColor: C_AMBER,
backgroundColor: C_AMBER_FILL,
borderWidth: 1.5,
fill: false,
tension: 0,
pointRadius: 0,
pointHoverRadius: 4,
pointHoverBackgroundColor: C_AMBER,
yAxisID: 'yRam',
},
],
},
options: {
...BASE_CHART_OPTIONS,
plugins: {
...BASE_CHART_OPTIONS.plugins,
legend: {
display: true,
position: 'top' as const,
align: 'end' as const,
labels: {
color: C_TICK,
font: { family: FONT_MONO, size: 10 },
boxWidth: 12,
padding: 12,
},
},
tooltip: {
...BASE_CHART_OPTIONS.plugins.tooltip,
callbacks: {
label: (ctx: { dataset: { label?: string }; parsed: { y: number } }) => {
if (ctx.dataset.label === 'RAM (GB)') {
return ` RAM: ${ctx.parsed.y.toFixed(1)} GB`;
}
return ` vCPUs: ${ctx.parsed.y}`;
},
},
},
},
scales: {
...BASE_CHART_OPTIONS.scales,
y: {
...BASE_CHART_OPTIONS.scales.y,
position: 'left' as const,
title: { display: true, text: 'vCPUs', color: C_TICK, font: { family: FONT_MONO, size: 10 } },
},
yRam: {
grid: { color: C_GRID },
ticks: { color: C_TICK, font: { family: FONT_MONO, size: 10 } },
border: { color: C_GRID },
beginAtZero: true,
position: 'right' as const,
title: { display: true, text: 'GB', color: C_TICK, font: { family: FONT_MONO, size: 10 } },
},
},
},
});
// Apply any data already loaded before charts were ready.
updateCharts();
restartPolling();
});
onDestroy(() => {
if (pollInterval) clearInterval(pollInterval);
chartRunning?.destroy();
chartResource?.destroy();
});
function fmtGB(mb: number): string {
return (mb / 1024).toFixed(1) + ' GB';
}
</script>
<div class="p-8 space-y-5" style="animation: fadeUp 0.35s ease both">
<!-- Header row: title + range selector + launch button -->
<div class="flex items-center justify-between">
<span class="text-meta font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">Usage Statistics</span>
<div class="flex items-center gap-3">
<div class="flex overflow-hidden rounded-[var(--radius-button)] border border-[var(--color-border)]">
{#each RANGES as r, i}
<button
onclick={() => setRange(r)}
class="px-2.5 py-1 font-mono text-label transition-colors duration-150
{range === r
? 'bg-[var(--color-bg-5)] text-[var(--color-text-bright)]'
: 'text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]'}
{i > 0 ? 'border-l border-[var(--color-border)]' : ''}"
>
{r}
</button>
{/each}
</div>
{#if onlaunch}
<button
onclick={onlaunch}
disabled={launchDisabled}
title={launchDisabled ? 'No active team — re-authenticate to create capsules' : undefined}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-4 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:pointer-events-none disabled:opacity-40"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
Launch Capsule
</button>
{/if}
</div>
</div>
<!-- 4 stat cards -->
<div class="flex overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border)]">
<!-- Current Running -->
<div class="flex-1 border-r border-[var(--color-border)] bg-[var(--color-bg-2)] px-5 py-5 transition-colors duration-150 hover:bg-[var(--color-bg-3)]">
<div class="flex items-center gap-2">
<span class="text-meta font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">Running Now</span>
{#if !loading}
<span class="rounded-[3px] bg-[var(--color-accent-glow-mid)] px-1.5 py-0.5 text-badge font-semibold uppercase tracking-[0.04em] text-[var(--color-accent-mid)]">
<span class="mr-0.5 inline-block h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]" style="animation: wrenn-glow 2.5s ease-in-out infinite"></span>
Live
</span>
{/if}
</div>
<div class="mt-1 font-serif text-[2.571rem] tracking-[-0.04em] text-[var(--color-text-bright)]">
{loading ? '—' : (stats?.current.running_count ?? 0)}
</div>
<div class="mt-1 text-label text-[var(--color-text-tertiary)]">capsules</div>
</div>
<!-- Peak Running 30d -->
<div class="flex-1 border-r border-[var(--color-border)] bg-[var(--color-bg-2)] px-5 py-5 transition-colors duration-150 hover:bg-[var(--color-bg-3)]">
<span class="text-meta font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">Peak Running</span>
<div class="mt-1 font-serif text-[2.571rem] tracking-[-0.04em] text-[var(--color-text-bright)]">
{loading ? '—' : (stats?.peaks.running_count ?? 0)}
</div>
<div class="mt-1 text-label text-[var(--color-text-tertiary)]">30-day max</div>
</div>
<!-- Peak CPU 30d -->
<div class="flex-1 border-r border-[var(--color-border)] bg-[var(--color-bg-2)] px-5 py-5 transition-colors duration-150 hover:bg-[var(--color-bg-3)]">
<span class="text-meta font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">Peak CPU</span>
<div class="mt-1 font-serif text-[2.571rem] tracking-[-0.04em] text-[var(--color-text-bright)]">
{loading ? '—' : (stats?.peaks.vcpus ?? 0)}
</div>
<div class="mt-1 text-label text-[var(--color-text-tertiary)]">vCPUs reserved · 30d max</div>
</div>
<!-- Peak RAM 30d -->
<div class="flex-1 bg-[var(--color-bg-2)] px-5 py-5 transition-colors duration-150 hover:bg-[var(--color-bg-3)]">
<span class="text-meta font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">Peak RAM</span>
<div class="mt-1 font-serif text-[2.571rem] tracking-[-0.04em] text-[var(--color-text-bright)]">
{loading ? '—' : fmtGB(stats?.peaks.memory_mb ?? 0)}
</div>
<div class="mt-1 text-label text-[var(--color-text-tertiary)]">reserved · 30d max</div>
</div>
</div>
<!-- Error state -->
{#if error}
<div class="rounded-[var(--radius-card)] border border-[var(--color-red)]/20 bg-[var(--color-red)]/5 px-4 py-3 text-ui text-[var(--color-red)]/70">
Failed to load stats: {error}
</div>
{/if}
<!-- Running Capsules chart -->
<div class="rounded-[var(--radius-card)] border border-[var(--color-border)] bg-[var(--color-bg-2)]">
<div class="flex items-center justify-between px-5 pt-5 pb-3">
<div>
<div class="text-meta font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">Running Capsules</div>
<div class="mt-0.5 flex items-baseline gap-2">
<span class="font-serif text-[2.143rem] tracking-[-0.04em] text-[var(--color-text-bright)]">
{loading ? '—' : (stats?.current.running_count ?? 0)}
</span>
<span class="text-ui text-[var(--color-text-secondary)]">now</span>
</div>
</div>
</div>
{#if !loading && stats && stats.series.labels.length === 0}
<div class="flex h-[200px] items-center justify-center text-ui text-[var(--color-text-muted)]">
Metrics will appear here once capsules have run. First data arrives within 10 seconds.
</div>
{:else}
<div class="relative h-[200px] px-5 pb-5">
<canvas bind:this={canvasRunning}></canvas>
</div>
{/if}
</div>
<!-- Reserved CPU & RAM chart -->
<div class="rounded-[var(--radius-card)] border border-[var(--color-border)] bg-[var(--color-bg-2)]">
<div class="flex items-center justify-between px-5 pt-5 pb-3">
<div>
<div class="text-meta font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">Reserved CPU & RAM</div>
<div class="mt-0.5 flex items-baseline gap-2">
<span class="font-serif text-[2.143rem] tracking-[-0.04em] text-[var(--color-text-bright)]">
{loading ? '—' : (stats?.current.vcpus_reserved ?? 0)}
</span>
<span class="text-ui text-[var(--color-text-secondary)]">vCPUs</span>
<span class="font-serif text-[2.143rem] tracking-[-0.04em] text-[var(--color-text-bright)]">
{loading ? '—' : fmtGB(stats?.current.memory_mb_reserved ?? 0)}
</span>
<span class="text-ui text-[var(--color-text-secondary)]">RAM</span>
</div>
</div>
</div>
{#if !loading && stats && stats.series.labels.length === 0}
<div class="flex h-[200px] items-center justify-center text-ui text-[var(--color-text-muted)]">
Metrics will appear here once capsules have run. First data arrives within 10 seconds.
</div>
{:else}
<div class="relative h-[200px] px-5 pb-5">
<canvas bind:this={canvasResource}></canvas>
</div>
{/if}
</div>
</div>

View File

@ -0,0 +1,102 @@
<script lang="ts">
import Sidebar from '$lib/components/Sidebar.svelte';
import { capsuleRunningCount } from '$lib/capsule-store.svelte';
import { page } from '$app/stores';
let { children } = $props();
let collapsed = $state(
typeof window !== 'undefined'
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
: false
);
let activeTab = $derived(
$page.url.pathname.startsWith('/dashboard/capsules/stats') ? 'stats' : 'list'
);
</script>
<svelte:head>
<title>Wrenn — Capsules</title>
</svelte:head>
<div class="flex h-screen overflow-hidden">
<Sidebar bind:collapsed />
<div class="flex flex-1 flex-col overflow-hidden">
<main class="flex-1 overflow-y-auto bg-[var(--color-bg-0)]">
<!-- Header area -->
<div class="px-7 pt-8">
<!-- Top row: title + status chip -->
<div class="flex items-center justify-between">
<div>
<h1 class="font-serif text-page tracking-[-0.02em] text-[var(--color-text-bright)]">
Capsules
</h1>
<p class="mt-2 text-ui text-[var(--color-text-secondary)]">
Isolated VMs. Start cold in under a second — pause, snapshot, or destroy at will.
</p>
</div>
<div class="flex items-center gap-3">
<!-- Status chip -->
<div
class="flex items-center gap-2.5 rounded-[var(--radius-card)] border border-[var(--color-accent)]/20 bg-[var(--color-bg-2)] px-3.5 py-2"
>
<span class="relative flex h-[8px] w-[8px]">
<span
class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"
></span>
<span class="relative inline-flex h-[8px] w-[8px] rounded-full bg-[var(--color-accent)]"></span>
</span>
<span class="font-mono text-body font-semibold text-[var(--color-accent-bright)]">{capsuleRunningCount.value}</span>
<span class="text-ui text-[var(--color-text-secondary)]">running now</span>
</div>
</div>
</div>
<!-- Tab bar -->
<div class="mt-5 flex gap-1 border-b border-[var(--color-border)]">
<a
href="/dashboard/capsules/list"
class="flex items-center gap-2 border-b-2 px-4 py-2.5 text-ui font-medium transition-colors duration-150 {activeTab === 'list'
? 'border-[var(--color-accent)] text-[var(--color-accent-bright)]'
: 'border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]'}"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="8" y1="6" x2="21" y2="6" /><line x1="8" y1="12" x2="21" y2="12" /><line x1="8" y1="18" x2="21" y2="18" />
<line x1="3" y1="6" x2="3.01" y2="6" /><line x1="3" y1="12" x2="3.01" y2="12" /><line x1="3" y1="18" x2="3.01" y2="18" />
</svg>
List
</a>
<a
href="/dashboard/capsules/stats"
class="flex items-center gap-2 border-b-2 px-4 py-2.5 text-ui font-medium transition-colors duration-150 {activeTab === 'stats'
? 'border-[var(--color-accent)] text-[var(--color-accent-bright)]'
: 'border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]'}"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12" />
</svg>
Stats
</a>
</div>
</div>
{@render children()}
</main>
<!-- Status bar -->
<footer
class="flex h-7 shrink-0 items-center justify-end border-t border-[var(--color-border)] bg-[var(--color-bg-1)] px-7"
>
<div class="flex items-center gap-1.5">
<span class="relative flex h-[5px] w-[5px]">
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
<span class="relative inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
</span>
<span class="font-mono text-label uppercase tracking-[0.04em] text-[var(--color-text-secondary)]">All systems operational</span>
</div>
</footer>
</div>
</div>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
import { redirect } from '@sveltejs/kit';
export function load() {
throw redirect(307, '/dashboard/capsules/list');
}

View File

@ -0,0 +1,734 @@
<script lang="ts">
import CreateCapsuleDialog from '$lib/components/CreateCapsuleDialog.svelte';
import { capsuleRunningCount } from '$lib/capsule-store.svelte';
import { onMount } from 'svelte';
import { toast } from '$lib/toast.svelte';
import { auth } from '$lib/auth.svelte';
import {
listCapsules,
pauseCapsule,
resumeCapsule,
destroyCapsule,
createSnapshot,
type Capsule
} from '$lib/api/capsules';
const REFRESH_INTERVAL = 30;
const SPIN_DURATION = 600;
// Capsule list state
let capsules = $state<Capsule[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
let searchQuery = $state('');
let actionLoading = $state<string | null>(null);
let spinning = $state(false);
// Auto-refresh countdown state
let autoRefresh = $state(true);
let countdown = $state(REFRESH_INTERVAL);
let countdownInterval: ReturnType<typeof setInterval> | null = null;
let refreshInterval: ReturnType<typeof setInterval> | null = null;
// Sorting state
type SortKey = 'status' | 'vcpus' | 'memory_mb' | 'started_at' | 'timeout_sec';
let sortKey = $state<SortKey | null>(null);
let sortDir = $state<'asc' | 'desc'>('asc');
// Status menu state
let openMenuId = $state<string | null>(null);
let menuPos = $state<{ top: number; left: number }>({ top: 0, left: 0 });
// Create dialog state
let showCreateDialog = $state(false);
// Snapshot dialog state
let snapshotTarget = $state<{ capsule: Capsule; pauseFirst: boolean } | null>(null);
let snapshotName = $state('');
let snapshotting = $state(false);
let snapshotError = $state<string | null>(null);
// Destroy confirmation state
let destroyTarget = $state<Capsule | null>(null);
let destroying = $state(false);
let destroyError = $state<string | null>(null);
// Briefly highlight a newly created capsule row
let newCapsuleId = $state<string | null>(null);
let filteredCapsules = $derived.by(() => {
let list = searchQuery
? capsules.filter((c) => c.id.toLowerCase().includes(searchQuery.toLowerCase()))
: [...capsules];
if (sortKey) {
const key = sortKey;
const dir = sortDir === 'asc' ? 1 : -1;
list.sort((a, b) => {
if (key === 'status') {
return a.status.localeCompare(b.status) * dir;
}
if (key === 'started_at') {
const ta = a.started_at ? new Date(a.started_at).getTime() : 0;
const tb = b.started_at ? new Date(b.started_at).getTime() : 0;
return (ta - tb) * dir;
}
const va = a[key] as number;
const vb = b[key] as number;
return (va - vb) * dir;
});
}
return list;
});
$effect(() => {
capsuleRunningCount.value = capsules.filter((c) => c.status === 'running').length;
});
function toggleSort(key: SortKey) {
if (sortKey === key) {
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
} else {
sortKey = key;
sortDir = 'asc';
}
}
function startAutoRefresh() {
stopAutoRefresh();
countdown = REFRESH_INTERVAL;
countdownInterval = setInterval(() => {
countdown--;
if (countdown <= 0) {
countdown = REFRESH_INTERVAL;
}
}, 1000);
refreshInterval = setInterval(fetchCapsules, REFRESH_INTERVAL * 1000);
}
function stopAutoRefresh() {
if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
if (refreshInterval) { clearInterval(refreshInterval); refreshInterval = null; }
}
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
if (autoRefresh) {
startAutoRefresh();
} else {
stopAutoRefresh();
}
}
async function fetchCapsules() {
const wasEmpty = capsules.length === 0;
if (wasEmpty) loading = true;
spinning = true;
const spinTimer = new Promise<void>((resolve) => setTimeout(resolve, SPIN_DURATION));
error = null;
const result = await listCapsules();
if (result.ok) {
capsules = result.data;
} else {
error = result.error;
}
loading = false;
if (autoRefresh) countdown = REFRESH_INTERVAL;
await spinTimer;
spinning = false;
}
async function handlePause(id: string) {
openMenuId = null;
actionLoading = id;
const result = await pauseCapsule(id);
if (result.ok) {
capsules = capsules.map((c) => (c.id === id ? result.data : c));
} else {
toast.error(result.error);
}
actionLoading = null;
}
async function handleResume(id: string) {
openMenuId = null;
actionLoading = id;
const result = await resumeCapsule(id);
if (result.ok) {
capsules = capsules.map((c) => (c.id === id ? result.data : c));
} else {
toast.error(result.error);
}
actionLoading = null;
}
function handleSnapshot(capsule: Capsule) {
openMenuId = null;
snapshotName = '';
snapshotError = null;
snapshotTarget = { capsule, pauseFirst: false };
}
function handlePauseAndSnapshot(capsule: Capsule) {
openMenuId = null;
snapshotName = '';
snapshotError = null;
snapshotTarget = { capsule, pauseFirst: true };
}
async function handleSnapshotConfirm() {
if (!snapshotTarget) return;
snapshotting = true;
snapshotError = null;
const result = await createSnapshot(snapshotTarget.capsule.id, snapshotName.trim() || undefined);
if (result.ok) {
snapshotTarget = null;
await fetchCapsules();
} else {
snapshotError = result.error;
}
snapshotting = false;
}
async function handleDestroy() {
if (!destroyTarget) return;
destroying = true;
destroyError = null;
const id = destroyTarget.id;
const result = await destroyCapsule(id);
if (result.ok) {
capsules = capsules.filter((c) => c.id !== id);
destroyTarget = null;
} else {
destroyError = result.error;
}
destroying = false;
}
function handleCapsuleCreated(capsule: Capsule) {
capsules = [capsule, ...capsules];
newCapsuleId = capsule.id;
setTimeout(() => { newCapsuleId = null; }, 1600);
}
function formatTime(iso: string | undefined): string {
if (!iso) return '—';
const d = new Date(iso);
return d.toLocaleString('en-US', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
}
function timeAgo(iso: string | undefined): string {
if (!iso) return '';
const seconds = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86400)}d ago`;
}
function handleClickOutside(event: MouseEvent) {
if (openMenuId && !(event.target as Element)?.closest('.status-menu-container')) {
openMenuId = null;
}
}
onMount(() => {
fetchCapsules();
startAutoRefresh();
return () => stopAutoRefresh();
});
</script>
<style>
.refresh-spin {
animation: spin-once 0.6s ease-in-out;
}
@keyframes capsule-born {
0%, 25% { background-color: rgba(94, 140, 88, 0.1); }
100% { background-color: transparent; }
}
.capsule-born {
animation: capsule-born 1.6s ease-out forwards;
}
.row-stripe {
transform: scaleY(0);
transform-origin: center;
transition: transform 0.18s cubic-bezier(0.25, 1, 0.5, 1);
}
.capsule-row:hover .row-stripe {
transform: scaleY(1);
}
</style>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<svelte:window onclick={handleClickOutside} onkeydown={(e) => { if (e.key === 'Escape') openMenuId = null; }} />
<div class="p-8" style="animation: fadeUp 0.35s ease both">
<!-- Search bar + controls -->
<div class="mb-4 flex items-center gap-3">
<div class="relative flex-1 max-w-[300px]">
<svg class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)]" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" />
</svg>
<input
type="text"
placeholder="Search by ID..."
bind:value={searchQuery}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-2 pl-9 pr-3 font-mono text-ui text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)]"
/>
</div>
<span class="text-ui text-[var(--color-text-secondary)]">{filteredCapsules.length} total</span>
<div class="flex-1"></div>
<!-- Refresh button -->
<button
onclick={fetchCapsules}
disabled={spinning}
class="flex h-8 w-8 items-center justify-center rounded-[var(--radius-button)] border border-[var(--color-border)] text-[var(--color-text-tertiary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-secondary)] disabled:opacity-50"
title="Refresh"
>
<svg
class={spinning ? 'refresh-spin' : ''}
width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
>
<polyline points="23 4 23 10 17 10" />
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
</svg>
</button>
<!-- Auto-refresh countdown toggle -->
<button
onclick={toggleAutoRefresh}
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border px-2.5 py-1.5 font-mono text-label transition-colors duration-150
{autoRefresh
? 'border-[var(--color-accent)]/30 text-[var(--color-accent-mid)] hover:border-[var(--color-accent)]/50'
: 'border-[var(--color-border)] text-[var(--color-text-muted)] hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-secondary)]'}"
title={autoRefresh ? 'Click to disable auto-refresh' : 'Click to enable auto-refresh (30s)'}
>
{#if autoRefresh}
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<circle cx="8" cy="8" r="5" stroke="var(--color-accent-glow-mid)" stroke-width="1.5" />
<circle
cx="8" cy="8" r="5"
stroke="var(--color-accent)"
stroke-width="1.5"
stroke-linecap="round"
stroke-dasharray="31.416"
stroke-dashoffset={31.416 * (1 - countdown / REFRESH_INTERVAL)}
transform="rotate(-90 8 8)"
style="transition: stroke-dashoffset 1s linear"
/>
</svg>
{countdown}s
{:else}
Off
{/if}
</button>
<button
onclick={() => { showCreateDialog = true; }}
disabled={!auth.teamId}
title={!auth.teamId ? 'No active team — re-authenticate to create capsules' : undefined}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-4 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:pointer-events-none disabled:opacity-40"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
Launch Capsule
</button>
</div>
{#if error}
<div class="mb-4 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-4 py-3 text-ui text-[var(--color-red)]">
{error}
</div>
{/if}
<!-- Table -->
<div class="rounded-[var(--radius-card)] border border-[var(--color-border)] overflow-hidden">
<!-- Table header -->
<div class="grid grid-cols-[1.6fr_0.8fr_0.5fr_0.5fr_0.6fr_1fr_0.9fr] rounded-t-[var(--radius-card)] border-b border-[var(--color-border)] bg-[var(--color-bg-3)]">
<div class="px-5 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">ID</div>
<div class="px-5 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Template</div>
{@render sortableHeader('CPU', 'vcpus')}
{@render sortableHeader('Memory', 'memory_mb')}
{@render sortableHeader('Idle Timeout', 'timeout_sec')}
{@render sortableHeader('Started', 'started_at')}
{@render sortableHeader('Status', 'status')}
</div>
{#if loading && capsules.length === 0}
<div class="flex items-center justify-center py-16">
<div class="flex items-center gap-3 text-ui text-[var(--color-text-secondary)]">
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Loading capsules...
</div>
</div>
{:else if filteredCapsules.length === 0}
<div class="flex flex-col items-center justify-center py-[72px]">
<div class="relative mb-5">
<div class="absolute inset-0 -m-4 rounded-full" style="background: radial-gradient(circle, rgba(94,140,88,0.08) 0%, transparent 70%)"></div>
<div class="relative flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-accent)]/20 bg-[var(--color-bg-3)]" style="animation: iconFloat 4s ease-in-out infinite">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-accent-mid)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="3" width="20" height="14" rx="2" />
<line x1="8" y1="21" x2="16" y2="21" />
<line x1="12" y1="17" x2="12" y2="21" />
</svg>
</div>
</div>
<p class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">
No capsules yet
</p>
<p class="mt-1.5 text-ui text-[var(--color-text-tertiary)]">
Each capsule is an isolated VM. Launch one to get started.
</p>
<button
onclick={() => { showCreateDialog = true; }}
disabled={!auth.teamId}
class="mt-6 flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:pointer-events-none disabled:opacity-40"
>
Launch a Capsule
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
</button>
</div>
{:else}
{#each filteredCapsules as capsule, i (capsule.id)}
{@const stripeColor = capsule.status === 'running' ? 'bg-[var(--color-accent)]' : capsule.status === 'paused' ? 'bg-[var(--color-amber)]' : 'bg-[var(--color-text-muted)]'}
<div
class="capsule-row relative grid grid-cols-[1.6fr_0.8fr_0.5fr_0.5fr_0.6fr_1fr_0.9fr] items-center overflow-hidden border-b border-[var(--color-border)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] last:border-b-0 {newCapsuleId === capsule.id ? 'capsule-born' : ''}"
style="animation: fadeUp 0.35s ease both; animation-delay: {i * 40}ms"
>
<!-- Left accent stripe -->
<div class="row-stripe pointer-events-none absolute left-0 top-0 h-full w-0.5 {stripeColor}"></div>
<!-- ID with status dot -->
<div class="flex items-center gap-2.5 px-5 py-4">
{#if capsule.status === 'running'}
<span class="relative flex h-[6px] w-[6px] shrink-0">
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
<span class="relative inline-flex h-[6px] w-[6px] rounded-full bg-[var(--color-accent)]"></span>
</span>
{:else if capsule.status === 'paused'}
<span class="inline-flex h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-amber)]"></span>
{:else}
<span class="inline-flex h-[6px] w-[6px] shrink-0 rounded-full bg-[var(--color-text-muted)]"></span>
{/if}
{#if searchQuery && capsule.id.toLowerCase().includes(searchQuery.toLowerCase())}
{@const matchIdx = capsule.id.toLowerCase().indexOf(searchQuery.toLowerCase())}
<span class="font-mono text-ui text-[var(--color-text-bright)]">{capsule.id.slice(0, matchIdx)}<mark class="rounded-[2px] bg-[var(--color-accent-glow-mid)] px-0.5 text-[var(--color-accent-bright)] not-italic">{capsule.id.slice(matchIdx, matchIdx + searchQuery.length)}</mark>{capsule.id.slice(matchIdx + searchQuery.length)}</span>
{:else}
<span class="font-mono text-ui text-[var(--color-text-bright)]">{capsule.id}</span>
{/if}
</div>
<!-- Template -->
<div class="min-w-0 px-5 py-4">
<span class="block truncate text-ui text-[var(--color-text-secondary)]">{capsule.template}</span>
</div>
<!-- CPU -->
<div class="px-5 py-4">
<span class="font-mono text-ui text-[var(--color-text-secondary)]">{capsule.vcpus}</span>
</div>
<!-- Memory -->
<div class="px-5 py-4">
<span class="font-mono text-ui text-[var(--color-text-secondary)]">{capsule.memory_mb}MB</span>
</div>
<!-- Idle Timeout -->
<div class="px-5 py-4">
<span class="font-mono text-ui text-[var(--color-text-secondary)]">{capsule.timeout_sec ? `${capsule.timeout_sec}s` : '—'}</span>
</div>
<!-- Started -->
<div class="px-5 py-4">
<span class="text-ui text-[var(--color-text-secondary)]" title={capsule.started_at ?? ''}>{formatTime(capsule.started_at)}</span>
{#if capsule.last_active_at}
<span class="ml-1.5 text-label text-[var(--color-text-muted)]">{timeAgo(capsule.last_active_at)}</span>
{/if}
</div>
<!-- Status button with popover -->
<div class="relative px-5 py-4 status-menu-container">
{#if actionLoading === capsule.id}
<span class="inline-flex items-center gap-1.5 text-ui text-[var(--color-text-secondary)]">
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
</span>
{:else}
<button
onclick={(e) => {
e.stopPropagation();
if (openMenuId === capsule.id) {
openMenuId = null;
} else {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
menuPos = { top: rect.bottom + 4, left: rect.right - 180 };
openMenuId = capsule.id;
}
}}
class="inline-flex items-center gap-1.5 rounded-[var(--radius-button)] border px-2.5 py-1 text-label font-semibold uppercase tracking-[0.04em] transition-colors duration-150 {capsule.status === 'running' ? 'border-[var(--color-accent)]/40 bg-[var(--color-accent-glow)] text-[var(--color-accent-mid)] hover:border-[var(--color-accent)]/70 hover:text-[var(--color-accent-bright)]' : capsule.status === 'paused' ? 'border-[var(--color-amber)]/30 bg-[var(--color-amber)]/5 text-[var(--color-amber)] hover:border-[var(--color-amber)]/60' : 'border-[var(--color-border)] bg-[var(--color-bg-2)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)]'}"
>
{capsule.status}
<svg
class="transition-transform duration-150 {openMenuId === capsule.id ? 'rotate-180' : ''}"
width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
{/if}
</div>
</div>
{/each}
{/if}
</div>
</div>
<!-- Fixed-position status popover menu -->
{#if openMenuId}
{@const openCapsule = capsules.find((c) => c.id === openMenuId)}
{#if openCapsule}
<div
class="fixed z-50 w-[180px] overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] py-1"
style="top: {menuPos.top}px; left: {menuPos.left}px; animation: fadeUp 0.15s ease both"
>
{#if openCapsule.status === 'running'}
<button
onclick={() => handlePause(openCapsule.id)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-meta text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" class="shrink-0">
<rect x="6" y="4" width="4" height="16" rx="1" />
<rect x="14" y="4" width="4" height="16" rx="1" />
</svg>
Pause
</button>
<button
onclick={() => handlePauseAndSnapshot(openCapsule)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-meta text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" />
<circle cx="12" cy="15" r="3" />
</svg>
Pause & Snapshot
</button>
{:else if openCapsule.status === 'paused'}
<button
onclick={() => handleResume(openCapsule.id)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-meta text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" class="shrink-0">
<polygon points="5 3 19 12 5 21 5 3" />
</svg>
Resume
</button>
<button
onclick={() => handleSnapshot(openCapsule)}
class="flex w-full items-center gap-2.5 px-3 py-2 text-meta text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" />
<circle cx="12" cy="15" r="3" />
</svg>
Snapshot
</button>
{/if}
<div class="my-1 border-t border-[var(--color-border)]"></div>
<button
onclick={() => { const target = openCapsule; openMenuId = null; destroyError = null; destroyTarget = target; }}
class="flex w-full items-center gap-2.5 px-3 py-2 text-meta text-[var(--color-red)] transition-colors duration-150 hover:bg-[var(--color-red)]/5"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
</svg>
Destroy
</button>
</div>
{/if}
{/if}
<!-- Snapshot Dialog -->
{#if snapshotTarget}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!snapshotting) snapshotTarget = null; }}
onkeydown={(e) => { if (e.key === 'Escape' && !snapshotting) snapshotTarget = null; }}
></div>
<div class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] overflow-hidden" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)">
<div class="flex items-center gap-4 border-b border-[var(--color-border)] bg-[var(--color-bg-3)] px-6 py-5">
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-[var(--radius-input)] bg-[var(--color-accent)]/15 text-[var(--color-accent)] shadow-[0_0_12px_var(--color-accent-glow)]">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
<path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" />
<circle cx="12" cy="15" r="3" />
</svg>
</div>
<div>
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">Capture snapshot</h2>
<p class="mt-0.5 text-meta text-[var(--color-text-muted)] font-mono">{snapshotTarget.capsule.id}</p>
</div>
</div>
<div class="px-6 pt-5 pb-6 space-y-4">
{#if snapshotTarget.pauseFirst}
<div class="flex items-start gap-2.5 rounded-[var(--radius-input)] border border-[var(--color-amber)]/25 bg-[var(--color-amber)]/8 px-3 py-2.5">
<svg class="mt-px shrink-0 text-[var(--color-amber)]" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
<p class="text-meta text-[var(--color-amber)] leading-relaxed">This capsule will be <strong class="font-semibold">paused first</strong> — memory state is captured at rest.</p>
</div>
{:else}
<p class="text-ui text-[var(--color-text-tertiary)]">The capsule's current memory state will be captured and stored as a reusable snapshot.</p>
{/if}
{#if snapshotError}
<div class="rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-meta text-[var(--color-red)]">
{snapshotError}
</div>
{/if}
<div>
<div class="mb-1.5 flex items-baseline justify-between">
<label class="text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="snapshot-name">Snapshot name</label>
<span class="text-meta text-[var(--color-text-muted)]">optional</span>
</div>
<input
id="snapshot-name"
type="text"
bind:value={snapshotName}
disabled={snapshotting}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-ui text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)] disabled:opacity-50"
placeholder="e.g. after-apt-install, pre-migration"
onkeydown={(e) => { if (e.key === 'Enter' && !snapshotting) handleSnapshotConfirm(); }}
/>
<p class="mt-1.5 text-meta text-[var(--color-text-muted)]">Leave blank to use an auto-generated name.</p>
</div>
<div class="flex justify-end gap-3 pt-1">
<button
onclick={() => { snapshotTarget = null; }}
disabled={snapshotting}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleSnapshotConfirm}
disabled={snapshotting}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if snapshotting}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Capturing...
{:else}
Capture snapshot
{/if}
</button>
</div>
</div>
</div>
</div>
{/if}
<!-- Destroy confirmation dialog -->
{#if destroyTarget}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute inset-0 bg-black/60"
onclick={() => { if (!destroying) destroyTarget = null; }}
onkeydown={(e) => { if (e.key === 'Escape' && !destroying) destroyTarget = null; }}
></div>
<div class="relative w-full max-w-[380px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both">
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">Destroy Capsule</h2>
<p class="mt-2 text-ui text-[var(--color-text-tertiary)]">
Terminate <span class="font-mono text-[var(--color-text-secondary)]">{destroyTarget.id}</span> and destroy all data inside it. This cannot be undone.
</p>
{#if destroyError}
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-meta text-[var(--color-red)]">
{destroyError}
</div>
{/if}
<div class="mt-6 flex justify-end gap-3">
<button
onclick={() => { destroyTarget = null; }}
disabled={destroying}
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
>
Cancel
</button>
<button
onclick={handleDestroy}
disabled={destroying}
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-110 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
>
{#if destroying}
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Destroying...
{:else}
Destroy
{/if}
</button>
</div>
</div>
</div>
{/if}
<!-- Create Capsule Dialog -->
<CreateCapsuleDialog
open={showCreateDialog}
onclose={() => { showCreateDialog = false; }}
oncreated={handleCapsuleCreated}
/>
{#snippet sortableHeader(label: string, key: SortKey)}
<button
onclick={() => toggleSort(key)}
class="flex items-center gap-1 px-5 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)] transition-colors duration-150 hover:text-[var(--color-text-secondary)]"
>
{label}
{#if sortKey === key}
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" class="text-[var(--color-accent)]">
{#if sortDir === 'asc'}
<polyline points="18 15 12 9 6 15" />
{:else}
<polyline points="6 9 12 15 18 9" />
{/if}
</svg>
{/if}
</button>
{/snippet}

View File

@ -0,0 +1,17 @@
<script lang="ts">
import StatsPanel from '$lib/components/StatsPanel.svelte';
import CreateCapsuleDialog from '$lib/components/CreateCapsuleDialog.svelte';
import { auth } from '$lib/auth.svelte';
let showCreateDialog = $state(false);
</script>
<StatsPanel
onlaunch={() => { showCreateDialog = true; }}
launchDisabled={!auth.teamId}
/>
<CreateCapsuleDialog
open={showCreateDialog}
onclose={() => { showCreateDialog = false; }}
/>

View File

@ -0,0 +1,100 @@
package api
import (
"log/slog"
"net/http"
"time"
"git.omukk.dev/wrenn/sandbox/internal/auth"
"git.omukk.dev/wrenn/sandbox/internal/service"
)
type statsHandler struct {
svc *service.StatsService
}
func newStatsHandler(svc *service.StatsService) *statsHandler {
return &statsHandler{svc: svc}
}
type statsCurrentResponse struct {
RunningCount int32 `json:"running_count"`
VCPUsReserved int32 `json:"vcpus_reserved"`
MemoryMBReserved int32 `json:"memory_mb_reserved"`
SampledAt string `json:"sampled_at,omitempty"`
}
type statsPeaksResponse struct {
RunningCount int32 `json:"running_count"`
VCPUs int32 `json:"vcpus"`
MemoryMB int32 `json:"memory_mb"`
}
type statsSeriesResponse struct {
Labels []string `json:"labels"`
Running []int32 `json:"running"`
VCPUs []int32 `json:"vcpus"`
MemoryMB []int32 `json:"memory_mb"`
}
type statsResponse struct {
Range string `json:"range"`
Current statsCurrentResponse `json:"current"`
Peaks statsPeaksResponse `json:"peaks"`
Series statsSeriesResponse `json:"series"`
}
// GetStats handles GET /v1/sandboxes/stats?range=5m|1h|6h|24h|30d
func (h *statsHandler) GetStats(w http.ResponseWriter, r *http.Request) {
ac := auth.MustFromContext(r.Context())
rangeParam := r.URL.Query().Get("range")
if rangeParam == "" {
rangeParam = string(service.Range1h)
}
tr := service.TimeRange(rangeParam)
if !service.ValidRange(tr) {
writeError(w, http.StatusBadRequest, "invalid_request", "range must be one of: 5m, 1h, 6h, 24h, 30d")
return
}
current, peaks, series, err := h.svc.GetStats(r.Context(), ac.TeamID, tr)
if err != nil {
slog.Error("stats handler: get stats failed", "team_id", ac.TeamID, "error", err)
writeError(w, http.StatusInternalServerError, "internal_error", "failed to retrieve stats")
return
}
resp := statsResponse{
Range: rangeParam,
Current: statsCurrentResponse{
RunningCount: current.RunningCount,
VCPUsReserved: current.VCPUsReserved,
MemoryMBReserved: current.MemoryMBReserved,
},
Peaks: statsPeaksResponse{
RunningCount: peaks.RunningCount,
VCPUs: peaks.VCPUs,
MemoryMB: peaks.MemoryMB,
},
Series: statsSeriesResponse{
Labels: make([]string, len(series)),
Running: make([]int32, len(series)),
VCPUs: make([]int32, len(series)),
MemoryMB: make([]int32, len(series)),
},
}
if !current.SampledAt.IsZero() {
resp.Current.SampledAt = current.SampledAt.UTC().Format(time.RFC3339)
}
for i, pt := range series {
resp.Series.Labels[i] = pt.Bucket.UTC().Format(time.RFC3339)
resp.Series.Running[i] = pt.RunningCount
resp.Series.VCPUs[i] = pt.VCPUsReserved
resp.Series.MemoryMB[i] = pt.MemoryMBReserved
}
writeJSON(w, http.StatusOK, resp)
}

View File

@ -0,0 +1,68 @@
package api
import (
"context"
"log/slog"
"time"
"git.omukk.dev/wrenn/sandbox/internal/db"
)
// MetricsSampler records per-team sandbox resource usage to
// sandbox_metrics_snapshots every interval. It also prunes rows older than
// 60 days on each tick to keep the table bounded.
type MetricsSampler struct {
db *db.Queries
interval time.Duration
}
// NewMetricsSampler creates a MetricsSampler.
func NewMetricsSampler(queries *db.Queries, interval time.Duration) *MetricsSampler {
return &MetricsSampler{db: queries, interval: interval}
}
// Start runs the sampler loop until the context is cancelled.
func (s *MetricsSampler) Start(ctx context.Context) {
go func() {
ticker := time.NewTicker(s.interval)
defer ticker.Stop()
// Sample immediately on startup.
s.run(ctx)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.run(ctx)
}
}
}()
}
func (s *MetricsSampler) run(ctx context.Context) {
s.prune(ctx)
if err := s.sample(ctx); err != nil {
slog.Warn("metrics sampler: sample failed", "error", err)
}
}
func (s *MetricsSampler) sample(ctx context.Context) error {
rows, err := s.db.SampleSandboxMetrics(ctx)
if err != nil {
return err
}
for _, row := range rows {
if err := s.db.InsertMetricsSnapshot(ctx, db.InsertMetricsSnapshotParams(row)); err != nil {
slog.Warn("metrics sampler: insert snapshot failed", "team_id", row.TeamID, "error", err)
}
}
return nil
}
func (s *MetricsSampler) prune(ctx context.Context) {
if err := s.db.PruneOldMetrics(ctx); err != nil {
slog.Warn("metrics sampler: prune failed", "error", err)
}
}

View File

@ -613,6 +613,32 @@ paths:
items: items:
$ref: "#/components/schemas/Sandbox" $ref: "#/components/schemas/Sandbox"
/v1/sandboxes/stats:
get:
summary: Get sandbox usage stats for your team
operationId: getSandboxStats
tags: [sandboxes]
security:
- apiKeyAuth: []
parameters:
- name: range
in: query
required: false
schema:
type: string
enum: [5m, 1h, 6h, 24h, 30d]
default: 1h
description: Time window for the time-series data.
responses:
"200":
description: Sandbox stats for the team
content:
application/json:
schema:
$ref: "#/components/schemas/SandboxStats"
"400":
$ref: "#/components/responses/BadRequest"
/v1/sandboxes/{id}: /v1/sandboxes/{id}:
parameters: parameters:
- name: id - name: id
@ -1578,6 +1604,57 @@ components:
after this duration of inactivity (no exec or ping). 0 means after this duration of inactivity (no exec or ping). 0 means
no auto-pause. no auto-pause.
SandboxStats:
type: object
properties:
range:
type: string
enum: [5m, 1h, 6h, 24h, 30d]
current:
type: object
properties:
running_count:
type: integer
vcpus_reserved:
type: integer
memory_mb_reserved:
type: integer
sampled_at:
type: string
format: date-time
nullable: true
peaks:
type: object
description: Maximum values over the last 30 days.
properties:
running_count:
type: integer
vcpus:
type: integer
memory_mb:
type: integer
series:
type: object
description: Parallel arrays for chart rendering.
properties:
labels:
type: array
items:
type: string
format: date-time
running:
type: array
items:
type: integer
vcpus:
type: array
items:
type: integer
memory_mb:
type: array
items:
type: integer
Sandbox: Sandbox:
type: object type: object
properties: properties:

View File

@ -46,6 +46,7 @@ func New(
hostSvc := &service.HostService{DB: queries, Redis: rdb, JWT: jwtSecret, Pool: pool} hostSvc := &service.HostService{DB: queries, Redis: rdb, JWT: jwtSecret, Pool: pool}
teamSvc := &service.TeamService{DB: queries, Pool: pgPool, HostPool: pool} teamSvc := &service.TeamService{DB: queries, Pool: pgPool, HostPool: pool}
auditSvc := &service.AuditService{DB: queries} auditSvc := &service.AuditService{DB: queries}
statsSvc := &service.StatsService{DB: queries, Pool: pgPool}
al := audit.New(queries) al := audit.New(queries)
@ -62,6 +63,7 @@ func New(
teamH := newTeamHandler(teamSvc, al) teamH := newTeamHandler(teamSvc, al)
usersH := newUsersHandler(teamSvc) usersH := newUsersHandler(teamSvc)
auditH := newAuditHandler(auditSvc) auditH := newAuditHandler(auditSvc)
statsH := newStatsHandler(statsSvc)
// OpenAPI spec and docs. // OpenAPI spec and docs.
r.Get("/openapi.yaml", serveOpenAPI) r.Get("/openapi.yaml", serveOpenAPI)
@ -109,6 +111,7 @@ func New(
r.Use(requireAPIKeyOrJWT(queries, jwtSecret)) r.Use(requireAPIKeyOrJWT(queries, jwtSecret))
r.Post("/", sandbox.Create) r.Post("/", sandbox.Create)
r.Get("/", sandbox.List) r.Get("/", sandbox.List)
r.Get("/stats", statsH.GetStats)
r.Route("/{id}", func(r chi.Router) { r.Route("/{id}", func(r chi.Router) {
r.Get("/", sandbox.Get) r.Get("/", sandbox.Get)

141
internal/db/metrics.sql.go Normal file
View File

@ -0,0 +1,141 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: metrics.sql
package db
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getCurrentMetrics = `-- name: GetCurrentMetrics :one
SELECT running_count, vcpus_reserved, memory_mb_reserved, sampled_at
FROM sandbox_metrics_snapshots
WHERE team_id = $1
ORDER BY sampled_at DESC
LIMIT 1
`
type GetCurrentMetricsRow struct {
RunningCount int32 `json:"running_count"`
VcpusReserved int32 `json:"vcpus_reserved"`
MemoryMbReserved int32 `json:"memory_mb_reserved"`
SampledAt pgtype.Timestamptz `json:"sampled_at"`
}
func (q *Queries) GetCurrentMetrics(ctx context.Context, teamID string) (GetCurrentMetricsRow, error) {
row := q.db.QueryRow(ctx, getCurrentMetrics, teamID)
var i GetCurrentMetricsRow
err := row.Scan(
&i.RunningCount,
&i.VcpusReserved,
&i.MemoryMbReserved,
&i.SampledAt,
)
return i, err
}
const getPeakMetrics = `-- name: GetPeakMetrics :one
SELECT
COALESCE(MAX(running_count), 0)::INTEGER AS peak_running_count,
COALESCE(MAX(vcpus_reserved), 0)::INTEGER AS peak_vcpus,
COALESCE(MAX(memory_mb_reserved), 0)::INTEGER AS peak_memory_mb
FROM sandbox_metrics_snapshots
WHERE team_id = $1
AND sampled_at > NOW() - INTERVAL '30 days'
`
type GetPeakMetricsRow struct {
PeakRunningCount int32 `json:"peak_running_count"`
PeakVcpus int32 `json:"peak_vcpus"`
PeakMemoryMb int32 `json:"peak_memory_mb"`
}
func (q *Queries) GetPeakMetrics(ctx context.Context, teamID string) (GetPeakMetricsRow, error) {
row := q.db.QueryRow(ctx, getPeakMetrics, teamID)
var i GetPeakMetricsRow
err := row.Scan(&i.PeakRunningCount, &i.PeakVcpus, &i.PeakMemoryMb)
return i, err
}
const insertMetricsSnapshot = `-- name: InsertMetricsSnapshot :exec
INSERT INTO sandbox_metrics_snapshots (team_id, running_count, vcpus_reserved, memory_mb_reserved)
VALUES ($1, $2, $3, $4)
`
type InsertMetricsSnapshotParams struct {
TeamID string `json:"team_id"`
RunningCount int32 `json:"running_count"`
VcpusReserved int32 `json:"vcpus_reserved"`
MemoryMbReserved int32 `json:"memory_mb_reserved"`
}
func (q *Queries) InsertMetricsSnapshot(ctx context.Context, arg InsertMetricsSnapshotParams) error {
_, err := q.db.Exec(ctx, insertMetricsSnapshot,
arg.TeamID,
arg.RunningCount,
arg.VcpusReserved,
arg.MemoryMbReserved,
)
return err
}
const pruneOldMetrics = `-- name: PruneOldMetrics :exec
DELETE FROM sandbox_metrics_snapshots
WHERE sampled_at < NOW() - INTERVAL '60 days'
`
func (q *Queries) PruneOldMetrics(ctx context.Context) error {
_, err := q.db.Exec(ctx, pruneOldMetrics)
return err
}
const sampleSandboxMetrics = `-- name: SampleSandboxMetrics :many
SELECT
team_id,
(COUNT(*) FILTER (WHERE status IN ('running', 'starting')))::INTEGER AS running_count,
(COALESCE(SUM(vcpus) FILTER (WHERE status IN ('running', 'starting')), 0)
+ CEIL(COALESCE(SUM(vcpus) FILTER (WHERE status = 'paused'), 0)::NUMERIC / 2))::INTEGER AS vcpus_reserved,
(COALESCE(SUM(memory_mb) FILTER (WHERE status IN ('running', 'starting')), 0)
+ CEIL(COALESCE(SUM(memory_mb) FILTER (WHERE status = 'paused'), 0)::NUMERIC / 2))::INTEGER AS memory_mb_reserved
FROM sandboxes
WHERE status IN ('running', 'starting', 'paused')
GROUP BY team_id
`
type SampleSandboxMetricsRow struct {
TeamID string `json:"team_id"`
RunningCount int32 `json:"running_count"`
VcpusReserved int32 `json:"vcpus_reserved"`
MemoryMbReserved int32 `json:"memory_mb_reserved"`
}
// Aggregates per-team resource usage from the live sandboxes table.
// paused sandboxes count at 50% (ceil) for capacity reservation.
func (q *Queries) SampleSandboxMetrics(ctx context.Context) ([]SampleSandboxMetricsRow, error) {
rows, err := q.db.Query(ctx, sampleSandboxMetrics)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SampleSandboxMetricsRow
for rows.Next() {
var i SampleSandboxMetricsRow
if err := rows.Scan(
&i.TeamID,
&i.RunningCount,
&i.VcpusReserved,
&i.MemoryMbReserved,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View File

@ -99,6 +99,15 @@ type Sandbox struct {
TeamID string `json:"team_id"` TeamID string `json:"team_id"`
} }
type SandboxMetricsSnapshot struct {
ID int64 `json:"id"`
TeamID string `json:"team_id"`
SampledAt pgtype.Timestamptz `json:"sampled_at"`
RunningCount int32 `json:"running_count"`
VcpusReserved int32 `json:"vcpus_reserved"`
MemoryMbReserved int32 `json:"memory_mb_reserved"`
}
type Team struct { type Team struct {
ID string `json:"id"` ID string `json:"id"`
Name string `json:"name"` Name string `json:"name"`

157
internal/service/stats.go Normal file
View File

@ -0,0 +1,157 @@
package service
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.omukk.dev/wrenn/sandbox/internal/db"
)
// TimeRange identifies a chart time window.
type TimeRange string
const (
Range5m TimeRange = "5m"
Range1h TimeRange = "1h"
Range6h TimeRange = "6h"
Range24h TimeRange = "24h"
Range30d TimeRange = "30d"
)
type rangeConfig struct {
bucketSec int // bucket width in seconds for time-series aggregation
intervalLiteral string // PostgreSQL interval literal for the lookback window
}
var rangeConfigs = map[TimeRange]rangeConfig{
Range5m: {bucketSec: 3, intervalLiteral: "5 minutes"},
Range1h: {bucketSec: 30, intervalLiteral: "1 hour"},
Range6h: {bucketSec: 180, intervalLiteral: "6 hours"},
Range24h: {bucketSec: 720, intervalLiteral: "24 hours"},
Range30d: {bucketSec: 21600, intervalLiteral: "30 days"},
}
// ValidRange returns true if r is a known TimeRange value.
func ValidRange(r TimeRange) bool {
_, ok := rangeConfigs[r]
return ok
}
// StatPoint is one bucketed data point in the time-series.
type StatPoint struct {
Bucket time.Time
RunningCount int32
VCPUsReserved int32
MemoryMBReserved int32
}
// CurrentStats holds the most recent sampled values for a team.
type CurrentStats struct {
RunningCount int32
VCPUsReserved int32
MemoryMBReserved int32
SampledAt time.Time
}
// PeakStats holds the 30-day maximum values for a team.
type PeakStats struct {
RunningCount int32
VCPUs int32
MemoryMB int32
}
// StatsService computes sandbox metrics for the dashboard.
type StatsService struct {
DB *db.Queries
Pool *pgxpool.Pool
}
// GetStats returns current stats, 30-day peaks, and a time-series for the
// given team and time range. If no snapshots exist yet, zeros are returned.
func (s *StatsService) GetStats(ctx context.Context, teamID string, r TimeRange) (CurrentStats, PeakStats, []StatPoint, error) {
cfg, ok := rangeConfigs[r]
if !ok {
return CurrentStats{}, PeakStats{}, nil, fmt.Errorf("unknown range: %s", r)
}
// Current snapshot.
var current CurrentStats
cur, err := s.DB.GetCurrentMetrics(ctx, teamID)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return CurrentStats{}, PeakStats{}, nil, fmt.Errorf("get current metrics: %w", err)
}
if err == nil {
current = CurrentStats{
RunningCount: cur.RunningCount,
VCPUsReserved: cur.VcpusReserved,
MemoryMBReserved: cur.MemoryMbReserved,
SampledAt: cur.SampledAt.Time,
}
}
// 30-day peaks.
var peaks PeakStats
pk, err := s.DB.GetPeakMetrics(ctx, teamID)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return CurrentStats{}, PeakStats{}, nil, fmt.Errorf("get peak metrics: %w", err)
}
if err == nil {
peaks = PeakStats{
RunningCount: pk.PeakRunningCount,
VCPUs: pk.PeakVcpus,
MemoryMB: pk.PeakMemoryMb,
}
}
// Time-series — dynamic bucket width, executed via pgx directly.
series, err := s.queryTimeSeries(ctx, teamID, cfg)
if err != nil {
return CurrentStats{}, PeakStats{}, nil, fmt.Errorf("get time series: %w", err)
}
return current, peaks, series, nil
}
// timeSeriesSQL uses an epoch-floor trick to bucket rows by an arbitrary
// integer number of seconds without requiring TimescaleDB.
//
// $1 = bucket width in seconds (integer)
// $2 = team_id
// $3 = lookback interval literal (e.g. '1 hour')
const timeSeriesSQL = `
SELECT
to_timestamp(floor(extract(epoch FROM sampled_at) / $1) * $1) AS bucket,
AVG(running_count)::INTEGER AS running_count,
AVG(vcpus_reserved)::INTEGER AS vcpus_reserved,
AVG(memory_mb_reserved)::INTEGER AS memory_mb_reserved
FROM sandbox_metrics_snapshots
WHERE team_id = $2
AND sampled_at >= NOW() - $3::INTERVAL
GROUP BY bucket
ORDER BY bucket ASC
`
func (s *StatsService) queryTimeSeries(ctx context.Context, teamID string, cfg rangeConfig) ([]StatPoint, error) {
rows, err := s.Pool.Query(ctx, timeSeriesSQL, cfg.bucketSec, teamID, cfg.intervalLiteral)
if err != nil {
return nil, err
}
defer rows.Close()
var points []StatPoint
for rows.Next() {
var p StatPoint
var bucket time.Time
if err := rows.Scan(&bucket, &p.RunningCount, &p.VCPUsReserved, &p.MemoryMBReserved); err != nil {
return nil, err
}
p.Bucket = bucket
points = append(points, p)
}
return points, rows.Err()
}