From e718339d93e2f60b6df55330aafb2d9536820ce4 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Fri, 15 Sep 2023 10:34:33 +0200 Subject: Add request_duration_seconds histogram --- src/index.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/index.ts b/src/index.ts index a377985..ee092f2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,7 +34,7 @@ collectDefaultMetrics({ FLY_REGION: Bun.env.FLY_REGION, }, }); -const counters = { +const metrics = { requestsByStatus: new prom.Counter({ name: "homestead_requests_by_status", help: "Number of requests by status code", @@ -45,6 +45,11 @@ const counters = { help: "Number of requests by path", labelNames: ["path"], }), + requestDuration: new prom.Histogram({ + name: "homestead_request_duration_seconds", + help: "Request duration in seconds", + labelNames: ["path"], + }), }; let files = new Map(); @@ -102,7 +107,7 @@ async function serveFile( extraHeaders: Record = {}, ): Promise { if (file && (await file.handle.exists())) { - counters.requestsByStatus.inc({ status_code: statusCode }); + metrics.requestsByStatus.inc({ status_code: statusCode }); return new Response(file.handle, { headers: { "last-modified": file.mtime.toUTCString(), @@ -112,7 +117,7 @@ async function serveFile( status: statusCode, }); } else { - counters.requestsByStatus.inc({ status_code: 404 }); + metrics.requestsByStatus.inc({ status_code: 404 }); // TODO return encoded return serveFile(files.get("/404.html"), 404); } @@ -151,17 +156,18 @@ console.info( const server = Bun.serve({ fetch: async function (request) { + const pathname = new URL(request.url).pathname; + const endTimer = metrics.requestDuration.startTimer({ path: pathname }); try { - const pathname = new URL(request.url).pathname; const file = files.get(pathname); - counters.requestsByPath.inc({ path: pathname }); + metrics.requestsByPath.inc({ path: pathname }); if (file) { if ( parseIfModifiedSinceHeader( request.headers.get("if-modified-since"), ) >= file?.mtime.getTime() ) { - counters.requestsByStatus.inc({ status_code: 304 }); + metrics.requestsByStatus.inc({ status_code: 304 }); return new Response("", { status: 304, headers: defaultHeaders }); } const encodings = (request.headers.get("accept-encoding") || "") @@ -192,9 +198,12 @@ const server = Bun.serve({ } return serveFile(file); } catch (error) { - counters.requestsByStatus.inc({ status_code: 503 }); + metrics.requestsByStatus.inc({ status_code: 503 }); Sentry.captureException(error); return new Response("Something went wrong", { status: 503 }); + } finally { + const seconds = endTimer(); + metrics.requestDuration.observe(seconds); } }, }); -- cgit 1.4.1