sdroege / async-tungstenite

Async binding for Tungstenite, the Lightweight stream-based WebSocket implementation
MIT License
395 stars 61 forks source link

Error "Task was cancelled" When trying to connect to a websocket #24

Closed Texlo-Dev closed 4 years ago

Texlo-Dev commented 4 years ago

I've been stuck with the following error for the past few days and I am not sure as to how I should overcome it.

thread 'tokio-runtime-worker' panicked at 'Failed to create shard: Tungstenite(Io(Custom { kind: Other, error: "task was cancelled" }))', gateway/src/manager.rs:141:49
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

I've managed to trace it back to the following piece of code:

let (wstream, _) = async_tungstenite::tokio::connect_async_with_config(ws,Some(WebSocketConfig {
    max_message_size: Some(usize::max_value()),
    max_frame_size: Some(usize::max_value()),
    ..Default::default()
})).await?;

ws is defined as &str.

I am extremely confused as to what is going on here. The WS URL is valid. It's a discord gateway for a discord library. Any ideas as to why this IO Custom error is being thrown here?

sdroege commented 4 years ago

Can you provide a testcase to reproduce it?

Texlo-Dev commented 4 years ago

My repository is https://github.com/spec-tacles/rustacles

To test it for yourself, you can run DISCORD_TOKEN=NTM1NTc5NTY1NDg2MTEyNzk2.XpB0Kw.TTFFbeGR7Jen7G_vkJCyPzEHBVA SHARD_COUNT=2 RUST_LOG=debug cargo run --example sharder

I'll reset the token once you've tested it.

sdroege commented 4 years ago

What fails here is this line https://github.com/sdroege/async-tungstenite/blob/70c77160a99b0e7ef0e014d63a4a0946da6817ec/src/tokio.rs#L239

It's trying to connect to gateway.discord.gg:443 and tokio just returns that error to us before we can even start the TLS (let alone the WebSocket) handshake. You should be able to reproduce the same with just doing exactly the same from your application code, e.g. directly calling tokio::net::TcpStream::connect(("gateway.discord.gg", 443)).await.unwrap() in Shard::connect().

This seems to be a general problem in how your application uses tokio. This error would happen if the tokio Task you're running in was somehow cancelled.