From b2d52d622ea0bb34143b7bbd40ceefdf5e6b9243 Mon Sep 17 00:00:00 2001 From: fenos Date: Mon, 30 Sep 2024 17:57:27 +0200 Subject: [PATCH] fix: prevent duplicate logs --- src/http/plugins/log-request.ts | 23 ++++++++++++++++------- src/http/plugins/signals.ts | 12 +++++++++++- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/http/plugins/log-request.ts b/src/http/plugins/log-request.ts index 15117e89..a7e518df 100644 --- a/src/http/plugins/log-request.ts +++ b/src/http/plugins/log-request.ts @@ -32,17 +32,26 @@ 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) { + 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 } + ) }) /** diff --git a/src/http/plugins/signals.ts b/src/http/plugins/signals.ts index 930474e6..a4734621 100644 --- a/src/http/plugins/signals.ts +++ b/src/http/plugins/signals.ts @@ -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 @@ -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()