OPC # 0006: Build monitor grid, CI SolutionBuild rows, by-sha endpoint, dashboard SHA badge

This commit is contained in:
amadzarak
2026-04-26 16:47:40 -04:00
parent c7da1eb017
commit 66ef611761
4 changed files with 318 additions and 3 deletions
@@ -1,4 +1,5 @@
using ControlPlane.Api.Services;
using ControlPlane.Core.Models;
using ControlPlane.Core.Services;
using System.Text.Json;
@@ -16,6 +17,7 @@ public static class ProjectBuildEndpoints
var group = app.MapGroup("/api/builds").WithTags("Builds");
group.MapGet("/projects", GetProjects);
group.MapGet("/history", GetHistory);
group.MapGet("/by-sha", GetBySha);
group.MapPost("/{projectName}", TriggerProjectBuild);
return app;
}
@@ -27,6 +29,31 @@ public static class ProjectBuildEndpoints
private static async Task<IResult> GetHistory(BuildHistoryService history) =>
Results.Ok(await history.GetBuildsAsync());
/// <summary>
/// Returns the latest SolutionBuild record for the given commit SHA, or null if none exists.
/// Used by the OPC CommitsTab to render per-commit CI status dots.
/// </summary>
private static async Task<IResult> GetBySha(string sha, BuildHistoryService history)
{
if (string.IsNullOrWhiteSpace(sha))
return Results.BadRequest("sha is required");
var builds = await history.GetBuildsByShaAsync(sha);
var latest = builds
.Where(b => b.Kind == BuildKind.SolutionBuild)
.MaxBy(b => b.StartedAt);
return Results.Ok(latest is null ? null : new
{
latest.Id,
latest.Status,
latest.StartedAt,
latest.FinishedAt,
latest.DurationMs,
latest.CommitSha,
});
}
/// <summary>
/// Triggers a build for a named project and streams SSE output.
/// projectName must match one of the names returned by GET /api/builds/projects.
+23
View File
@@ -30,6 +30,29 @@ export async function getBuildHistory(): Promise<BuildRecord[]> {
return res.json();
}
export interface ShaBuildResult {
id: string;
status: 'Running' | 'Succeeded' | 'Failed';
startedAt: string;
finishedAt?: string;
durationMs?: number;
commitSha?: string;
}
/** Returns the latest SolutionBuild for a given SHA, or null if none exists. */
export async function getBuildBySha(sha: string): Promise<ShaBuildResult | null> {
const res = await fetch(`${BASE_URL}/api/builds/by-sha?sha=${encodeURIComponent(sha)}`);
if (!res.ok) throw new Error(`getBuildBySha failed: ${res.statusText}`);
return res.json();
}
/** Batch-fetches SolutionBuild status for multiple SHAs. Returns a map of sha -> result|null. */
export async function getBuildsByShas(shas: string[]): Promise<Map<string, ShaBuildResult | null>> {
const unique = [...new Set(shas.filter(Boolean))];
const entries = await Promise.all(unique.map(async (sha) => [sha, await getBuildBySha(sha)] as const));
return new Map(entries);
}
export function triggerProjectBuild(
projectName: string,
onLine: (line: string) => void,
@@ -1,10 +1,266 @@
import { useEffect, useRef, useState } from 'react';
import {
Button, Callout, Intent, Tag, Spinner, NonIdealState,
Collapse, HTMLTable,
AnchorButton, Button, Callout, Collapse, HTMLTable, Intent, NonIdealState, Spinner, Tag,
} from '@blueprintjs/core';
import { getProjects, getBuildHistory, type ProjectDefinition, type BuildRecord } from '../api/buildApi';
import { getGitLog, type GitCommit } from '../api/gitApi';
const BASE_URL = import.meta.env.VITE_API_URL ?? '';
const KIND_LABEL: Record<string, string> = {
DotnetProject: '.NET',
NpmProject: 'npm',
DockerImage: 'Docker',
SolutionBuild: 'CI',
};
const KIND_INTENT: Record<string, Intent> = {
DotnetProject: Intent.PRIMARY,
NpmProject: Intent.WARNING,
DockerImage: Intent.NONE,
SolutionBuild: Intent.SUCCESS,
};
const STATUS_INTENT: Record<string, Intent> = {
Succeeded: Intent.SUCCESS,
Failed: Intent.DANGER,
Running: Intent.PRIMARY,
};
// ── Inline log viewer ─────────────────────────────────────────────────────────
function LogRow({ lines }: { lines: string[] }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [lines]);
return (
<tr>
<td colSpan={7} style={{ padding: 0 }}>
<div ref={ref} style={{
fontFamily: 'monospace', fontSize: '0.7rem',
background: '#111', color: '#d4d4d4',
padding: '0.5rem 0.75rem', maxHeight: 200, overflowY: 'auto',
whiteSpace: 'pre-wrap', wordBreak: 'break-all',
}}>
{lines.map((l, i) => <div key={i}>{l}</div>)}
</div>
</td>
</tr>
);
}
// ── Manual project row ────────────────────────────────────────────────────────
function ProjectRow({
project, lastBuild, onBuilt,
}: {
project: ProjectDefinition;
lastBuild: BuildRecord | undefined;
onBuilt: () => void;
}) {
const [building, setBuilding] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const [open, setOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleBuild = async () => {
setBuilding(true);
setOpen(true);
setLogs([]);
setError(null);
try {
const res = await fetch(`${BASE_URL}/api/builds/${encodeURIComponent(project.name)}`, { method: 'POST' });
if (!res.ok || !res.body) throw new Error(res.statusText);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split('\n\n');
buffer = parts.pop() ?? '';
for (const chunk of parts) {
const dataLine = chunk.replace(/^data:\s*/m, '').trim();
if (!dataLine) continue;
try {
const msg = JSON.parse(dataLine);
if (msg.done) onBuilt();
else if (typeof msg.line === 'string') setLogs((p) => [...p.slice(-1000), msg.line]);
} catch { /* ignore */ }
}
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Unknown error');
} finally {
setBuilding(false);
}
};
const statusIntent = lastBuild ? STATUS_INTENT[lastBuild.status] : Intent.NONE;
const duration = lastBuild?.durationMs != null ? `${(lastBuild.durationMs / 1000).toFixed(1)}s` : '—';
const lastRun = lastBuild ? new Date(lastBuild.startedAt).toLocaleString() : '—';
return (
<>
<tr>
<td>
<span style={{ fontWeight: 600 }}>{project.name}</span>
<br />
<code style={{ fontSize: '0.68rem', color: '#8f99a8' }}>{project.relativePath}</code>
</td>
<td><Tag intent={KIND_INTENT[project.kind] ?? Intent.NONE} minimal round>{KIND_LABEL[project.kind] ?? project.kind}</Tag></td>
<td><Tag minimal round style={{ color: '#8f99a8' }}>manual</Tag></td>
<td><Tag intent={statusIntent} minimal round>{lastBuild?.status ?? 'Never'}</Tag></td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem' }}>{lastRun}</td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem', textAlign: 'right' }}>{duration}</td>
<td style={{ textAlign: 'right' }}>
<Button icon="play" small intent={Intent.PRIMARY} loading={building} onClick={handleBuild} text="Build" />
{logs.length > 0 && (
<Button minimal small icon={open ? 'chevron-up' : 'chevron-down'} onClick={() => setOpen((o) => !o)} style={{ marginLeft: 4 }} />
)}
</td>
</tr>
{error && (
<tr><td colSpan={7}><Callout intent={Intent.DANGER} compact>{error}</Callout></td></tr>
)}
<Collapse isOpen={open && logs.length > 0} keepChildrenMounted>
<LogRow lines={logs} />
</Collapse>
</>
);
}
// ── CI (SolutionBuild) row ───────────────────────────────────────────────────
function CiRow({ build, giteaBase }: { build: BuildRecord; giteaBase: string }) {
const [open, setOpen] = useState(false);
const repo = build.target.replace(/\.slnx?$/, ''); // "ControlPlane.slnx" → "ControlPlane"
const shortSha = build.commitSha?.slice(0, 7);
const shaUrl = build.commitSha
? `${giteaBase}/ClarityStack/${repo === 'ControlPlane' ? 'OPC' : repo}/commit/${build.commitSha}`
: null;
const duration = build.durationMs != null ? `${(build.durationMs / 1000).toFixed(1)}s` : '—';
const lastRun = new Date(build.startedAt).toLocaleString();
return (
<>
<tr>
<td>
<span style={{ fontWeight: 600 }}>{repo}</span>
<br />
<code style={{ fontSize: '0.68rem', color: '#8f99a8' }}>{build.target}</code>
</td>
<td><Tag intent={Intent.SUCCESS} minimal round>CI</Tag></td>
<td>
{shortSha && shaUrl ? (
<AnchorButton href={shaUrl} target="_blank" rel="noopener noreferrer" minimal small
style={{ fontFamily: 'monospace', fontSize: '0.72rem', padding: '0 4px' }}>
{shortSha}
</AnchorButton>
) : <span style={{ color: '#8f99a8', fontSize: '0.8rem' }}></span>}
</td>
<td><Tag intent={STATUS_INTENT[build.status] ?? Intent.NONE} minimal round>{build.status}</Tag></td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem' }}>{lastRun}</td>
<td style={{ color: '#8f99a8', fontSize: '0.8rem', textAlign: 'right' }}>{duration}</td>
<td style={{ textAlign: 'right' }}>
{build.log.length > 0 && (
<Button minimal small icon={open ? 'chevron-up' : 'chevron-down'} onClick={() => setOpen((o) => !o)} text={open ? 'Hide' : 'Log'} />
)}
</td>
</tr>
<Collapse isOpen={open} keepChildrenMounted>
<LogRow lines={build.log} />
</Collapse>
</>
);
}
// ── Page ──────────────────────────────────────────────────────────────────────
export default function BuildMonitorPage() {
const [projects, setProjects] = useState<ProjectDefinition[]>([]);
const [history, setHistory] = useState<BuildRecord[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const giteaBase = (import.meta.env.VITE_GITEA_URL as string | undefined) ?? 'https://opc.clarity.test';
const load = async () => {
setLoading(true);
setError(null);
try {
const [p, h] = await Promise.all([getProjects(), getBuildHistory()]);
setProjects(p);
setHistory(h);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load');
} finally {
setLoading(false);
}
};
useEffect(() => { load(); }, []);
// Latest SolutionBuild per solution target (one CI row per repo)
const ciBuilds = Object.values(
history
.filter((b) => b.kind === 'SolutionBuild')
.reduce<Record<string, BuildRecord>>((acc, b) => {
if (!acc[b.target] || new Date(b.startedAt) > new Date(acc[b.target].startedAt))
acc[b.target] = b;
return acc;
}, {})
);
// Latest manual build per project path
const lastBuildFor = (project: ProjectDefinition): BuildRecord | undefined =>
history.find((b) => b.target === project.relativePath);
return (
<>
<div className="page-header">
<div>
<h1>Build Monitor</h1>
<p>CI gate builds (webhook-triggered) and manual per-project builds.</p>
</div>
<Button icon="refresh" minimal onClick={load} loading={loading} title="Refresh" />
</div>
{error && (
<Callout intent={Intent.DANGER} title="Failed to load" style={{ marginBottom: '1rem' }}>{error}</Callout>
)}
{loading && <NonIdealState icon={<Spinner />} title="Loading..." />}
{!loading && !error && (
<HTMLTable className="bp6-html-table-condensed bp6-html-table-striped" style={{ width: '100%' }}>
<thead>
<tr>
<th>Name</th>
<th>Kind</th>
<th>Commit / Trigger</th>
<th>Status</th>
<th>Last Run</th>
<th style={{ textAlign: 'right' }}>Duration</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{ciBuilds.map((b) => (
<CiRow key={`ci-${b.target}`} build={b} giteaBase={giteaBase} />
))}
{projects.map((p) => (
<ProjectRow key={p.name} project={p} lastBuild={lastBuildFor(p)} onBuilt={load} />
))}
{ciBuilds.length === 0 && projects.length === 0 && (
<tr><td colSpan={7} style={{ textAlign: 'center', color: '#8f99a8', padding: '2rem' }}>No builds yet.</td></tr>
)}
</tbody>
</HTMLTable>
)}
</>
);
}
const BASE_URL = import.meta.env.VITE_API_URL ?? '';
@@ -43,6 +43,15 @@ function TenantCard({ t }: { t: TenantRecord }) {
<div style={{ display: 'flex', gap: '0.4rem', alignItems: 'center' }}>
<Tag intent={ENV_INTENT[t.environment] ?? Intent.NONE} round minimal>{t.environment}</Tag>
<Tag intent={t.status === 'Provisioned' ? Intent.SUCCESS : Intent.WARNING} round>{t.status}</Tag>
{t.containerImage && (() => {
const sha = t.containerImage.includes(':') ? t.containerImage.split(':').pop()! : t.containerImage;
return (
<Tag minimal round style={{ fontFamily: 'monospace', fontSize: '0.7rem', color: '#8f99a8' }}
title={t.containerImage}>
{sha.slice(0, 7)}
</Tag>
);
})()}
</div>
</div>