-
Notifications
You must be signed in to change notification settings - Fork 0
fix: expose Croco operations status plane #817
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| "@croco/transports-http": patch | ||
| "@croco/cli": patch | ||
| --- | ||
|
|
||
| Expose canonical operations endpoints and add `croco ops status` for machine-readable and human-readable runtime status checks. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,333 @@ | ||
| import { defineCommand } from "citty"; | ||
| import { Problem, ProblemCategory } from "@croco/problems-core"; | ||
| import { GLOBAL_OPTIONS } from "./options.js"; | ||
|
|
||
| const DEFAULT_TIMEOUT_MS = 5000; | ||
| const DEFAULT_TOKEN_HEADER = "X-Diagnostics-Token"; | ||
| const OPS_ENDPOINTS = [ | ||
| { name: "health", path: "/health" }, | ||
| { name: "ready", path: "/ready" }, | ||
| { name: "diagnostics", path: "/diagnostics" }, | ||
| { name: "metrics", path: "/metrics" }, | ||
| ] as const; | ||
|
|
||
| export type OpsEndpointName = (typeof OPS_ENDPOINTS)[number]["name"]; | ||
|
|
||
| export type OpsEndpointSnapshot = { | ||
| readonly name: OpsEndpointName; | ||
| readonly url: string; | ||
| readonly httpStatus: number | null; | ||
| readonly ok: boolean; | ||
| readonly body: unknown; | ||
| readonly error?: string; | ||
| }; | ||
|
|
||
| export type OpsStatusSummary = "healthy" | "degraded" | "unhealthy"; | ||
|
|
||
| export type OpsStatusReport = { | ||
| readonly target: string; | ||
| readonly timestamp: string; | ||
| readonly summary: OpsStatusSummary; | ||
| readonly endpoints: readonly OpsEndpointSnapshot[]; | ||
| }; | ||
|
|
||
| export type OpsStatusFetch = (input: string, init?: RequestInit) => Promise<Response>; | ||
|
|
||
| export type RunOpsStatusOptions = { | ||
| readonly fetch?: OpsStatusFetch; | ||
| readonly timeoutMs?: number; | ||
| readonly token?: string; | ||
| readonly tokenHeader?: string; | ||
| }; | ||
|
|
||
| class InvalidOpsTimeoutProblem extends Problem { | ||
| constructor(value: unknown) { | ||
| super( | ||
| "cli/invalid-ops-timeout", | ||
| ProblemCategory.BadRequest, | ||
| `Invalid timeout: ${String(value)}`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| class InvalidOpsTargetUrlProblem extends Problem { | ||
| constructor(target: string) { | ||
| super( | ||
| "cli/invalid-ops-target-url", | ||
| ProblemCategory.BadRequest, | ||
| `Invalid Croco app URL: ${target}`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| export const opsStatus = defineCommand({ | ||
| meta: { | ||
| name: "status", | ||
| description: "Read Croco operational endpoints", | ||
| }, | ||
| args: { | ||
| ...GLOBAL_OPTIONS, | ||
| url: { | ||
| type: "positional", | ||
| required: true, | ||
| description: "Croco app base URL", | ||
| }, | ||
| json: { | ||
| type: "boolean", | ||
| description: "Print the machine-readable status report", | ||
| }, | ||
| token: { | ||
| type: "string", | ||
| description: "Diagnostics token", | ||
| }, | ||
| tokenHeader: { | ||
| type: "string", | ||
| default: DEFAULT_TOKEN_HEADER, | ||
| description: "Diagnostics token header", | ||
| }, | ||
| timeout: { | ||
| type: "string", | ||
| description: "Per-endpoint timeout in milliseconds", | ||
| }, | ||
| }, | ||
| async run({ args }) { | ||
| const report = await runOpsStatus(String(args.url ?? ""), { | ||
| token: typeof args.token === "string" ? args.token : undefined, | ||
| tokenHeader: typeof args.tokenHeader === "string" ? args.tokenHeader : DEFAULT_TOKEN_HEADER, | ||
| timeoutMs: parseTimeoutMs(args.timeout), | ||
| }); | ||
|
|
||
| console.log(args.json ? JSON.stringify(report, null, 2) : formatOpsStatusReport(report)); | ||
| process.exitCode = getOpsStatusExitCode(report.summary); | ||
| }, | ||
| }); | ||
|
|
||
| export const ops = defineCommand({ | ||
| meta: { | ||
| name: "ops", | ||
| description: "Inspect Croco operational endpoints", | ||
| }, | ||
| args: { | ||
| ...GLOBAL_OPTIONS, | ||
| }, | ||
| subCommands: { | ||
| status: opsStatus, | ||
| }, | ||
| }); | ||
|
|
||
| export async function runOpsStatus( | ||
| target: string, | ||
| options: RunOpsStatusOptions = {}, | ||
| ): Promise<OpsStatusReport> { | ||
| const targetUrl = parseTargetUrl(target); | ||
| const fetchEndpoint = options.fetch ?? fetch; | ||
| const timeoutMs = parseTimeoutMs(options.timeoutMs ?? DEFAULT_TIMEOUT_MS) ?? DEFAULT_TIMEOUT_MS; | ||
| const tokenHeader = options.tokenHeader ?? DEFAULT_TOKEN_HEADER; | ||
| const snapshots = await Promise.all( | ||
| OPS_ENDPOINTS.map(async (endpoint) => | ||
| fetchOperationalEndpoint({ | ||
| endpoint, | ||
| fetchEndpoint, | ||
| targetUrl, | ||
| timeoutMs, | ||
| token: options.token, | ||
| tokenHeader, | ||
| }), | ||
| ), | ||
| ); | ||
|
|
||
| return { | ||
| target: targetUrl.toString(), | ||
| timestamp: new Date().toISOString(), | ||
| summary: summarizeOpsStatus(snapshots), | ||
| endpoints: snapshots, | ||
| }; | ||
| } | ||
|
|
||
| export function formatOpsStatusReport(report: OpsStatusReport): string { | ||
| const lines = [ | ||
| `Croco ops status: ${report.summary}`, | ||
| `Target: ${report.target}`, | ||
| `Checked: ${report.timestamp}`, | ||
| "", | ||
| ]; | ||
|
|
||
| for (const endpoint of report.endpoints) { | ||
| const httpStatus = endpoint.httpStatus === null ? "ERR" : String(endpoint.httpStatus); | ||
| const status = describeEndpointStatus(endpoint); | ||
| const suffix = endpoint.error ? ` - ${endpoint.error}` : ""; | ||
| lines.push(`${endpoint.name.padEnd(11)} ${httpStatus.padEnd(3)} ${status}${suffix}`); | ||
| } | ||
|
|
||
| return lines.join("\n"); | ||
| } | ||
|
|
||
| export function getOpsStatusExitCode(summary: OpsStatusSummary): number { | ||
| return summary === "healthy" ? 0 : 1; | ||
| } | ||
|
|
||
| function parseTimeoutMs(value: unknown): number | undefined { | ||
| if (value === undefined) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const parsed = Number(value); | ||
| if (!Number.isFinite(parsed) || parsed <= 0) { | ||
| throw new InvalidOpsTimeoutProblem(value); | ||
| } | ||
|
|
||
| return parsed; | ||
| } | ||
|
|
||
| function parseTargetUrl(target: string): URL { | ||
| try { | ||
| return new URL(target); | ||
| } catch { | ||
| throw new InvalidOpsTargetUrlProblem(target); | ||
| } | ||
| } | ||
|
|
||
| async function fetchOperationalEndpoint({ | ||
| endpoint, | ||
| fetchEndpoint, | ||
| targetUrl, | ||
| timeoutMs, | ||
| token, | ||
| tokenHeader, | ||
| }: { | ||
| readonly endpoint: (typeof OPS_ENDPOINTS)[number]; | ||
| readonly fetchEndpoint: OpsStatusFetch; | ||
| readonly targetUrl: URL; | ||
| readonly timeoutMs: number; | ||
| readonly token?: string; | ||
| readonly tokenHeader: string; | ||
| }): Promise<OpsEndpointSnapshot> { | ||
| const controller = new AbortController(); | ||
| const timeout = setTimeout(() => controller.abort(), timeoutMs); | ||
| const headers = new Headers({ Accept: "application/json" }); | ||
|
|
||
| if (token && endpoint.name === "diagnostics") { | ||
| headers.set(tokenHeader, token); | ||
| } | ||
|
|
||
| const url = resolveEndpointUrl(targetUrl, endpoint.path); | ||
|
|
||
| try { | ||
| const response = await fetchEndpoint(url, { | ||
| headers, | ||
| signal: controller.signal, | ||
| }); | ||
| const body = await readResponseBody(response); | ||
|
|
||
| return { | ||
| name: endpoint.name, | ||
| url, | ||
| httpStatus: response.status, | ||
| ok: response.ok, | ||
| body, | ||
| }; | ||
| } catch (error) { | ||
| return { | ||
| name: endpoint.name, | ||
| url, | ||
| httpStatus: null, | ||
| ok: false, | ||
| body: null, | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }; | ||
| } finally { | ||
| clearTimeout(timeout); | ||
| } | ||
| } | ||
|
|
||
| function resolveEndpointUrl(targetUrl: URL, path: string): string { | ||
| const url = new URL(targetUrl.toString()); | ||
| const basePath = url.pathname === "/" ? "" : url.pathname.replace(/\/$/, ""); | ||
| url.pathname = `${basePath}${path}`; | ||
| url.search = ""; | ||
| url.hash = ""; | ||
| return url.toString(); | ||
| } | ||
|
|
||
| async function readResponseBody(response: Response): Promise<unknown> { | ||
| const text = await response.text(); | ||
| if (text.length === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| try { | ||
| return JSON.parse(text) as unknown; | ||
| } catch { | ||
| return text; | ||
| } | ||
| } | ||
|
|
||
| function summarizeOpsStatus(endpoints: readonly OpsEndpointSnapshot[]): OpsStatusSummary { | ||
| if (endpoints.some((endpoint) => isEndpointUnhealthy(endpoint))) { | ||
| return "unhealthy"; | ||
| } | ||
|
|
||
| if (endpoints.some((endpoint) => isEndpointDegraded(endpoint))) { | ||
| return "degraded"; | ||
| } | ||
|
|
||
| return "healthy"; | ||
| } | ||
|
|
||
| function isEndpointUnhealthy(endpoint: OpsEndpointSnapshot): boolean { | ||
| if (!endpoint.ok) { | ||
| return endpoint.name === "health" || endpoint.name === "ready"; | ||
| } | ||
|
|
||
| const status = readStringField(endpoint.body, "status"); | ||
| const summary = readStringField(endpoint.body, "summary"); | ||
|
|
||
| return status === "down" || status === "unhealthy" || summary === "issues_detected"; | ||
| } | ||
|
|
||
| function isEndpointDegraded(endpoint: OpsEndpointSnapshot): boolean { | ||
| if (!endpoint.ok) { | ||
| return true; | ||
| } | ||
|
|
||
| const status = readStringField(endpoint.body, "status"); | ||
| const summary = readStringField(endpoint.body, "summary"); | ||
|
|
||
| return status === "degraded" || summary === "degraded"; | ||
| } | ||
|
|
||
| function describeEndpointStatus(endpoint: OpsEndpointSnapshot): string { | ||
| if (!endpoint.ok) { | ||
| return "unavailable"; | ||
| } | ||
|
|
||
| const status = readStringField(endpoint.body, "status"); | ||
| const summary = readStringField(endpoint.body, "summary"); | ||
|
|
||
| if (status) { | ||
| return status; | ||
| } | ||
|
|
||
| if (summary) { | ||
| return summary; | ||
| } | ||
|
|
||
| if (endpoint.name === "metrics") { | ||
| return "available"; | ||
| } | ||
|
|
||
| return "ok"; | ||
| } | ||
|
|
||
| function readStringField(value: unknown, key: string): string | undefined { | ||
| if (!isRecord(value)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const field = value[key]; | ||
| return typeof field === "string" ? field : undefined; | ||
| } | ||
|
|
||
| function isRecord(value: unknown): value is Record<string, unknown> { | ||
| return typeof value === "object" && value !== null; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.