tungstenite-rs
tungstenite-rs copied to clipboard
Support custom behavior for some handshake error cases
I found that currently the server side of tungstenite will directly drop the connection when encountering some handshake failures (the stream is moved into accept() so it will be dropped when an error occurs).
However I have a requirement to return a valid http response when some websocket related headers are missing (such as the connection upgrade header). Currently tungstenite seems unable to do this.
I wonder if some new accept functions can be added to tungstenite to support this?
In fact, Tungstenite is able to do this without any changes. The clue is the stream itself. It should be just Read + White, and Tungstenite doesn't care about implementation details. Use a wrapper around some kind of stream reference (Arc?) which is safe to drop while keeping the original.
We could let Tungstenite return the failed stream inside of HandshakeError::Failure, but it would be a breaking change.
Ahh thank you, I can get your point.
It is a good idea to have something like WebSocketStream<SomeArcStreamWrapper<S>>, but to avoid a more compilcated type and also some runtime overhead, I'm wondering if I can convert it back into WebSocketStream<S> after a successful handshake. 🤔
It is possible but quite fragile. There is from_raw_socket() so that you can construct WebSocketStream again. But it should be done immediately after doing handshake. It will break if there is some ongoing WebSocket traffic.
Alternatively you can perform the handshake by using MidHandshake directly. There is some freedom of specifying handshake results.
Probably we should add a impl From<WebSocket<Q>> for WebSocket<S> where S: From<Q> to do it safely.
Thank you for your help! I have a new idea to maintain the current API and behavior while also allowing for handling invalid requests.
Let me create a pull request to provide more details.