-
Notifications
You must be signed in to change notification settings - Fork 18
feat: add basic api metric (detecting api client versions) #1102
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| import "@/instrumentation.js"; | ||
|
|
||
| import { env } from "@/config.js"; | ||
| import { app } from "@/server.js"; | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { env } from "@/config.js"; | ||
| import { metrics } from "@opentelemetry/api"; | ||
| import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http"; | ||
| import { Resource } from "@opentelemetry/resources"; | ||
| import { | ||
| MeterProvider, | ||
| PeriodicExportingMetricReader, | ||
| } from "@opentelemetry/sdk-metrics"; | ||
|
|
||
| import { logger } from "@ctrlplane/logger"; | ||
|
|
||
| const stripTrailingSlash = (s: string) => s.replace(/\/$/, ""); | ||
| const appendMetricsPath = (base: string) => | ||
| `${stripTrailingSlash(base)}/v1/metrics`; | ||
|
|
||
| const metricsUrl = | ||
| env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ?? | ||
| (env.OTEL_EXPORTER_OTLP_ENDPOINT && | ||
| appendMetricsPath(env.OTEL_EXPORTER_OTLP_ENDPOINT)); | ||
|
|
||
| if (metricsUrl) { | ||
| const meterProvider = new MeterProvider({ | ||
| resource: new Resource({ "service.name": env.OTEL_SERVICE_NAME }), | ||
| readers: [ | ||
| new PeriodicExportingMetricReader({ | ||
| exporter: new OTLPMetricExporter({ url: metricsUrl }), | ||
| exportIntervalMillis: 30_000, | ||
| }), | ||
| ], | ||
| }); | ||
|
|
||
| metrics.setGlobalMeterProvider(meterProvider); | ||
|
|
||
| for (const signal of ["SIGINT", "SIGTERM"] as const) { | ||
| process.on(signal, () => { | ||
| meterProvider | ||
| .shutdown() | ||
| .catch((err) => | ||
| logger.error("meterProvider.shutdown error", { err }), | ||
| ); | ||
| }); | ||
| } | ||
|
|
||
| logger.info(`OTel metrics enabled (endpoint: ${metricsUrl})`); | ||
| } else { | ||
| logger.info( | ||
| "OTel metrics disabled (set OTEL_EXPORTER_OTLP_ENDPOINT or OTEL_EXPORTER_OTLP_METRICS_ENDPOINT to enable)", | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import type { Counter } from "@opentelemetry/api"; | ||
| import type { Request, RequestHandler } from "express"; | ||
| import { metrics } from "@opentelemetry/api"; | ||
|
|
||
| // Clients in this set are tagged with their version (e.g. `ctrlc/1.2.3`); | ||
| // everyone else is tagged with just the client name to keep cardinality bounded. | ||
| const VERSIONED_CLIENT_ALLOWLIST = new Set(["ctrlc"]); | ||
|
|
||
| const BROWSER_MATCHERS: Array<{ test: (ua: string) => boolean; name: string }> = | ||
| [ | ||
| // Order matters: Edge / Opera UAs include "Chrome/" too, so they go first. | ||
| { test: (ua) => ua.includes("Edg/") || ua.includes("Edge/"), name: "Edge" }, | ||
| { | ||
| test: (ua) => ua.includes("OPR/") || ua.includes("Opera/"), | ||
| name: "Opera", | ||
| }, | ||
| { test: (ua) => ua.includes("Chrome/"), name: "Chrome" }, | ||
| { test: (ua) => ua.includes("Firefox/"), name: "Firefox" }, | ||
| // Safari last: every WebKit-based browser includes "Safari/" in its UA. | ||
| { | ||
| test: (ua) => ua.startsWith("Mozilla/") && ua.includes("Safari/"), | ||
| name: "Safari", | ||
| }, | ||
| ]; | ||
|
|
||
| export const simplifyUserAgent = ( | ||
| userAgent: string | string[] | undefined | null, | ||
| ): string => { | ||
| const ua = Array.isArray(userAgent) ? userAgent[0] : userAgent; | ||
| if (!ua || ua.trim() === "") return "unknown"; | ||
| const trimmed = ua.trim(); | ||
|
|
||
| for (const { test, name } of BROWSER_MATCHERS) { | ||
| if (test(trimmed)) return name; | ||
| } | ||
|
|
||
| // Generic "Mozilla/..." UA we don't recognize — still a browser-shape. | ||
| if (trimmed.startsWith("Mozilla/")) return "browser-other"; | ||
|
|
||
| // Non-browser clients usually look like "name/version ..." — take the first | ||
| // product token, then split name/version. | ||
| const [rawName, version] = trimmed.split(/\s+/, 1)[0]!.split("/", 2); | ||
| const name = rawName?.toLowerCase(); | ||
| if (!name || !/^[a-z][a-z0-9._-]{0,63}$/.test(name)) return "other"; | ||
| return VERSIONED_CLIENT_ALLOWLIST.has(name) && version | ||
| ? `${name}/${version}` | ||
| : name; | ||
| }; | ||
|
|
||
| const resolveRouteTemplate = (req: Request): string => { | ||
| const template = req.route?.path; | ||
| if (template == null) return "unmatched"; | ||
| return `${req.baseUrl}${typeof template === "string" ? template : String(template)}`; | ||
| }; | ||
|
|
||
| let counter: Counter | null = null; | ||
| const getCounter = (): Counter => { | ||
| if (counter) return counter; | ||
| counter = metrics | ||
| .getMeter("ctrlplane-api") | ||
| .createCounter("http.server.requests_by_client", { | ||
| description: | ||
| "Number of HTTP requests received, labeled by simplified client (User-Agent)", | ||
| }); | ||
| return counter; | ||
| }; | ||
|
dacbd marked this conversation as resolved.
|
||
|
|
||
| export const metricsMiddleware: RequestHandler = (req, res, next) => { | ||
| res.on("finish", () => { | ||
| getCounter().add(1, { | ||
| client: simplifyUserAgent(req.headers["user-agent"]), | ||
| method: req.method, | ||
| status_code: String(res.statusCode), | ||
| route: resolveRouteTemplate(req), | ||
| }); | ||
| }); | ||
| next(); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,9 @@ | ||
| import baseConfig from "@ctrlplane/eslint-config/base"; | ||
|
|
||
| /** @type {import('typescript-eslint').Config} */ | ||
| export default []; | ||
| export default [ | ||
| { | ||
| ignores: ["dist/**", "node_modules/**", "src/schema.ts"], | ||
| }, | ||
| ...baseConfig, | ||
| ]; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unvalidated
versionstring will cause metric-label cardinality explosion.The raw version substring is passed directly to the OTel counter label for allowlisted clients:
Any client sending
User-Agent: ctrlc/<UUID>,ctrlc/<unix-timestamp>, or any high-cardinality string will generate a unique metric label combination per request. Most time-series backends (Prometheus, Thanos, Victoria Metrics) have hard cardinality limits; exceeding them causes OOM crashes or label truncation silently.Validate
versionagainst a bounded pattern (e.g. semver-like) before using it as a label:🛡️ Proposed fix
🤖 Prompt for AI Agents