Converting between two streams

I am writing some code which receives HTTP requests over WebSockets and connects them to a warp based web server.

With tokio_tungsten I can get a WebSocket connection which I would like to connect to warp's Server::serve_incoming function.

I need to put something in the middle to handle the Messages produced by the WebSocket connection and convert them to something similar to a TcpStream that warp can handle, then the reverse to send the responses back to the WebSocket. What's the best way to implement something like this?

If the websocket connection gives you a futures::Stream of messages, you should be able to map() them to convert the messages into another form so they can be sent to warp as requests.

You won't be able to pass it to Server::serve_incoming() though, because that expects something like a socket, and a Message (a plain old data type) isn't something you can turn into a socket/TCP stream (an OS-backed resource).

Maybe you could turn each Message into a warp::test::RequestBuilder then call the reply() method with your filter to execute the server logic directly?

That's a great idea, I gave it a go but unfortunately RequestBuilder only handles a known number of headers: because of the borrow checker I can't iterate through a list of headers and add them to the request.

RequestBuilder::header consumes self, but it also returns self, so it can work in a loop like this:

let mut r = warp::test::request();
for (k, v) in [("asdf", 1234), ("qwer", 5678)] {
    r = r.header(k, v);
}
1 Like

That works nicely, but I have a filter that returns server-sent events and the RequestBuilder::reply() never returns in that case (which makes sense as the sending event stream isn't closed). Any other ideas?