Graceful Shutdown¶
Graceful shutdown in ClashRS is not only about exiting cleanly on Ctrl+C or SIGTERM. The same machinery drives:
- Hot configuration reloads (
PUT /configsvia the REST API), where old listeners, TUN devices, DNS servers, and (when controller settings change) the API server must stop and release their ports/routes before replacements bind. - Provider updates, where dynamically loaded inbound listeners and file watchers are stopped when removed or replaced.
- Embedded & FFI lifecycles (
start_scaffold_instanceandclash_shutdowninclash-ffi), where multiple test instances or mobile VPN extensions must tear down cleanly without terminating the host process.
ClashRS standardizes cooperative cancellation around tokio_util::sync::CancellationToken.
The Three-Phase Shutdown Model¶
Every long-running subsystem should follow three explicit phases:
1. Signal ──► cancel_token.cancel()
2. Drain ──► await task JoinHandle(s) (with a bounded timeout if needed)
3. Cleanup ──► release OS resources (routes, WFP policies, IPC sockets, locks)
Skipping phase 2 (returning immediately after calling cancel()) is a frequent source of flaky reloads and EADDRINUSE errors, because the old listener socket or TUN interface may still be open when the new configuration starts.
CancellationToken Hierarchy¶
CancellationToken supports parent–child trees via child_token():
- Cancelling a parent token automatically cancels all descendants.
- Cancelling a child token affects only that subsystem and its children, leaving the rest of the process running.
In clash-lib/src/lib.rs, start_with_overrides creates or receives a root shutdown_token and derives child tokens for subsystems:
shutdown_token (cancelled by Ctrl+C, clash_lib::shutdown(), or caller)
├── api_runner_token (cancelled on process exit OR controller config reload)
├── reload_token (child for replacement ApiRunner instances)
└── components_token (per-RuntimeComponents generation during hot reload)
├── inbound_manager_token
└── dns_listener_token
Use drop_guard() on Early-Exit Ownership Paths
If a task or guard struct owns a CancellationToken that must always be cancelled when the owner exits (including on ? early returns or panics), store let _guard = token.clone().drop_guard();. Dropping the guard calls cancel() automatically.
How ClashRS Components Shut Down¶
1. Entry Points (clash-lib/src/lib.rs & clash-ffi)¶
ClashRS exposes two lifecycle styles:
-
Process-global (
start_scaffold/start_scaffold_with_overrides): Registers the rootCancellationTokenin the staticSHUTDOWN_TOKENregistry soclash_lib::shutdown()(and FFIclash_shutdown()) can cancel it from another thread.start_with_overrideswaits on: -
Instance-scoped (
start_scaffold_instance): Returns(std::thread::JoinHandle<()>, CancellationToken)without touching the global registry. Prefer this in integration tests and multi-instance embedding so instances never interfere with each other.
2. The Runner Trait¶
Background services implement clash_lib::runner::Runner (clash-lib/src/runner.rs):
pub trait Runner: Send + Sync {
/// Start running the runner in background.
fn run_async(&self);
/// Signal the runner to shutdown.
fn shutdown(&self);
/// Wait for the runner to finish.
fn join(&self) -> BoxFuture<'_, Result<(), crate::Error>>;
}
Compare how ApiRunner (clash-lib/src/app/api/runner.rs) implements the full signal-and-join lifecycle:
// Inside run_async():
let result = tokio::select! {
Some(result) = futures::future::OptionFuture::from(tcp_fut) => result,
Some(result) = futures::future::OptionFuture::from(ipc_fut) => result,
_ = cancellation_token.cancelled() => {
info!("API server closed");
Ok(())
}
};
// Store `JoinHandle` in `self.task_handle`.
// On shutdown & join:
fn shutdown(&self) {
info!("Shutting down API server");
self.cancellation_token.cancel();
}
fn join(&self) -> BoxFuture<'_, Result<(), crate::Error>> {
Box::pin(async move {
let handle = self.task_handle.lock().unwrap().take();
if let Some(h) = handle {
let _ = h.await;
}
Ok(())
})
}
When PUT /configs changes controller settings, lib.rs calls api_runner.shutdown(); let _ = api_runner.join().await; before starting the new ApiRunner, guaranteeing the previous TCP listener or Unix/Named-Pipe IPC endpoint has stopped.
3. Ordered OS Resource Teardown (TunRunner)¶
clash-lib/src/proxy/tun/runner.rs illustrates why waiting for the task before cleanup is essential:
async fn stop_running(&self, running: &mut Option<RunningTun>) {
if let Some(RunningTun { cancel, task }) = running.take() {
cancel.cancel();
let _ = task.await;
if let Err(e) = routes::maybe_routes_clean_up(&self.cfg) {
error!("failed to clean up routes: {e}");
}
}
}
Notice the strict ordering:
cancel.cancel()exits thetokio::select!insiderun(...), dropping the TUN device handle, netstack loops, and Windows WFP_policyguard owned by the task.task.awaitwaits until the task has actually dropped those handles.routes::maybe_routes_clean_upremoves OS routing table entries only after the packet loops have stopped.
4. Bounded Best-Effort Close on Data-Plane Sessions¶
Not every peer closes cleanly on demand. When closing an active proxy stream or UDP session, give protocol-level teardown (such as TLS close_notify or TCP FIN) a short, bounded timeout so a black-holed peer cannot stall shutdown forever.
For example, clash-lib/src/app/dispatcher/dispatcher_impl.rs closes the inbound receiver immediately so new packets reconnect right away, and gives the outbound sink a 1-second timeout to send its closing frame:
drop(remote_forwarder);
tokio::spawn(async move {
let _ = tokio::time::timeout(Duration::from_secs(1), remote_w.close()).await;
});
Common Pitfalls to Avoid¶
Empty join() Implementations
If a Runner::join() returns Ok(()) immediately without awaiting its spawned task(s)—as some legacy runners still do—callers cannot tell when sockets have actually been closed. New runners (and refactors of existing ones) should store their JoinHandle or JoinSet and await completion in join().
Prefer Cooperative Cancellation Over Blind abort()
Calling JoinHandle::abort() drops a task at its next .await point without running explicit post-loop cleanup code. Use CancellationToken as the primary shutdown signal so loops can break cleanly, flush or close handles, and exit normally. Reserve abort() (or AbortOnDropHandle) for:
- Purely reactive tasks whose
Dropimplementation already performs all required cleanup. - A fallback after a graceful shutdown timeout expires.
- Unlinked tokens during reload: In
start_with_overrides, verify that newly createdRuntimeComponentsderive their token from the activeshutdown_token(or are explicitly stopped whenstart_with_overridesexits) so process shutdown does not leave background watchers or listeners alive. - Non-async blockers: Never block a Tokio worker thread with long synchronous I/O or
std::thread::sleepin a shutdown-sensitive task; cancelled tokens will never be polled until the blocking call returns. - Forgetting
Fetcher/ watcher tasks: Background tasks holding OS handles (such asnotifyfile watchers inproviders/fetcher.rs) must select oncancel_token.cancelled()and drop the watcher on exit.
Review Checklist¶
- [ ] Every new long-lived loop accepts a
CancellationToken(derived viachild_token()from its parent scope) and breaks cleanly whencancelled()resolves. - [ ]
shutdown()+join()waits for listeners and tasks to release ports, IPC paths, and OS routes before returning. - [ ] Protocol close / drain steps use a bounded timeout so an unresponsive remote peer cannot hang shutdown or config reload.
- [ ] Process shutdown and hot-reload paths both leave zero leaked tasks or stale OS routes (verify with a targeted start-and-stop or reload test).