-
Notifications
You must be signed in to change notification settings - Fork 0
feat: API monitoring #49
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,7 +10,11 @@ import { | |
| RawReplyDefaultExpression, | ||
| RawRequestDefaultExpression, | ||
| RawServerDefault, | ||
| FastifyReply, | ||
| FastifyRequest, | ||
| RouteOptions, | ||
| } from "fastify"; | ||
| import fastifyMetrics from "fastify-metrics"; | ||
| import * as path from "path"; | ||
| import { fileURLToPath } from "url"; | ||
|
|
||
|
|
@@ -21,6 +25,8 @@ export type AppOptions = { | |
| // Place your custom options for app below here. | ||
| // MongoDB URI (Optional) | ||
| // mongoUri: string; | ||
| lokiHost?: string; | ||
| prometheusKey?: string; | ||
| } & FastifyServerOptions & | ||
| Partial<AutoloadPluginOptions> & | ||
| AuthPluginOptions; | ||
|
|
@@ -66,9 +72,49 @@ const options: AppOptions = { | |
| // mongoUri: getOption("MONGO_URI")!, | ||
| authDiscoveryURL: getOption("AUTH_DISCOVERY_URL")!, | ||
| authClientID: getOption("AUTH_CLIENT_ID")!, | ||
| lokiHost: getOption("LOKI_HOST", false), | ||
| prometheusKey: getOption("PROMETHEUS_KEY", false), | ||
| authSkip: getBooleanOption("AUTH_SKIP", false), | ||
| }; | ||
|
|
||
| if (options.lokiHost) { | ||
| const lokiTransport = { | ||
| target: "pino-loki", | ||
| options: { | ||
| batching: true, | ||
| interval: 5, // Logs are sent every 5 seconds, default. | ||
| host: options.lokiHost, | ||
| labels: { application: packageJson.name }, | ||
| }, | ||
| }; | ||
|
|
||
| const existingLogger = options.logger; | ||
|
|
||
| if (existingLogger && typeof existingLogger === "object") { | ||
| const loggerOptions = existingLogger as { transport?: unknown }; | ||
| const existingTransport = loggerOptions.transport; | ||
|
|
||
| let mergedTransport: unknown; | ||
| if (Array.isArray(existingTransport)) { | ||
| mergedTransport = [...existingTransport, lokiTransport]; | ||
| } else if (existingTransport) { | ||
| mergedTransport = [existingTransport, lokiTransport]; | ||
| } else { | ||
| mergedTransport = lokiTransport; | ||
| } | ||
|
|
||
| options.logger = { | ||
| ...(existingLogger as object), | ||
| transport: mergedTransport, | ||
| } as Exclude<FastifyServerOptions["logger"], boolean | undefined>; | ||
| } else { | ||
| options.logger = { | ||
| level: "info", | ||
| transport: lokiTransport, | ||
| }; | ||
| } | ||
|
Comment on lines
+93
to
+115
|
||
| } | ||
|
Comment on lines
+80
to
+116
|
||
|
|
||
| // Support Typebox | ||
| export type FastifyTypebox = FastifyInstance< | ||
| RawServerDefault, | ||
|
|
@@ -93,6 +139,29 @@ const app: FastifyPluginAsync<AppOptions> = async ( | |
| origin: "*", | ||
| }); | ||
|
|
||
| // Register Metrics | ||
| const metricsEndpoint: RouteOptions | string | null = opts.prometheusKey | ||
wylited marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ? { | ||
| url: "/metrics", | ||
| method: "GET", | ||
| handler: async () => {}, // Overridden by fastify-metrics | ||
| onRequest: async (request: FastifyRequest, reply: FastifyReply) => { | ||
| if ( | ||
| request.headers.authorization !== `Bearer ${opts.prometheusKey}` | ||
| ) { | ||
wylited marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| reply.code(401).send({ status: "error", message: "Unauthorized" }); | ||
| return; | ||
| } | ||
| }, | ||
| } | ||
| : "/metrics"; | ||
|
|
||
| await fastify.register(fastifyMetrics.default, { | ||
| endpoint: metricsEndpoint, | ||
| defaultMetrics: { enabled: true }, | ||
| clearRegisterOnInit: true, | ||
| }); | ||
|
|
||
| // Register Swagger & Swagger UI & Scalar | ||
| await fastify.register(import("@fastify/swagger"), { | ||
| openapi: { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { build } from "../helper.js"; | ||
| import * as assert from "node:assert"; | ||
| import { test } from "node:test"; | ||
|
|
||
| test("metrics route without key", async (t) => { | ||
| const app = await build(t); | ||
|
|
||
| const response = await app.inject({ | ||
| url: "/metrics", | ||
| }); | ||
|
|
||
| assert.equal(response.statusCode, 200); | ||
| }); | ||
wylited marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| test("metrics route with key", async (t) => { | ||
| const app = await build(t, { prometheusKey: "secret" }); | ||
|
|
||
| // Without auth header | ||
| const response = await app.inject({ | ||
| url: "/metrics", | ||
| }); | ||
| assert.equal(response.statusCode, 401); | ||
|
|
||
| // With correct auth header | ||
| const responseAuth = await app.inject({ | ||
| url: "/metrics", | ||
| headers: { | ||
| authorization: "Bearer secret", | ||
| }, | ||
| }); | ||
| assert.equal(responseAuth.statusCode, 200); | ||
wylited marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // With incorrect auth header | ||
| const responseBadAuth = await app.inject({ | ||
| url: "/metrics", | ||
| headers: { | ||
| authorization: "Bearer wrong", | ||
| }, | ||
| }); | ||
| assert.equal(responseBadAuth.statusCode, 401); | ||
| }); | ||
Uh oh!
There was an error while loading. Please reload this page.