import { Counter, Gauge, Histogram } from "prom-client"; import type { MetricsRegistry } from "./registry.js"; /** * Latency-histogram buckets in seconds. The spread covers 5ms - 10s, which is * the realistic range for both HTTP requests (top of bucket: timeout / 504) * and queue jobs (top of bucket: slow exports). Keep them in sync across the * api + worker + web registries so Grafana panels can mix them. */ export const HISTOGRAM_BUCKETS_SECONDS: readonly number[] = [ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, ] as const; export type LatencyHistogramOptions = { name: string; help: string; labelNames: readonly string[]; buckets?: readonly number[]; }; export type DefaultMetrics = { httpRequestsTotal: Counter<"method" | "route" | "status">; httpRequestDurationSeconds: Histogram<"method" | "route" | "status">; prismaQueryDurationSeconds: Histogram<"model" | "action">; redisCommandDurationSeconds: Histogram<"command">; queueJobsActive: Gauge<"queue">; queueJobsWaiting: Gauge<"queue">; queueJobsEnqueuedTotal: Counter<"queue" | "priority">; queueJobsCompletedTotal: Counter<"queue" | "job_name">; queueJobsFailedTotal: Counter<"queue" | "job_name" | "error_type">; queueJobDurationSeconds: Histogram<"queue" | "job_name">; outboxDispatchTotal: Counter<"event_type" | "status">; webSsrLoaderDurationSeconds: Histogram<"route" | "status">; aiTokensConsumedTotal: Counter<"provider" | "model" | "tenant_bucket">; billingProviderWebhookEventsTotal: Counter<"event_type" | "status">; mailSentTotal: Counter<"provider" | "status">; webhookDeliveryAttemptsTotal: Counter<"status">; csrfTokenRotationTotal: Counter; subscriptionActive: Gauge<"plan_id">; activeTenants: Gauge; activeUsers24h: Gauge; }; /** * Registers the canonical metric set for any service registry. Calling this * twice on the same registry would throw — callers wire the result into a * service-scoped singleton. */ export function createDefaultMetrics(registry: MetricsRegistry): DefaultMetrics { return { httpRequestsTotal: new Counter({ name: "http_requests_total", help: "Total HTTP requests served by this service.", labelNames: ["method", "route", "status"] as const, registers: [registry], }), httpRequestDurationSeconds: new Histogram({ name: "http_request_duration_seconds", help: "HTTP request duration in seconds.", labelNames: ["method", "route", "status"] as const, buckets: [...HISTOGRAM_BUCKETS_SECONDS], registers: [registry], }), prismaQueryDurationSeconds: new Histogram({ name: "prisma_query_duration_seconds", help: "Prisma query duration in seconds.", labelNames: ["model", "action"] as const, buckets: [...HISTOGRAM_BUCKETS_SECONDS], registers: [registry], }), redisCommandDurationSeconds: new Histogram({ name: "redis_command_duration_seconds", help: "Redis command duration in seconds.", labelNames: ["command"] as const, buckets: [...HISTOGRAM_BUCKETS_SECONDS], registers: [registry], }), queueJobsActive: new Gauge({ name: "queue_jobs_active", help: "BullMQ jobs currently being processed per queue.", labelNames: ["queue"] as const, registers: [registry], }), queueJobsWaiting: new Gauge({ name: "queue_jobs_waiting", help: "BullMQ jobs waiting to be processed per queue.", labelNames: ["queue"] as const, registers: [registry], }), queueJobsEnqueuedTotal: new Counter({ name: "queue_jobs_enqueued_total", help: "BullMQ jobs enqueued per queue / priority (critical|high|normal|low|other).", labelNames: ["queue", "priority"] as const, registers: [registry], }), queueJobsCompletedTotal: new Counter({ name: "queue_jobs_completed_total", help: "BullMQ jobs that completed successfully per queue / job_name.", labelNames: ["queue", "job_name"] as const, registers: [registry], }), queueJobsFailedTotal: new Counter({ name: "queue_jobs_failed_total", help: "BullMQ jobs that failed terminally per queue / job_name / error_type.", labelNames: ["queue", "job_name", "error_type"] as const, registers: [registry], }), queueJobDurationSeconds: new Histogram({ name: "queue_job_duration_seconds", help: "BullMQ job duration in seconds.", labelNames: ["queue", "job_name"] as const, buckets: [...HISTOGRAM_BUCKETS_SECONDS], registers: [registry], }), outboxDispatchTotal: new Counter({ name: "outbox_dispatch_total", help: "Transactional outbox dispatch attempts per event_type / status.", labelNames: ["event_type", "status"] as const, registers: [registry], }), webSsrLoaderDurationSeconds: new Histogram({ name: "web_ssr_loader_duration_seconds", help: "React Router SSR loader duration in seconds.", labelNames: ["route", "status"] as const, buckets: [...HISTOGRAM_BUCKETS_SECONDS], registers: [registry], }), aiTokensConsumedTotal: new Counter({ name: "ai_tokens_consumed_total", help: "AI provider tokens consumed. tenant_bucket holds the top-N tenant id or 'other' to cap cardinality.", labelNames: ["provider", "model", "tenant_bucket"] as const, registers: [registry], }), billingProviderWebhookEventsTotal: new Counter({ name: "billing_provider_webhook_events_total", help: "Billing webhook events processed per event_type / status.", labelNames: ["event_type", "status"] as const, registers: [registry], }), mailSentTotal: new Counter({ name: "mail_sent_total", help: "Mail-provider send attempts per provider / status.", labelNames: ["provider", "status"] as const, registers: [registry], }), webhookDeliveryAttemptsTotal: new Counter({ name: "webhook_delivery_attempts_total", help: "Outbound webhook delivery attempts per status (success / retry / dlq).", labelNames: ["status"] as const, registers: [registry], }), csrfTokenRotationTotal: new Counter({ name: "csrf_token_rotation_total", help: "CSRF token rotations performed.", registers: [registry], }), subscriptionActive: new Gauge({ name: "subscription_active", help: "Active subscriptions per plan_id.", labelNames: ["plan_id"] as const, registers: [registry], }), activeTenants: new Gauge({ name: "active_tenants", help: "Total active (non-deleted) tenants.", registers: [registry], }), activeUsers24h: new Gauge({ name: "active_users_24h", help: "Unique users that signed in within the last 24 hours.", registers: [registry], }), }; }