Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/ops-status-plane.md
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.
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"@clack/prompts": "^0.9.1",
"@croco/migration-runner": "workspace:*",
"@croco/openapi-spec": "workspace:*",
"@croco/problems-core": "workspace:*",
"@croco/rpc-codegen": "workspace:*",
"citty": "^0.1.6",
"ts-morph": "^24.0.0"
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/bin/croco.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { create } from "../commands/create.js";
import { generate } from "../commands/generate.js";
import { make } from "../commands/make.js";
import { migrate } from "../commands/migrate.js";
import { ops } from "../commands/ops.js";
import { GLOBAL_OPTIONS } from "../commands/options.js";

const main = defineCommand({
Expand All @@ -23,6 +24,7 @@ const main = defineCommand({
codegen,
contracts,
migrate,
ops,
},
});

Expand Down
333 changes: 333 additions & 0 deletions packages/cli/src/commands/ops.ts
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);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

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;
}
16 changes: 16 additions & 0 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,20 @@ export { makeEvent } from "./commands/makeEvent";
export { makeListener } from "./commands/makeListener";
export { makeRepository } from "./commands/makeRepository";
export { migrate } from "./commands/migrate";
export {
formatOpsStatusReport,
getOpsStatusExitCode,
ops,
opsStatus,
runOpsStatus,
} from "./commands/ops";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
export { GLOBAL_OPTIONS } from "./commands/options";

export type {
OpsEndpointName,
OpsEndpointSnapshot,
OpsStatusFetch,
OpsStatusReport,
OpsStatusSummary,
RunOpsStatusOptions,
} from "./commands/ops";
Loading
Loading