Skip to content

'onRequestAbort' and 'request.raw.on("close")' not firing reliably #866

Closed
@TimShilov

Description

@TimShilov

Summary

Hello,
I'm trying to handle cases where the user aborts the request to cancel database queries.
I've looked at:

  1. https://www.fastify.io/docs/latest/Guides/Detecting-When-Clients-Abort/
  2. https://www.fastify.io/docs/latest/Reference/Hooks/#onrequestabort

Both seem to not work reliably (and in my cases, they don't work at all). It seems to have something to do with Content-Type header.

Reproduction code (mostly the copy-paste from documentation).

const fastify = require("fastify");

const sleep = async (time) => {
    return new Promise((resolve) => setTimeout(resolve, time || 1000));
};

const app = fastify({
    logger: {
        transport: {
            target: "pino-pretty",
            options: { translateTime: "HH:MM:ss Z", ignore: "pid,hostname" },
        },
    },
});

app.addHook("onRequestAbort", async (request) => {
    console.log("Aborted!", request.raw.aborted);
});

app.post("/", async (request, reply) => {
    console.log("in handler");
    request.raw.on("close", () => {
        console.log("close");
        if (request.raw.aborted) {
            console.log("request aborted!");
        }
    });
    await sleep(3000);
    reply.code(200).send({ ok: true });
});

const start = async () => {
    try {
        await app.listen({ port: 3000 });
    } catch (error) {
        app.log.error(error);
        process.exit(1);
    }
};

start();

Expected Behavior

When sending any request and aborting it I should see this output:

in handler
close
request aborted!
Aborted! true

Actual Behavior

For this request, all works fine:

curl --request POST --url 'http://localhost:3000/'

When I abort the request I see the expected output.

However, for this request (same thing but with JSON content type and a body) the abort is not caught:

curl --request POST  --url 'http://localhost:3000/' --header 'Content-Type: application/json' --data '{}'

And the output is:

in handler
close

Also, it looks like close is fired right away (before 3-second delay and before me actually canceling the request).

Question

Any idea what could cause that and how can I make it work reliably?

Your Environment

  • node version: v18.15.0
  • fastify version: 4.15.0
  • os: MacOS 13.3.1 (22E261)

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions