tokio-tungstenite icon indicating copy to clipboard operation
tokio-tungstenite copied to clipboard

Async Callback (for usage with `accept_hdr_async`)

Open cameronpickham opened this issue 3 years ago • 6 comments

Is there progress on supporting asynchronous callbacks in methods like accept_hdr_async? It is a common pattern to make asynchronous requests to external authentication providers from within this callback to determine if a connection should be accepted or rejected.

cameronpickham avatar Mar 17 '21 19:03 cameronpickham

Not supported yet (currently it calls a function from tungstenite-rs to implement the callback which is not "async-aware"). But we could eventually add this support in tokio-tungstenite.

daniel-abramov avatar Mar 18 '21 10:03 daniel-abramov

Ok, thank you for the response. Are features like this part of the short/mid-term roadmap for this project?

cameronpickham avatar Mar 18 '21 17:03 cameronpickham

Currently not planned, but if someone submits a PR, we would be glad to review and merge it.

daniel-abramov avatar Mar 18 '21 18:03 daniel-abramov

fyi, this was also brought up here https://github.com/sdroege/async-tungstenite/issues/70

i'm having trouble with an alternative since i need data from the request to do the desired io

databasedav avatar Jun 30 '21 04:06 databasedav

could it at least for now be possible that the callback is called inside tokio::task::spawn_blocking? Im trying blocking_lock an async mutex inside the callback but despite the callback being synchronous (non async) i assume the surrounding context of wherever the callbacks on_request is called in accept_hdr_async is async and thats why im getting a runtime panic "Cannot start a runtime from within a runtime".

Directory avatar Aug 15 '22 03:08 Directory

The thing is that the callback logic is implemented inside tungstenite-rs (the base crate), we're just calling it here from Tokio. We could potentially call spawn_blocking() from this function, but this arguably won't have the desired effect, since the handshake would also then be spawned blocked, so probably it won't change anything semantically.

What we should do instead is to make tungstenite-rs more "basic" in a sense that it should provide all WebSocket logic without adding any coupling with Read + Write or calling sync callbacks, so that we could create a nice async callback based thing here on tokio-tungstenite level. Unfortunately, no-one seem to have gotten closer to it.

In your particular case, won't a regular Mutex work to get the desired effect? (I understand that it would be a big inelegant kludge though)

daniel-abramov avatar Aug 15 '22 17:08 daniel-abramov