palantir / witchcraft-rust-server

A highly opinionated Rust embedded application server for RESTy APIs
Apache License 2.0
4 stars 7 forks source link

Support websocket servers #198

Open TheKeveloper opened 1 month ago

TheKeveloper commented 1 month ago

Witchcraft rust doesn't currently support setting up websockets. We should add in some basic support for creating websockets. I don't think we need to be super opinionated about the websocket support, and we could probably get away with an interface that is like

pub fn websocket(template: &'static str, handler: WebsocketHandler) {
   ... 
}

trait WebsocketHandler {
   pub fn handle(WebSocketConnection websocket);
}

Where WebSocketConnection has a read and write message stream, as well as methods for closing the connection.

It doesn't seem like this would be too difficult to accomplish. We could probably just leverage some existing websocket library like https://docs.rs/tokio-tungstenite/latest/tokio_tungstenite/ and there's some rough guidance on how to handle this with hyper: https://seanmonstar.com/blog/better-http-upgrades-with-hyper/

sfackler commented 1 month ago

I think this should probably be implementable today without any witchcraft-rust changes using Hyper's built-in upgrade support and tokio-tungstenite.

The upgrade support in Hyper has changed since that blog post was written - it's handled via this module: https://docs.rs/hyper/latest/hyper/upgrade/index.html.

I think it'd definitely make sense to add a crate to integrate websockets into witchcraft-server in a more first-class way though.