Skip to content
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

Do not throw if request is not found #4

Merged
merged 2 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ module.exports = (registry, config = {}) => {

if (ignoreRoute(request, server)) return

const { summaryTimer, histogramTimer } = timers.get(request)
const requestTimers = timers.get(request)
if (!requestTimers) return

const { summaryTimer, histogramTimer } = requestTimers
timers.delete(request)

if (ignore(request, response, server)) return
Expand Down
3 changes: 3 additions & 0 deletions test/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ function createHttpServer (t) {
if (req.url === '/2s') {
await sleep(2000)
}
if (req.url === '/10s') {
await sleep(10000)
}
res.end('Hello World\n')
}
)
Expand Down
30 changes: 30 additions & 0 deletions test/http-metrics.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const assert = require('node:assert/strict')
const { test } = require('node:test')
const { setTimeout: sleep } = require('node:timers/promises')
const { request } = require('undici')
const { Registry } = require('prom-client')
const httpMetrics = require('../index.js')
Expand Down Expand Up @@ -258,3 +259,32 @@ test('should ignore route with a callback', async (t) => {
}
}
})

test('should not throw if request timers are not found', async (t) => {
const serverUrl = createHttpServer(t)

const responsePromise = request(serverUrl + '/10s', {
method: 'GET',
headers: { 'x-ignore': 'true' },
})

// Wait for server to receive the request
await sleep(500)

const registry = new Registry()
httpMetrics(registry, {
ignore: (req) => req.headers['x-ignore'] === 'true',
})

await responsePromise

const metrics = await registry.getMetricsAsJSON()
assert.strictEqual(metrics.length, 2)

const histogramMetric = metrics.find(
(metric) => metric.name === 'http_request_duration_seconds'
)

const histogramValues = histogramMetric.values
assert.strictEqual(histogramValues.length, 0)
})
Loading