swindon-rs / tk-http

Full featured HTTP and Websockets library for rust/tokio
Apache License 2.0
136 stars 10 forks source link

Sending websocket `Packet`s of shared data #30

Closed walfie closed 7 years ago

walfie commented 7 years ago

I'm trying to use BufferedDispatcher::new_with_websockets to handle HTTP and websocket requests on the server side. It works great, however I have a lot of cases where I need to send the same thing to multiple websocket sinks (e.g., broadcast the same message to all users).

I couldn't find a good way to do this without having to clone the data for every user, since everything accepts a Packet, which owns its data in a Vec<u8> or String (although encoding a Packet only requires a reference to the bytes).

Is there a recommended way to do this without cloning?


On a related note, I'm guessing the reason Packet is using String/Vec is so that it's compatible with futures/tokio, which requires 'static in most places. However if Packet were defined as:

enum Packet<T> where T: AsRef<[u8]> {
  // ...
  Binary(T),
  // ...
}

it would allow Packet to still "own" the data, and allow end-users to use something like the bytes crate to share the data internally (or define their own Arc<Vec<u8>> wrapper that can dereference to an array of bytes, etc). This would probably make the API more annoying to use though, for what might be an uncommon use case.

I could try implementing a Codec in my own code, but since most of the logic is the same, it looks like I would have to copy/paste a lot of the private stuff from BufferedCodec and websocket::ServerCodec / websocket::zero_copy.

tailhook commented 7 years ago

Well, I think writing codecs is perfectly fine. They have quite a bit of boilerplate, but not hard to write either.

But if you make a pull request, and it doesn't look very invasive I don't mind applying it. The only issue is that I don't want to release a backward-incompatible release without a good reason, so this issue might lay around until we need another breaking change.

walfie commented 7 years ago

Ah, ok. I'll take a look to see if I can find a nice way to do it with a codec first. I'll close this issue for now, and reopen later if necessary.