feat: add webhook /metrics endpoint with Prometheus output (5.2)

This commit is contained in:
wdawdwa committed 2026-08-22 18:44:37 +08:00
1 parent 98d2557c32
commit 5bc1486be6
5 files changed
+126 -8

No files matched your search

+59
View File
@@ -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
View File
@@ -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;
}