feat: add webhook /metrics endpoint with Prometheus output (5.2)
This commit is contained in:
1 parent
98d2557c32
commit
5bc1486be6
5 files changed
+126
-8
No files matched your search
@@ -0,0 +1,59 @@
|
|||||||
|
/**
|
||||||
|
* Webhook 运行期指标:纯内存累加器 + Prometheus 文本格式序列化。
|
||||||
|
* 无外部依赖;webhook 服务通过 /metrics 端点暴露。
|
||||||
|
*/
|
||||||
|
|
||||||
|
type CounterKey = string;
|
||||||
|
|
||||||
|
export class MetricsRegistry {
|
||||||
|
private readonly counters = new Map<CounterKey, number>();
|
||||||
|
private readonly durations: number[] = [];
|
||||||
|
private readonly startedAt = Date.now();
|
||||||
|
|
||||||
|
inc(name: string, labels: Record<string, string> = {}, 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, string>): 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");
|
||||||
|
}
|
||||||
+16
-1
@@ -5,6 +5,7 @@ import { config } from "../config.js";
|
|||||||
import { createGitHubAppInstallationCredentials } from "../github/client.js";
|
import { createGitHubAppInstallationCredentials } from "../github/client.js";
|
||||||
import { logger } from "../logger.js";
|
import { logger } from "../logger.js";
|
||||||
import { parseWebhookMentionEvent, processWebhookMention } from "./processor.js";
|
import { parseWebhookMentionEvent, processWebhookMention } from "./processor.js";
|
||||||
|
import { MetricsRegistry } from "./metrics.js";
|
||||||
|
|
||||||
const MAX_WEBHOOK_BODY_BYTES = 2 * 1024 * 1024;
|
const MAX_WEBHOOK_BODY_BYTES = 2 * 1024 * 1024;
|
||||||
const DELIVERY_RETENTION_MS = 24 * 60 * 60 * 1000;
|
const DELIVERY_RETENTION_MS = 24 * 60 * 60 * 1000;
|
||||||
@@ -42,7 +43,10 @@ export function verifyGitHubWebhookSignature(
|
|||||||
return supplied.length === expected.length && timingSafeEqual(supplied, expected);
|
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) {
|
if (!options.secret) {
|
||||||
throw new Error("WEBHOOK_SECRET is required to create the GitHub webhook server.");
|
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 });
|
writeJson(response, 200, { ok: true, webhook: true });
|
||||||
return;
|
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) {
|
if (request.method !== "POST" || pathname !== webhookPath) {
|
||||||
response.setHeader("allow", "GET, POST");
|
response.setHeader("allow", "GET, POST");
|
||||||
writeJson(response, 404, { error: "Not found." });
|
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 eventName = singleHeader(request.headers["x-github-event"]);
|
||||||
const signature = singleHeader(request.headers["x-hub-signature-256"]);
|
const signature = singleHeader(request.headers["x-hub-signature-256"]);
|
||||||
if (!deliveryId || !eventName || !signature) {
|
if (!deliveryId || !eventName || !signature) {
|
||||||
|
metrics.inc("webhook_requests_total", { result: "missing_headers" });
|
||||||
writeJson(response, 400, { error: "Missing GitHub webhook headers." });
|
writeJson(response, 400, { error: "Missing GitHub webhook headers." });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -83,10 +93,12 @@ export function createWebhookServer(options: WebhookServerOptions): http.Server
|
|||||||
{ error, deliveryId, eventName },
|
{ error, deliveryId, eventName },
|
||||||
"Rejected oversized or unreadable GitHub webhook body."
|
"Rejected oversized or unreadable GitHub webhook body."
|
||||||
);
|
);
|
||||||
|
metrics.inc("webhook_requests_total", { result: "too_large" });
|
||||||
writeJson(response, 413, { error: "Webhook payload is too large." });
|
writeJson(response, 413, { error: "Webhook payload is too large." });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!verifyGitHubWebhookSignature(body, signature, options.secret)) {
|
if (!verifyGitHubWebhookSignature(body, signature, options.secret)) {
|
||||||
|
metrics.inc("webhook_requests_total", { result: "bad_signature" });
|
||||||
writeJson(response, 401, { error: "Invalid webhook signature." });
|
writeJson(response, 401, { error: "Invalid webhook signature." });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -104,14 +116,17 @@ export function createWebhookServer(options: WebhookServerOptions): http.Server
|
|||||||
handleDelivery(eventName, payload, deliveryId)
|
handleDelivery(eventName, payload, deliveryId)
|
||||||
);
|
);
|
||||||
if (!accepted) {
|
if (!accepted) {
|
||||||
|
metrics.inc("webhook_deliveries_total", { result: "duplicate" });
|
||||||
writeJson(response, 202, { ok: true, duplicate: true });
|
writeJson(response, 202, { ok: true, duplicate: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
metrics.inc("webhook_deliveries_total", { event: eventName, result: "accepted" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
{ error, deliveryId, eventName },
|
{ error, deliveryId, eventName },
|
||||||
"Webhook queue is full; asking GitHub to retry."
|
"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." });
|
writeJson(response, 503, { error: "Webhook queue is temporarily full." });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import test from "node:test";
|
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", () => {
|
test("final confirmation parses a clean JSON body", () => {
|
||||||
const parsed = parseFinalConfirmation(
|
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", () => {
|
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/);
|
assert.match(timeout, /No commit was pushed/);
|
||||||
const identity = describeConflictResolutionFailure(new Error("committer identity unknown"));
|
const identity = describeConflictResolutionFailure(new Error("committer identity unknown"));
|
||||||
assert.match(identity, /committer identity/);
|
assert.match(identity, /committer identity/);
|
||||||
const push = describeConflictResolutionFailure(
|
const push = describeConflictResolutionFailure(new Error("! [rejected] ... (stale info)"));
|
||||||
new Error("! [rejected] ... (stale info)")
|
|
||||||
);
|
|
||||||
assert.match(push, /force lease rejected|Run \/conflict again/);
|
assert.match(push, /force lease rejected|Run \/conflict again/);
|
||||||
const generic = describeConflictResolutionFailure(new Error("something odd"));
|
const generic = describeConflictResolutionFailure(new Error("something odd"));
|
||||||
assert.match(generic, /could not safely complete/);
|
assert.match(generic, /could not safely complete/);
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import test from "node:test";
|
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";
|
import { config } from "../src/config.js";
|
||||||
|
|
||||||
const originalEffort = config.gooseThinkingEffort;
|
const originalEffort = config.gooseThinkingEffort;
|
||||||
@@ -38,7 +42,7 @@ test("extractGooseFinalText strips a surrounding markdown fence", () => {
|
|||||||
messages: [
|
messages: [
|
||||||
{
|
{
|
||||||
role: "assistant",
|
role: "assistant",
|
||||||
content: [{ type: "text", text: "```json\n{\"ok\":true}\n```" }]
|
content: [{ type: "text", text: '```json\n{"ok":true}\n```' }]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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/);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user