feat: add handleUpgradeRequest route option
At gadget we make extensive use of @fastify/websocket. One use case is a websocket proxy that connects vite hmr clients in the browser to a developers serverless development environment. The vite client has a ping protocol with the following semantics:
- If the vite dev server listening then the hmr endpoint should upgrade the connection and immediately close
- If the vite dev server isn't listening yet the endpoint should reject the connection https://github.com/vitejs/vite/blob/main/packages/vite/src/node/server/ws.ts#L258-L263
We need a way to handle upgrade events in our proxy layer and not upgrade connections until we know that the upstream vite will also upgrade the connection. To do this I have introduced a route level option handleUpgradeRequest that allows for a route by route customization of how the upgrade event should be handled.
handleUpgradeRequest is a function that takes the incoming FastifyRequest, the source socket and the head buffer; to continue through to the normal wsHandler the use should return a promise that resolves to a connected websocket; to reject the connection the user can either throw an error (optionally with a statusCode) or write directly to/teardown the source socket
Checklist
- [x] run
npm run test && npm run benchmark --if-present - [x] tests and/or benchmarks are included
- [x] documentation is changed or added
- [x] commit message and code follows the Developer's Certification of Origin and the Code of conduct
@mcollina any thoughts on this?