Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 | 1x 1x 1x 612x 612x 606x 606x 606x 606x 606x 612x 612x 612x 289x 289x 289x 289x 289x 289x 289x 1x 1x 34x 34x 34x 34x 68x 68x 68x 68x 1190x 68x 1x 1x 1x 786x 258x 528x 527x 525x 524x 156x 54x 40x 39x 27x 532x 3055x 532x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 289x 1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 28x 28x 34x 646x 646x 532x 114x 34x 2864x 34x 34x 646x 34x 34x 34x 33x 33x 33x 33x 54x 54x 54x 54x 54x 54x 1x 34x 1x 1x 34x 34x 54x 378x 378x 54x 378x 216x 54x 34x 408x 408x 408x 34x 1020x 34x 34x 21x 34x 54x 34x 408x 34x 34x 34x 646x 646x 646x 646x 34x 34x 34x 34x 34x 34x | import { getServerSession } from "next-auth/next";
import { NextResponse } from "next/server";
import http from "node:http";
import { edcClient } from "@/lib/edc";
import { runQuery } from "@/lib/neo4j";
import {
azureResourceGroup,
azureSubscriptionId,
getContainerAppMetrics,
isAzureDeployment,
listContainerApps,
parseMemoryToBytes,
} from "@/lib/azure-arm";
import { authOptions } from "@/lib/auth";
import { cached } from "@/lib/server-cache";
export const dynamic = "force-dynamic";
// Topology aggregates ARM list + per-app metrics + Neo4j + CFM lookups.
// 30s SWR keeps the page snappy without losing live monitoring fidelity.
const TOPOLOGY_CACHE_TTL_MS = 30_000;
// ---------------------------------------------------------------------------
// Docker helpers (local-dev path)
// ---------------------------------------------------------------------------
const DOCKER_SOCKET = "/var/run/docker.sock";
function dockerGet<T>(path: string): Promise<T> {
return new Promise((resolve, reject) => {
const req = http.request(
{ socketPath: DOCKER_SOCKET, path, method: "GET" },
(res) => {
let data = "";
res.on("data", (chunk: Buffer) => (data += chunk.toString()));
res.on("end", () => {
try {
resolve(JSON.parse(data) as T);
} catch {
reject(new Error(`Docker API parse error: ${data.slice(0, 200)}`));
}
});
},
);
req.on("error", reject);
req.setTimeout(5000, () => {
req.destroy();
reject(new Error("Docker API timeout"));
});
req.end();
});
}
interface DockerContainer {
Id: string;
Names: string[];
State: string;
}
interface DockerStats {
cpu_stats: {
cpu_usage: { total_usage: number };
system_cpu_usage: number;
online_cpus: number;
};
precpu_stats: {
cpu_usage: { total_usage: number };
system_cpu_usage: number;
};
memory_stats: {
usage: number;
limit: number;
stats?: { cache?: number };
};
}
interface DockerInspect {
State: {
Health?: { Status: string };
Status: string;
StartedAt: string;
};
}
function calcCpuPercent(stats: DockerStats): number {
const cpuDelta =
stats.cpu_stats.cpu_usage.total_usage -
stats.precpu_stats.cpu_usage.total_usage;
const systemDelta =
stats.cpu_stats.system_cpu_usage - stats.precpu_stats.system_cpu_usage;
const numCpus = stats.cpu_stats.online_cpus || 1;
Eif (systemDelta > 0 && cpuDelta >= 0) {
return (cpuDelta / systemDelta) * numCpus * 100;
}
return 0;
}
function calcMemMB(stats: DockerStats): number {
const cache = stats.memory_stats.stats?.cache || 0;
return (
Math.round(((stats.memory_stats.usage - cache) / 1024 / 1024) * 10) / 10
);
}
// ---------------------------------------------------------------------------
// Types returned by this endpoint
// ---------------------------------------------------------------------------
type Severity = "critical" | "warning" | "healthy" | "unknown";
type MetricsSource = "docker" | "azure-monitor" | "none";
interface ParticipantComponent {
name: string;
container: string;
status: string;
severity: Severity;
cpu: number;
memMB: number;
uptime: string;
}
interface ParticipantTopology {
id: string;
displayName: string;
organization: string;
role: string;
did: string;
state: string;
health: Severity;
components: ParticipantComponent[];
}
interface InfraComponent extends ParticipantComponent {
layer: string;
}
// ---------------------------------------------------------------------------
// Server-side metrics history (in-memory, survives across requests)
// ---------------------------------------------------------------------------
interface MetricsSnapshot {
ts: number;
totalCpu: number;
totalMemMB: number;
}
const metricsHistory: MetricsSnapshot[] = [];
const MAX_HISTORY_AGE_MS = 48 * 60 * 60 * 1000;
function recordMetrics(totalCpu: number, totalMemMB: number) {
const now = Date.now();
metricsHistory.push({ ts: now, totalCpu, totalMemMB });
const cutoff = now - MAX_HISTORY_AGE_MS;
while (metricsHistory.length > 0 && metricsHistory[0].ts < cutoff) {
metricsHistory.shift();
}
}
interface PeakWindow {
peakCpu: number;
peakMemMB: number;
samples: number;
}
function computePeakWindow(fromMs: number, toMs: number): PeakWindow {
let peakCpu = 0;
let peakMemMB = 0;
let samples = 0;
for (const s of metricsHistory) {
Iif (s.ts >= fromMs && s.ts < toMs) {
peakCpu = Math.max(peakCpu, s.totalCpu);
peakMemMB = Math.max(peakMemMB, s.totalMemMB);
samples++;
}
}
return { peakCpu, peakMemMB, samples };
}
// ---------------------------------------------------------------------------
// Service catalogue — same logical components, mapped to either Docker
// container names (local) or ACA app names (Azure). The `container` field on
// the API response is whichever one matches the active deployment, so the UI
// shows the actual workload identifier the operator can grep in their cluster.
// ---------------------------------------------------------------------------
interface ServiceDef {
name: string;
docker: string;
aca: string;
core?: boolean;
layer?: string;
}
const PARTICIPANT_SERVICES: ServiceDef[] = [
{
name: "Control Plane",
docker: "health-dataspace-controlplane",
aca: "mvhd-controlplane",
core: true,
},
{
name: "Data Plane FHIR",
docker: "health-dataspace-dataplane-fhir",
aca: "mvhd-dp-fhir",
core: true,
},
{
name: "Data Plane OMOP",
docker: "health-dataspace-dataplane-omop",
aca: "mvhd-dp-omop",
core: true,
},
{
name: "Identity Hub",
docker: "health-dataspace-identityhub",
aca: "mvhd-identityhub",
core: true,
},
{
name: "Issuer Service",
docker: "health-dataspace-issuerservice",
aca: "mvhd-issuerservice",
core: false,
},
{
name: "Keycloak",
docker: "health-dataspace-keycloak",
aca: "mvhd-keycloak",
core: false,
},
{
name: "Vault",
docker: "health-dataspace-vault",
aca: "mvhd-vault",
core: false,
},
];
const INFRA_SERVICES: ServiceDef[] = [
{
name: "PostgreSQL",
docker: "health-dataspace-postgres",
aca: "mvhd-postgres",
layer: "infrastructure",
},
{
name: "NATS",
docker: "health-dataspace-nats",
aca: "mvhd-nats",
layer: "infrastructure",
},
{
name: "Neo4j",
docker: "health-dataspace-neo4j",
aca: "mvhd-neo4j",
layer: "infrastructure",
},
{
name: "Neo4j Proxy",
docker: "health-dataspace-neo4j-proxy",
aca: "mvhd-neo4j-proxy",
layer: "infrastructure",
},
{
name: "Traefik",
docker: "health-dataspace-traefik",
aca: "", // ACA has its own ingress, no equivalent app
layer: "infrastructure",
},
{
name: "Tenant Manager",
docker: "health-dataspace-tenant-manager",
aca: "mvhd-tenant-mgr",
layer: "cfm",
},
{
name: "Provision Manager",
docker: "health-dataspace-provision-manager",
aca: "mvhd-provision-mgr",
layer: "cfm",
},
{
name: "EDC-V Agent",
docker: "health-dataspace-cfm-edcv-agent",
aca: "",
layer: "cfm",
},
{
name: "Keycloak Agent",
docker: "health-dataspace-cfm-keycloak-agent",
aca: "",
layer: "cfm",
},
{
name: "Registration Agent",
docker: "health-dataspace-cfm-registration-agent",
aca: "",
layer: "cfm",
},
{
name: "Onboarding Agent",
docker: "health-dataspace-cfm-onboarding-agent",
aca: "",
layer: "cfm",
},
{
name: "UI",
docker: "health-dataspace-ui",
aca: "mvhd-ui",
layer: "infrastructure",
},
];
interface ResolvedMetrics {
status: string;
cpu: number;
memMB: number;
memLimitMB: number;
uptime: string;
}
const UNKNOWN_METRICS: ResolvedMetrics = {
status: "unknown",
cpu: 0,
memMB: 0,
memLimitMB: 0,
uptime: "—",
};
// ---------------------------------------------------------------------------
// Severity logic
// ---------------------------------------------------------------------------
function deriveSeverity(
status: string,
cpu: number,
memMB: number,
limitMB: number,
): Severity {
if (status === "unhealthy" || status === "stopped" || status === "exited") {
return "critical";
}
if (status === "starting") return "warning";
if (cpu > 80) return "warning";
if (limitMB > 0 && memMB / limitMB > 0.9) return "warning";
if (status === "healthy" || status === "running") return "healthy";
return "unknown";
}
function worstSeverity(sevs: Severity[]): Severity {
if (sevs.includes("critical")) return "critical";
if (sevs.includes("warning")) return "warning";
if (sevs.includes("unknown")) return "unknown";
return "healthy";
}
// ---------------------------------------------------------------------------
// Docker metrics resolver
// ---------------------------------------------------------------------------
async function resolveDockerContainer(
containers: DockerContainer[],
containerName: string,
): Promise<ResolvedMetrics> {
const c = containers.find((c) =>
c.Names.some((n) => n === `/${containerName}`),
);
if (!c) return { ...UNKNOWN_METRICS, status: "stopped" };
let status = "running";
let uptime = "—";
try {
const inspect = await dockerGet<DockerInspect>(`/containers/${c.Id}/json`);
Eif (inspect.State.Health?.Status) status = inspect.State.Health.Status;
const started = new Date(inspect.State.StartedAt);
const diffMs = Date.now() - started.getTime();
const hours = Math.floor(diffMs / 3600000);
const mins = Math.floor((diffMs % 3600000) / 60000);
uptime = hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
} catch {
/* ignore */
}
let cpu = 0;
let memMB = 0;
let memLimitMB = 0;
try {
const stats = await dockerGet<DockerStats>(
`/containers/${c.Id}/stats?stream=false`,
);
cpu = Math.round(calcCpuPercent(stats) * 100) / 100;
memMB = calcMemMB(stats);
memLimitMB = Math.round((stats.memory_stats.limit / 1024 / 1024) * 10) / 10;
} catch {
/* ignore */
}
return { status, cpu, memMB, memLimitMB, uptime };
}
// ---------------------------------------------------------------------------
// Azure Container Apps metrics resolver
// ---------------------------------------------------------------------------
async function loadAcaMetrics(): Promise<Map<string, ResolvedMetrics> | null> {
const subscriptionId = azureSubscriptionId();
const resourceGroup = azureResourceGroup();
if (!subscriptionId || !resourceGroup) return null;
let apps: Awaited<ReturnType<typeof listContainerApps>>;
try {
apps = await listContainerApps(subscriptionId, resourceGroup);
} catch (err) {
console.warn("ARM listContainerApps failed (topology):", err);
return null;
}
const map = new Map<string, ResolvedMetrics>();
await Promise.all(
apps.map(async (app) => {
const container = app.properties.template?.containers?.[0];
const cpuReservation = container?.resources?.cpu ?? 0;
const memReservationBytes = parseMemoryToBytes(
container?.resources?.memory,
);
let sample: Awaited<ReturnType<typeof getContainerAppMetrics>> | null =
null;
try {
sample = await getContainerAppMetrics(
subscriptionId,
resourceGroup,
app.name,
);
} catch {
/* metrics may be missing */
}
const runningStatus =
app.properties.runningStatus ?? app.properties.provisioningState ?? "";
const status = /running/i.test(runningStatus)
? "healthy"
: /stopped|stop/i.test(runningStatus)
? "stopped"
: "unknown";
const rawCpuPct = sample?.cpuPercent ?? 0;
const cpu =
cpuReservation > 0
? Math.round((rawCpuPct / cpuReservation) * 100) / 100
: Math.round(rawCpuPct * 100) / 100;
const usedBytes = sample?.memPercent ?? 0;
const memMB = Math.round((usedBytes / 1024 / 1024) * 10) / 10;
const memLimitMB =
Math.round((memReservationBytes / 1024 / 1024) * 10) / 10;
map.set(app.name, {
status,
cpu,
memMB,
memLimitMB,
uptime: "—",
});
}),
);
return map;
}
// ---------------------------------------------------------------------------
// Neo4j participant fallback (used when CFM tenant-manager is unreachable)
// ---------------------------------------------------------------------------
async function loadParticipantsFromNeo4j(): Promise<
{ id: string; name: string; type: string; did: string }[]
> {
try {
return await runQuery<{
id: string;
name: string;
type: string;
did: string;
}>(
`MATCH (p:Participant)
WHERE p.name IS NOT NULL AND p.name <> ''
RETURN coalesce(p.participantId, p.id) AS id,
p.name AS name,
coalesce(p.participantType, '—') AS type,
coalesce(p.did, p.participantId, '—') AS did
ORDER BY p.name`,
);
} catch (err) {
console.warn("Neo4j participant fallback failed (topology):", err);
return [];
}
}
// ---------------------------------------------------------------------------
// GET /api/admin/components/topology
// ---------------------------------------------------------------------------
export async function GET() {
const session = await getServerSession(authOptions);
const roles = (session as { roles?: string[] } | null)?.roles ?? [];
Iif (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
Iif (!roles.includes("EDC_ADMIN")) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const result = await cached(
"admin-components-topology",
TOPOLOGY_CACHE_TTL_MS,
buildTopologyResponse,
);
return NextResponse.json(result);
}
async function buildTopologyResponse() {
// ── 1. Resolve metrics from whichever runtime is available ──
let metricsSource: MetricsSource = "none";
let acaMetrics: Map<string, ResolvedMetrics> | null = null;
let dockerContainers: DockerContainer[] = [];
let dockerOk = false;
Iif (isAzureDeployment()) {
acaMetrics = await loadAcaMetrics();
if (acaMetrics && acaMetrics.size > 0) {
metricsSource = "azure-monitor";
}
}
Eif (metricsSource === "none") {
try {
dockerContainers = await dockerGet<DockerContainer[]>(
"/containers/json?all=true&filters=" +
encodeURIComponent(JSON.stringify({ name: ["health-dataspace"] })),
);
dockerOk = true;
metricsSource = "docker";
} catch {
/* socket unavailable */
}
}
const isAzure = metricsSource === "azure-monitor";
/** Resolve a service to its current metrics from the active runtime. */
async function resolveService(svc: ServiceDef): Promise<ResolvedMetrics> {
Iif (isAzure) {
if (!svc.aca) return UNKNOWN_METRICS;
return acaMetrics?.get(svc.aca) ?? UNKNOWN_METRICS;
}
if (dockerOk) {
return resolveDockerContainer(dockerContainers, svc.docker);
}
return UNKNOWN_METRICS;
}
const containerLabel = (svc: ServiceDef) =>
isAzure ? svc.aca || svc.docker : svc.docker;
// ── 2. Pre-resolve metrics for every shared service (one round-trip) ──
const serviceMetrics = new Map<string, ResolvedMetrics>();
await Promise.all(
[...PARTICIPANT_SERVICES, ...INFRA_SERVICES].map(async (svc) => {
serviceMetrics.set(containerLabel(svc), await resolveService(svc));
}),
);
// ── 3. Resolve participants — CFM first, Neo4j fallback ──
type RawParticipant = {
id: string;
displayName: string;
organization: string;
role: string;
did: string;
state: string;
};
const participantsRaw: RawParticipant[] = [];
try {
const tenants =
await edcClient.tenant<
{ id: string; version: number; properties: Record<string, string> }[]
>("/v1alpha1/tenants");
let edcParticipants: { "@id": string; identity: string; state: string }[] =
[];
try {
edcParticipants = await edcClient.management<
{ "@id": string; identity: string; state: string }[]
>("/v5alpha/participants");
} catch {
/* auth may be unavailable */
}
for (const t of tenants) {
let profiles: {
identifier?: string;
properties?: {
"cfm.vpa.state"?: { participantContextId?: string };
[k: string]: unknown;
};
}[] = [];
try {
profiles = await edcClient.tenant<typeof profiles>(
`/v1alpha1/tenants/${t.id}/participant-profiles`,
);
} catch {
/* no profiles */
}
const ctxId =
profiles?.[0]?.properties?.["cfm.vpa.state"]?.participantContextId;
const ctx = edcParticipants.find((p) => p["@id"] === ctxId);
participantsRaw.push({
id: t.id,
displayName: t.properties?.displayName || t.id,
organization: t.properties?.organization || "—",
role: t.properties?.ehdsParticipantType || t.properties?.role || "—",
did:
ctx?.identity ||
profiles?.[0]?.identifier ||
t.properties?.did ||
"—",
state: ctx?.state || "—",
});
}
} catch (err) {
console.warn("CFM tenant-manager unreachable (topology):", err);
}
if (participantsRaw.length === 0) {
const neo = await loadParticipantsFromNeo4j();
for (const p of neo) {
participantsRaw.push({
id: p.id,
displayName: p.name,
organization: p.name,
role: p.type,
did: p.did,
state: "SEEDED",
});
}
}
// ── 4. Build per-participant topology rows ──
//
// On Azure (ACA) there is exactly one container per service across ALL
// participants — `mvhd-controlplane`, `mvhd-dataplane-fhir`, etc. are
// single-instance. Participants are logical DIDs, not deployments, so
// per-participant CPU/MEM is meaningless: we'd either copy the same
// shared-pool number onto every row (misleading) or divide it by N
// (mathematically cute but implies a per-participant allocation that
// does not exist).
//
// Instead, on Azure we surface the same underlying ACA-app metric on
// every participant row and set `metricsShared=true` so the UI can
// annotate the value with a "shared" hint. That way the per-row CPU/MEM
// is *correct* (it reflects the actual container the participant uses)
// while the user knows the same number applies across all participants.
//
// On local JAD (docker), every participant has its own containers
// (ihub-alpha, dataplane-pharmaco-fhir, …) and the per-row values are
// independent; metricsShared stays false.
const metricsShared = isAzure && participantsRaw.length > 0;
const participantTopologies: ParticipantTopology[] = participantsRaw.map(
(p) => {
const components: ParticipantComponent[] = PARTICIPANT_SERVICES.map(
(svc) => {
const m = serviceMetrics.get(containerLabel(svc)) ?? UNKNOWN_METRICS;
return {
name: svc.name,
container: containerLabel(svc),
status: m.status,
severity: deriveSeverity(m.status, m.cpu, m.memMB, m.memLimitMB),
cpu: m.cpu,
memMB: m.memMB,
uptime: m.uptime,
};
},
);
const coreSeverities = components
.filter((_, i) => PARTICIPANT_SERVICES[i].core)
.map((c) => c.severity);
return {
...p,
health: worstSeverity(coreSeverities),
components,
};
},
);
// ── 5. Build infrastructure rows (skip services with no equivalent on
// the active runtime — e.g. Traefik on ACA) ──
const infraComponents: InfraComponent[] = INFRA_SERVICES.filter((svc) =>
isAzure ? svc.aca !== "" : true,
).map((svc) => {
const m = serviceMetrics.get(containerLabel(svc)) ?? UNKNOWN_METRICS;
return {
name: svc.name,
container: containerLabel(svc),
layer: svc.layer ?? "infrastructure",
status: m.status,
severity: deriveSeverity(m.status, m.cpu, m.memMB, m.memLimitMB),
cpu: m.cpu,
memMB: m.memMB,
uptime: m.uptime,
};
});
infraComponents.sort(
(a, b) => a.layer.localeCompare(b.layer) || a.name.localeCompare(b.name),
);
const severityOrder = { critical: 0, warning: 1, unknown: 2, healthy: 3 };
participantTopologies.sort(
(a, b) =>
severityOrder[a.health] - severityOrder[b.health] ||
a.displayName.localeCompare(b.displayName),
);
const degradedCount = participantTopologies.filter(
(p) => p.health === "critical" || p.health === "warning",
).length;
// ── 6. Cluster-wide metrics ──
//
// Source: the raw per-container `serviceMetrics` map, summed once per
// distinct container. MUST NOT use participantTopologies.components here
// because those now carry divided per-participant shares on Azure; using
// them would under-report the real cluster footprint by `shareDivisor`.
const clusterContainers = new Set<string>([
...PARTICIPANT_SERVICES.map(containerLabel),
...INFRA_SERVICES.filter((svc) => (isAzure ? svc.aca !== "" : true)).map(
containerLabel,
),
]);
let clusterCpu = 0;
let clusterMemMB = 0;
for (const container of clusterContainers) {
const m = serviceMetrics.get(container);
Iif (!m) continue;
clusterCpu += m.cpu;
clusterMemMB += m.memMB;
}
recordMetrics(clusterCpu, clusterMemMB);
const now = Date.now();
const last24h = computePeakWindow(now - 24 * 3600_000, now);
const prev24h = computePeakWindow(now - 48 * 3600_000, now - 24 * 3600_000);
const deploymentTarget = isAzureDeployment()
? "azure"
: dockerOk
? "docker"
: "unknown";
return {
timestamp: new Date().toISOString(),
metricsSource,
deploymentTarget,
// True when per-participant metrics are that participant's share of a
// shared infrastructure pool (ACA case). The UI uses this to annotate
// rows with "shared" so users understand the values are not
// independent per-container reservations.
metricsShared,
// Backwards-compatible flag — true whenever ANY runtime metrics are
// available, so the old "Docker socket not available" banner only fires
// when both Docker and Azure paths failed.
dockerAvailable: metricsSource !== "none",
participants: participantTopologies,
infrastructure: infraComponents,
summary: {
totalParticipants: participantTopologies.length,
degradedParticipants: degradedCount,
totalInfra: infraComponents.length,
},
clusterMetrics: {
currentCpu: Math.round(clusterCpu * 100) / 100,
currentMemMB: Math.round(clusterMemMB * 10) / 10,
last24h: {
peakCpu: Math.round(last24h.peakCpu * 100) / 100,
peakMemMB: Math.round(last24h.peakMemMB * 10) / 10,
samples: last24h.samples,
},
prev24h: {
peakCpu: Math.round(prev24h.peakCpu * 100) / 100,
peakMemMB: Math.round(prev24h.peakMemMB * 10) / 10,
samples: prev24h.samples,
},
},
};
}
|