From 32ce1e47a004bb14f5e954cede149a67c119a1f6 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 | 20 ++++++++------------ src/http/plugins/signals.ts | 12 +++++++++++- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/http/plugins/log-request.ts b/src/http/plugins/log-request.ts index 15117e89..d01eef01 100644 --- a/src/http/plugins/log-request.ts +++ b/src/http/plugins/log-request.ts @@ -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, + }) }) }) @@ -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, 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()