Skip to content

Commit

Permalink
fix: prevent duplicate logs
Browse files Browse the repository at this point in the history
  • Loading branch information
fenos committed Sep 30, 2024
1 parent da3ce61 commit b2d52d6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
23 changes: 16 additions & 7 deletions src/http/plugins/log-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,26 @@ export const logRequest = (options: RequestLoggerOptions) =>
fastify.addHook('onRequest', async (req, res) => {

Check warning on line 32 in src/http/plugins/log-request.ts

View workflow job for this annotation

GitHub Actions / Test / OS ubuntu-20.04 / Node 20

'res' is defined but never used
req.startTime = Date.now()

// Request was aborted before the server finishes to return a response
res.raw.once('close', () => {
const aborted = !res.raw.writableFinished
if (aborted) {
req.signals.disconnect.signal.addEventListener(
'abort',
() => {
if (!req.signals.body.signal.aborted && !req.raw.aborted) {
doRequestLog(req, {
excludeUrls: options.excludeUrls,
statusCode: 'ABORTED RES',
responseTime: (Date.now() - req.startTime) / 1000,
})
return
}

doRequestLog(req, {
excludeUrls: options.excludeUrls,
statusCode: 'ABORTED RES',
statusCode: 'ABORTED REQ',
responseTime: (Date.now() - req.startTime) / 1000,
})
}
})
},
{ once: true }
)
})

/**
Expand Down
12 changes: 11 additions & 1 deletion src/http/plugins/signals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ export const signals = fastifyPlugin(
disconnect: new AbortController(),
}

// Client terminated the request before the body was fully sent
req.raw.once('close', () => {
if (req.raw.aborted) {
req.signals.body.abort()

if (!req.signals.disconnect.signal.aborted) {
req.signals.disconnect.abort()
}
}
})

// Client terminated the request before server finished sending the response
res.raw.once('close', () => {
const aborted = !res.raw.writableFinished
Expand All @@ -33,7 +44,6 @@ export const signals = fastifyPlugin(
})
})

// Client terminated the request before the body was fully sent
fastify.addHook('onRequestAbort', async (req) => {
req.signals.body.abort()

Expand Down

0 comments on commit b2d52d6

Please sign in to comment.