From 5bc1486be6e703497d2c8e46e11d584d6131ed34 Mon Sep 17 00:00:00 2001 From: wdawdwa <2864460459@qq.com> Date: Sat, 22 Aug 2026 18:44:37 +0800 Subject: [PATCH] feat: add webhook /metrics endpoint with Prometheus output (5.2) --- src/webhook/metrics.ts | 59 ++++++++++++++++++++++++++++++ src/webhook/server.ts | 17 ++++++++- test/conflict-confirmation.test.ts | 13 ++++--- test/goose-agent-env.test.ts | 8 +++- test/webhook-metrics.test.ts | 37 +++++++++++++++++++ 5 files changed, 126 insertions(+), 8 deletions(-) create mode 100644 src/webhook/metrics.ts create mode 100644 test/webhook-metrics.test.ts diff --git a/src/webhook/metrics.ts b/src/webhook/metrics.ts new file mode 100644 index 0000000..bfa3852 --- /dev/null +++ b/src/webhook/metrics.ts @@ -0,0 +1,59 @@ +/** + * Webhook 运行期指标:纯内存累加器 + Prometheus 文本格式序列化。 + * 无外部依赖;webhook 服务通过 /metrics 端点暴露。 + */ + +type CounterKey = string; + +export class MetricsRegistry { + private readonly counters = new Map(); + private readonly durations: number[] = []; + private readonly startedAt = Date.now(); + + inc(name: string, labels: Record = {}, value = 1): void { + const key = serializeMetricName(name, labels); + this.counters.set(key, (this.counters.get(key) ?? 0) + value); + } + + observeDuration(name: string, ms: number): void { + this.durations.push(ms); + this.inc(`${name}_count`); + this.inc(`${name}_sum_ms`, {}, ms); + } + + snapshotPrometheus(): string { + const lines: string[] = []; + lines.push(`# TYPE ghbot_uptime_seconds gauge`); + lines.push(`ghbot_uptime_seconds ${Math.round((Date.now() - this.startedAt) / 1000)}`); + for (const [key, value] of [...this.counters.entries()].sort(([a], [b]) => + a.localeCompare(b) + )) { + lines.push(`${key} ${value}`); + } + if (this.durations.length > 0) { + const sorted = [...this.durations].sort((a, b) => a - b); + const p50 = sorted[Math.floor(sorted.length * 0.5)] ?? 0; + const p95 = sorted[Math.floor(sorted.length * 0.95)] ?? 0; + lines.push(`# TYPE ghbot_duration_ms summary`); + lines.push(`ghbot_duration_ms{quantile="0.5"} ${p50}`); + lines.push(`ghbot_duration_ms{quantile="0.95"} ${p95}`); + } + return `${lines.join("\n")}\n`; + } +} + +function serializeMetricName(name: string, labels: Record): string { + const entries = Object.entries(labels); + if (entries.length === 0) { + return `ghbot_${name}`; + } + const labelString = entries + .sort(([a], [b]) => a.localeCompare(b)) + .map(([key, value]) => `${key}="${escapeLabelValue(value)}"`) + .join(","); + return `ghbot_${name}{${labelString}}`; +} + +function escapeLabelValue(value: string): string { + return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n"); +} diff --git a/src/webhook/server.ts b/src/webhook/server.ts index 7d4ff84..fc7703e 100644 --- a/src/webhook/server.ts +++ b/src/webhook/server.ts @@ -5,6 +5,7 @@ import { config } from "../config.js"; import { createGitHubAppInstallationCredentials } from "../github/client.js"; import { logger } from "../logger.js"; import { parseWebhookMentionEvent, processWebhookMention } from "./processor.js"; +import { MetricsRegistry } from "./metrics.js"; const MAX_WEBHOOK_BODY_BYTES = 2 * 1024 * 1024; const DELIVERY_RETENTION_MS = 24 * 60 * 60 * 1000; @@ -42,7 +43,10 @@ export function verifyGitHubWebhookSignature( return supplied.length === expected.length && timingSafeEqual(supplied, expected); } -export function createWebhookServer(options: WebhookServerOptions): http.Server { +export function createWebhookServer( + options: WebhookServerOptions, + metrics: MetricsRegistry = new MetricsRegistry() +): http.Server { if (!options.secret) { throw new Error("WEBHOOK_SECRET is required to create the GitHub webhook server."); } @@ -61,6 +65,11 @@ export function createWebhookServer(options: WebhookServerOptions): http.Server writeJson(response, 200, { ok: true, webhook: true }); return; } + if (request.method === "GET" && pathname === "/metrics") { + response.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" }); + response.end(metrics.snapshotPrometheus()); + return; + } if (request.method !== "POST" || pathname !== webhookPath) { response.setHeader("allow", "GET, POST"); writeJson(response, 404, { error: "Not found." }); @@ -71,6 +80,7 @@ export function createWebhookServer(options: WebhookServerOptions): http.Server const eventName = singleHeader(request.headers["x-github-event"]); const signature = singleHeader(request.headers["x-hub-signature-256"]); if (!deliveryId || !eventName || !signature) { + metrics.inc("webhook_requests_total", { result: "missing_headers" }); writeJson(response, 400, { error: "Missing GitHub webhook headers." }); return; } @@ -83,10 +93,12 @@ export function createWebhookServer(options: WebhookServerOptions): http.Server { error, deliveryId, eventName }, "Rejected oversized or unreadable GitHub webhook body." ); + metrics.inc("webhook_requests_total", { result: "too_large" }); writeJson(response, 413, { error: "Webhook payload is too large." }); return; } if (!verifyGitHubWebhookSignature(body, signature, options.secret)) { + metrics.inc("webhook_requests_total", { result: "bad_signature" }); writeJson(response, 401, { error: "Invalid webhook signature." }); return; } @@ -104,14 +116,17 @@ export function createWebhookServer(options: WebhookServerOptions): http.Server handleDelivery(eventName, payload, deliveryId) ); if (!accepted) { + metrics.inc("webhook_deliveries_total", { result: "duplicate" }); writeJson(response, 202, { ok: true, duplicate: true }); return; } + metrics.inc("webhook_deliveries_total", { event: eventName, result: "accepted" }); } catch (error) { logger.warn( { error, deliveryId, eventName }, "Webhook queue is full; asking GitHub to retry." ); + metrics.inc("webhook_deliveries_total", { result: "queue_full" }); writeJson(response, 503, { error: "Webhook queue is temporarily full." }); return; } diff --git a/test/conflict-confirmation.test.ts b/test/conflict-confirmation.test.ts index 6a4c857..e29123a 100644 --- a/test/conflict-confirmation.test.ts +++ b/test/conflict-confirmation.test.ts @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { parseFinalConfirmation, describeConflictResolutionFailure } from "../src/review/conflictResolver.js"; +import { + parseFinalConfirmation, + describeConflictResolutionFailure +} from "../src/review/conflictResolver.js"; test("final confirmation parses a clean JSON body", () => { const parsed = parseFinalConfirmation( @@ -31,13 +34,13 @@ test("final confirmation rejects structurally invalid output", () => { }); test("failure descriptions are actionable and never expose raw command output", () => { - const timeout = describeConflictResolutionFailure(new Error("initial goose conflict-editing pass timed out.")); + const timeout = describeConflictResolutionFailure( + new Error("initial goose conflict-editing pass timed out.") + ); assert.match(timeout, /No commit was pushed/); const identity = describeConflictResolutionFailure(new Error("committer identity unknown")); assert.match(identity, /committer identity/); - const push = describeConflictResolutionFailure( - new Error("! [rejected] ... (stale info)") - ); + const push = describeConflictResolutionFailure(new Error("! [rejected] ... (stale info)")); assert.match(push, /force lease rejected|Run \/conflict again/); const generic = describeConflictResolutionFailure(new Error("something odd")); assert.match(generic, /could not safely complete/); diff --git a/test/goose-agent-env.test.ts b/test/goose-agent-env.test.ts index ecfaa9d..cda0b3f 100644 --- a/test/goose-agent-env.test.ts +++ b/test/goose-agent-env.test.ts @@ -1,6 +1,10 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { buildGooseAgentEnvironment, extractGooseFinalText, redactProcessArgs } from "../src/ai/gooseCli.js"; +import { + buildGooseAgentEnvironment, + extractGooseFinalText, + redactProcessArgs +} from "../src/ai/gooseCli.js"; import { config } from "../src/config.js"; const originalEffort = config.gooseThinkingEffort; @@ -38,7 +42,7 @@ test("extractGooseFinalText strips a surrounding markdown fence", () => { messages: [ { role: "assistant", - content: [{ type: "text", text: "```json\n{\"ok\":true}\n```" }] + content: [{ type: "text", text: '```json\n{"ok":true}\n```' }] } ] }); diff --git a/test/webhook-metrics.test.ts b/test/webhook-metrics.test.ts new file mode 100644 index 0000000..128aa01 --- /dev/null +++ b/test/webhook-metrics.test.ts @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { MetricsRegistry } from "../src/webhook/metrics.js"; + +test("counters accumulate and serialize with sorted stable output", () => { + const registry = new MetricsRegistry(); + registry.inc("reviews_total", { outcome: "pass" }); + registry.inc("reviews_total", { outcome: "pass" }); + registry.inc("reviews_total", { outcome: "block" }); + const output = registry.snapshotPrometheus(); + assert.match(output, /ghbot_reviews_total\{outcome="pass"\} 2/); + assert.match(output, /ghbot_reviews_total\{outcome="block"\} 1/); + assert.match(output, /ghbot_uptime_seconds \d+/); +}); + +test("label values are escaped for the Prometheus text format", () => { + const registry = new MetricsRegistry(); + registry.inc("events_total", { repo: 'acme "x"\n' }); + const output = registry.snapshotPrometheus(); + assert.ok(output.includes('ghbot_events_total{repo="acme \\"x\\"\\n"} 1')); +}); + +test("durations produce count, sum, and quantiles", () => { + const registry = new MetricsRegistry(); + registry.observeDuration("review_duration_ms", 100); + registry.observeDuration("review_duration_ms", 300); + const output = registry.snapshotPrometheus(); + assert.match(output, /ghbot_review_duration_ms_count 2/); + assert.match(output, /ghbot_review_duration_ms_sum_ms 400/); + assert.match(output, /ghbot_duration_ms\{quantile="0.5"\} \d+/); + assert.match(output, /ghbot_duration_ms\{quantile="0.95"\} \d+/); +}); + +test("an empty registry still emits uptime", () => { + const output = new MetricsRegistry().snapshotPrometheus(); + assert.match(output, /ghbot_uptime_seconds/); +});