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 32ce1e4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
20 changes: 8 additions & 12 deletions src/http/plugins/log-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,20 @@ export const logRequest = (options: RequestLoggerOptions) =>
fastify.addHook('onRequest', async (req, res) => {
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) {
if (req.raw.aborted) {
doRequestLog(req, {
excludeUrls: options.excludeUrls,
statusCode: 'ABORTED RES',
statusCode: 'ABORTED REQ',
responseTime: (Date.now() - req.startTime) / 1000,
})
return
}
doRequestLog(req, {
excludeUrls: options.excludeUrls,
statusCode: 'ABORTED RES',
responseTime: (Date.now() - req.startTime) / 1000,
})
})
})

Expand Down Expand Up @@ -73,14 +77,6 @@ export const logRequest = (options: RequestLoggerOptions) =>
}
})

fastify.addHook('onRequestAbort', async (req) => {
doRequestLog(req, {
excludeUrls: options.excludeUrls,
statusCode: 'ABORTED REQ',
responseTime: (Date.now() - req.startTime) / 1000,
})
})

fastify.addHook('onResponse', async (req, reply) => {
doRequestLog(req, {
reply,
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 32ce1e4

Please sign in to comment.