trpc icon indicating copy to clipboard operation
trpc copied to clipboard

feat: add keep alive (ping/pong) implementation to websocket handler

Open nohum opened this issue 3 years ago โ€ข 0 comments

Describe the feature you'd like to request

We are using long-living websocket connections and would like to keep them alive using websocket ping-pongs.

Describe the solution you'd like to see

I already have a working solution on my side, so it is just about the incorporation I guess.

However, I would modify the applyWSSHandler and add the ping/pong code there.

https://github.com/trpc/trpc/blob/81d85defcd58ea0d8941f1677028d0ed4250d398/packages/server/src/adapters/ws.ts#L113-L113

In the WSSHandlerOptions I would introduce a property keepAliveMs?: number. If unset, I would default to a keep-alive timeout of e.g. 20000ms. This means that package upgrades on developer-side would automatically introduce this as an opt-in (is this regarded as a breaking change?). Additionally, you could also set the property to 0 to disable keep alive. One issue I am unsure about here is on how to expose this best to the various adapters (e.g. I am using the fastifyTRPCPlugin) which is the main reason why I would go for an opt-out to be honest.

Within the applyWSSHandler I would (if enabled) listen for new connections and set a interval for pings (set by keepAliveMs) and also a timeout to wait for pongs (this timeout would also be keepAliveMs). If no pong is received, the connection is terminated.

Describe alternate solutions

An alternate solution would be to implement keep alive frames within TRPC as operations itself.

However, native websocket ping/pongs are supported out-of-the box by websocket implementations as part of control frames (see RFC6455) and would not pollute the messages that are sent and received by TRPC itself.

Additional information

This issue should only be the implementation of the ping/pong part on the server.

As written in the RFC (https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2), client implemenations are required to respond to pings with a pong, so the implementation of the ping-part on the server using native websocket pings should be sufficient.

๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Contributing

  • [X] ๐Ÿ™‹โ€โ™‚๏ธ Yes, I'd be down to file a PR implementing this feature!

nohum avatar Jan 05 '23 08:01 nohum