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

Undefined behaviour due to error handing in xrpc-server #2204

Open
matthieusieben opened this issue Feb 21, 2024 · 0 comments
Open

Undefined behaviour due to error handing in xrpc-server #2204

matthieusieben opened this issue Feb 21, 2024 · 0 comments

Comments

@matthieusieben
Copy link
Contributor

The following lines in xrpc-server can cause an undefined behavior:

if (input?.body instanceof Readable) {
// If the body stream errors at any time, abort the request
input.body.once('error', next)
}

The reason is that the next() function might get called multiple times. These lines also prevent the handler to catch and handle the error itself:

server.method(
  'io.example.blobTest',
  async (ctx: { input?: xrpcServer.HandlerInput }) => {
    if (!(ctx.input?.body instanceof Readable))
      throw new Error('Input not readable')

    try {
      const buffers: Buffer[] = []
      for await (const data of ctx.input.body) {
        buffers.push(data)
      }
      return {
        encoding: 'json',
        body: { data: Buffer.concat(buffers).toString('base64') },
      }
    } catch (er) {
      return {
        encoding: 'json',
        body: { error: er.message },
      }
    }
  }
)

In the previous example, an error in the body stream can either result in the handler's payload being sent ({ error: 'some message' }) OR result in Express' finalhandler sending a generir error response. Whichever occurs first depends on the order of async tasks which is not predictable by the user of xrpc-server.

IMHO xrpc-server should avoid this behavior and require that the handler handles any potential error when the body is a stream. For convenience, RouteOpts could be used in order to describe how the payload should be processed (e.g. allow defining acceptable content types).

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

1 participant