Cancellation Safety¶
In asynchronous Rust, cancelling a future means dropping it before it returns Poll::Ready. This happens automatically on every losing branch of tokio::select! and whenever tokio::time::timeout elapses or a task is aborted.
A future is cancellation safe if dropping it mid-execution—and potentially creating a fresh call on the next loop iteration—cannot lose data, corrupt protocol state, or violate invariants.
For Tokio's canonical definition and per-method guarantees, see tokio::select! — Cancellation Safety.
Why It Matters in ClashRS¶
Proxy cores spend most of their time inside long-lived tokio::select! loops:
- Multiplexing local-to-remote and remote-to-local UDP packets (
clash-lib/src/app/dispatcher/dispatcher_impl.rs). - Watching file updates or timer ticks alongside a shutdown token (
clash-lib/src/app/remote_content_manager/providers/fetcher.rs). - Racing listener accept loops against a
CancellationToken(clash-lib/src/app/inbound/manager.rs,clash-lib/src/proxy/tun/runner.rs). - Framing streams over TLS, WebSocket, AnyTLS, Shadowsocks, VMess, or VLESS.
If a non-cancellation-safe future is created inside a loop { tokio::select! { ... } }, any other branch completing first drops that future along with whatever partial bytes or internal state it already consumed.
Quick Reference: Common Tokio & Futures Operations¶
| Operation | Cancellation Safe? | Notes & Safe Alternative |
|---|---|---|
CancellationToken::cancelled() |
Yes | Safe in any select! loop |
tokio::sync::mpsc::Receiver::recv() |
Yes | Either yields an item or leaves it in the channel |
tokio::sync::broadcast::Receiver::recv() |
Yes | Does not advance the cursor until ready |
tokio::sync::watch::Receiver::changed() |
Yes | Re-calling continues waiting for unseen updates |
tokio::sync::oneshot::Receiver |
Yes | Dropping cancels reception cleanly |
tokio::net::TcpListener::accept() |
Yes | Safe to race against shutdown |
tokio::net::UdpSocket::recv_from() |
Yes | One datagram is either read completely or stays queued |
tokio::io::AsyncReadExt::read() / read_buf() |
Yes | Returns 0..=n bytes atomically; does not buffer unread data inside the future |
tokio::time::Interval::tick() |
Yes | State lives on Interval, not on the tick future |
futures::StreamExt::next() |
Depends on stream | Safe only if the underlying Stream is cancellation safe (e.g., mpsc receiver streams, SplitStream over datagrams) |
tokio::io::AsyncReadExt::read_exact() |
No | Already-read prefix bytes are lost when dropped; accumulate into a BytesMut via read_buf() or use tokio_util::codec::Framed |
tokio::io::AsyncWriteExt::write_all() |
No | Partial bytes may already be written to the socket; track write offset outside the select! |
tokio::io::AsyncBufReadExt::read_line() / read_until() |
No | Partial line bytes may be discarded or left inconsistent across cancellations |
tokio::sync::mpsc::Sender::send() |
No | Dropping loses the item or channel fairness; use reserve() / try_send() or tokio_util::sync::PollSender |
futures::SinkExt::send() |
No | Dropping mid-flush can leave buffered items unsent or lose the item |
tokio::time::Sleep recreated each iteration |
Pitfall | Resets the deadline every time another branch fires; pin one Sleep outside the loop |
Holding a Lock Across .await Inside select!
Avoid acquiring an async Mutex / RwLock inside a select! branch future if another branch can cancel it mid-critical-section—and never leave a multi-step state mutation half-finished across an .await point.
Patterns Used in ClashRS¶
1. Keep Only Cancellation-Safe Futures in select! Branches¶
In clash-lib/src/app/remote_content_manager/providers/fetcher.rs, both the file-watch loop and the periodic pull loop keep only cancellation-safe operations (cancel_token.cancelled(), rx.recv(), ticker.tick()) as the branch expressions:
loop {
tokio::select! {
_ = cancel_token.cancelled() => break,
_ = ticker.tick() => {
Fetcher::<U, P>::run_update(
inner.clone(),
vehicle.clone(),
parser.clone(),
on_update.clone(),
&name,
)
.await;
}
}
}
Once ticker.tick() or rx.recv() wins, the handler block runs to completion without racing against cancellation mid-update. If a handler itself can hang on slow network I/O during shutdown, wrap the inner operation with its own timeout or propagate cancel_token down into the I/O call rather than cancelling a partially mutated state structure from the outside.
2. Pin Long-Lived Futures Outside the select!¶
When a future must make progress across multiple wakeups or be resumed after another branch resolves, pin it outside tokio::select! and poll &mut fut.
In clash-lib/src/app/dispatcher/dispatcher_impl.rs (dispatch_datagram), the forwarding future is pinned so that if the caller drops close_sender (rather than sending an explicit close byte), the task awaits the same forwarding future instead of restarting or cancelling it:
let forwarding = self.datagram_session(sess, udp_inbound, None);
let (close_sender, close_receiver) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
tokio::pin!(forwarding);
tokio::select! {
() = &mut forwarding => {},
signal = close_receiver => {
if signal.is_err() {
forwarding.await;
}
}
}
});
The same rule applies to idle timeouts inside a loop: construct let sleep = tokio::time::sleep(timeout); tokio::pin!(sleep); before the loop, poll &mut sleep inside select!, and call sleep.as_mut().reset(Instant::now() + timeout) only when real traffic arrives.
3. Externalize Read/Write Buffers Instead of read_exact / write_all¶
// BUG: if `shutdown.cancelled()` or another branch fires after 1 byte
// has been read from `stream`, those bytes are permanently lost!
loop {
let mut header = [0u8; 4];
tokio::select! {
res = stream.read_exact(&mut header) => {
res?;
handle_frame(header).await?;
}
_ = keepalive.tick() => {
send_ping(&mut writer).await?;
}
}
}
When implementing a framed protocol (such as Shadowsocks, VMess, VLESS, or AnyTLS), prefer tokio_util::codec::Framed / Decoder + Encoder or keep a BytesMut buffer outside the select! loop so partial reads survive cancellation.
4. Backpressure Without Losing Messages (reserve / PollSender)¶
If you need to select between receiving data and waiting for channel capacity:
- With
tokio::sync::mpsc::Sender: awaittx.reserve().await(which is cancellation safe) to obtain aPermit, then synchronously callpermit.send(item)once you have the item. Dropping aPermitreleases the slot without losing any payload. - When implementing
futures::Sinkovermpsc::Sender: usetokio_util::sync::PollSender, as ClashRS does inclash-lib/src/proxy/naive/datagram.rsandclash-lib/src/proxy/tailscale/datagram.rs.PollSendermanages permit reservation insidepoll_readysostart_sendnever blocks or loses packets.
5. Watch Out for select! Handler Blocking¶
In clash-lib/src/app/dispatcher/dispatcher_impl.rs, the UDP NAT relay selects between remote_forwarder.recv() (local → remote) and remote_r.next() (remote → local):
loop {
tokio::select! {
pkt = remote_forwarder.recv() => {
let Some((mut packet, dest)) = pkt else { break };
// ... rewrite address ...
if let Err(err) = remote_w.send(packet).await {
// ...
}
}
pkt = remote_r.next() => {
let Some(mut packet) = pkt else { break };
// ... restore address ...
if let Err(err) = remote_receiver_w.send(packet).await {
break;
}
}
}
}
Both branch heads (recv() and next()) are cancellation safe. Note the trade-off: awaiting remote_w.send(packet).await or remote_receiver_w.send(packet).await inside the branch body is safe against cancellation (nothing cancels it except dropping the whole task), but if one side's sink stalls under backpressure, it pauses polling the opposite direction until the send resolves. When bidirectional progress must stay completely independent under heavy backpressure, split the two directions into separate tasks or bounded select! loops with non-blocking/reserved sends.
Review Checklist¶
Before merging code that uses tokio::select! or tokio::time::timeout:
- [ ] Every future placed directly in a
select!branch inside aloopis verified to be cancellation safe—or is pinned outside the loop and polled by&mut. - [ ] No
read_exact,write_all,read_line, orSinkExt::sendis re-created on each iteration of aselect!loop. - [ ] Any
tokio::time::Sleepused as a timeout inside a loop is pinned outside the loop and reset explicitly. - [ ] Channel sends participating in a
select!usereserve()/try_send()/PollSenderrather than dropping a pendingsend(item). - [ ] State updates across
.awaitpoints preserve valid invariants if the future is dropped at any.await.