Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throwing an error in wsHandler causes the node process to exit #308

Open
2 tasks done
AnzeKop opened this issue Dec 4, 2024 · 1 comment
Open
2 tasks done

Throwing an error in wsHandler causes the node process to exit #308

AnzeKop opened this issue Dec 4, 2024 · 1 comment

Comments

@AnzeKop
Copy link

AnzeKop commented Dec 4, 2024

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.1.0

Plugin version

11.0.01

Node.js version

20

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 20

Description

When throwing an error in the websocket route (in our case this is when an unexpected close happens from the user) the node process seems to exit with status code 1 instead of just abandoning the connection causing the entire app to stop and then leads to unstable restarts when in our case Heroku tries to restart the app.

Example is this.

  ...(apiJob.server?.websocket === true
        ? {
            wsHandler: async (socket, request) => {
              try {
                const wsManager = new WebSocketServerManager(socket);

                const parseResult = apiJob.schema.safeParse(
                  unflattenParams(new URLSearchParams(request.query as any))
                );

                if (!parseResult.success) {
                  socket.close(4422, "Invalid payload structure.");
                  console.error(
                    `Invalid payload structure: ${JSON.stringify(
                      parseResult.error.errors,
                      null,
                      2
                    )}`
                  );
                  return;
                }

                await apiJob.server!.handler(parseResult.data as any, {
                  run: new Run({
                    cache: new KnexCache(),
                  }),
                  hubspotApi: await createClientWithAccessToken(),
                  jobId: request.id,
                  socket: wsManager,
                });
              } catch (error) {
                console.error(`Failed to process request:`, error);
                socket.close(4500, "An unknown error occurred");
              }
            },
          }
        : {}),
// inside the websocket server manager class

    this.socket.on("close", () => {
      this.cleanup();
      if (!this.expectedClose) {
        console.warn("WebSocket connection closed unexpectedly");
        throw new Error("WebSocket connection closed unexpectedly");
      }
    });

Link to code that reproduces the bug

No response

Expected Behavior

Throwing an error inside a socket handler stops any ongoing processes/function executions and just closes the connection.

If there is any better way to stop any ongoing execution I'm happy to hear suggestions

@airhorns
Copy link
Member

airhorns commented Dec 4, 2024

@AnzeKop its tricky for us as maintainers to debug other folks code like this -- if you can put together a minimal reproduction, we can get to the bottom of exactly what the right behaviour of fastify-websocket should be! I'm not quite sure where in the code above the error you're mentioning is being thrown, and/or if it is being thrown in that async context or in a different one. In general, unhandled exceptions or promise rejections teardown the whole process, and it already looks like you have a try/catch around it there, so my guess is your error is actually coming from some other callback outside of that context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants