Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

task_hygiene.rs

Helper script for rust-tokio-async-service-builder · 108 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references8 scripts
scripts/task_hygiene.rs
//! Find task and channel patterns that lose errors, memory or data.
//!   TK009 detached-spawn               tokio::spawn(..); with the JoinHandle dropped
//!   TK010 unbounded-channel            mpsc::unbounded_channel(): no backpressure
//!   TK016 select-loop-not-cancel-safe  select! in a loop racing read_exact/read_line/write_all or a fresh sleep(..)
//!   TK019 spawn-without-move           tokio::spawn(async { .. }) / .spawn(async { .. }) without `move`
//!
//! Build: rustc -O --edition 2021 scripts/task_hygiene.rs -o /tmp/task_hygiene
//! Usage: task_hygiene <FILES|DIRS|-> [--json] [--strict] [--select IDS] [--ignore IDS]

mod async_ctx;
mod cli;
mod rsparse;

use async_ctx::{fn_at, macro_spans};
use cli::{Finding, Rule};
use rsparse::{close_of, items, word_positions, Src};

const RULES: &[Rule] = &[
    Rule { id: "TK009", name: "detached-spawn", severity: "medium",
           why: "a dropped JoinHandle loses the task's panic and result, and shutdown cannot wait for it",
           fix: "keep it: JoinSet / TaskTracker (tokio-util) or store the JoinHandle and await it; log errors inside the task" },
    Rule { id: "TK010", name: "unbounded-channel", severity: "medium",
           why: "an unbounded channel has no backpressure: a slow consumer turns into unbounded memory growth",
           fix: "mpsc::channel(capacity) and send().await (or try_send for drop-on-full)" },
    Rule { id: "TK016", name: "select-loop-not-cancel-safe", severity: "high",
           why: "select! drops the losing futures: read_exact/read_line/write_all lose partial data, a fresh sleep() never fires",
           fix: "pin the long-lived future outside the loop (let sleep = sleep(d); tokio::pin!(sleep); &mut sleep), use cancel-safe reads (read/recv) or a framed codec" },
    Rule { id: "TK019", name: "spawn-without-move", severity: "low",
           why: "a spawned future must be 'static: without `move` it borrows locals (E0373) or only compiles by accident",
           fix: "tokio::spawn(async move { .. }) with owned or Arc data" },
];

const USAGE: &str = "usage: task_hygiene <FILES|DIRS|-> [options]

Report detached tokio::spawn calls (TK009), unbounded channels (TK010), select! loops racing
futures that are not cancel safe (TK016) and spawned async blocks without `move` (TK019).";

const NOT_CANCEL_SAFE: &[&str] = &["read_exact(", "read_line(", "read_to_end(", "read_to_string(", "write_all(", "sleep("];

fn main() {
    let opts = cli::parse(USAGE, RULES, &[]);
    let inputs = opts.inputs();
    let mut findings = Vec::new();
    for input in &inputs {
        let src = Src::new(input.text.clone());
        let code = &src.code;
        let (fns, _, _) = items(&src);
        let mut found = Vec::new();
        let mut push = |off: usize, id: &'static str, what: String| {
            let place = fn_at(&src, &fns, off).map_or(String::new(), |f| format!(" in fn {}", f.name));
            found.push(Finding { file: input.name.clone(), line: src.line_of(off), id, msg: format!("{what}{place}"), fix: String::new() });
        };

        for (off, _) in code.match_indices("tokio::spawn(") {
            let before = code[..off].trim_end();
            let statement_start = before.is_empty() || before.ends_with([';', '{', '}']);
            let open = off + "tokio::spawn".len();
            let after = code[close_of(code, open)..].trim_start();
            if statement_start && after.starts_with(';') {
                push(off, "TK009", "`tokio::spawn(..);` drops its JoinHandle".into());
            }
        }
        for (off, _) in code.match_indices("unbounded_channel") {
            if code[off..].trim_start_matches("unbounded_channel").trim_start().starts_with(['(', ':']) {
                push(off, "TK010", "`unbounded_channel()` has no backpressure".into());
            }
        }
        // select! inside loop / while / for bodies
        let loops: Vec<(usize, usize)> = ["loop", "while", "for"]
            .iter()
            .flat_map(|kw| word_positions(code, kw))
            .filter_map(|i| code[i..].find('{').map(|b| (i + b, close_of(code, i + b))))
            .collect();
        for (a, b) in macro_spans(code, "select!") {
            if !loops.iter().any(|&(la, lb)| la < a && b <= lb) {
                continue;
            }
            let body = &code[a..b];
            let racing: Vec<&str> = NOT_CANCEL_SAFE
                .iter()
                .filter(|p| body.match_indices(*p).any(|(i, _)| !body[..i].ends_with("&mut ")))
                .map(|p| p.trim_end_matches('('))
                .collect();
            if !racing.is_empty() {
                push(a, "TK016", format!("select! in a loop races {} (recreated or partially done each iteration)", racing.join(", ")));
            }
        }
        for pat in ["tokio::spawn(", ".spawn("] {
            for (off, _) in code.match_indices(pat) {
                let arg = code[off + pat.len()..].trim_start();
                if arg.starts_with("async") && arg[5..].trim_start().starts_with('{') {
                    push(off, "TK019", format!("`{}async {{ .. }})` without move", pat));
                }
            }
        }
        let on = |id: &str| RULES.iter().any(|r| r.id == id && opts.enabled(r));
        findings.extend(found.into_iter().filter(|f| on(f.id) && !src.noqa(f.line, f.id)));
    }
    let findings: Vec<Finding> = findings
        .into_iter()
        .map(|mut f| {
            f.fix = RULES.iter().find(|r| r.id == f.id).map_or(String::new(), |r| r.fix.to_string());
            f
        })
        .collect();
    cli::finish(&opts, RULES, findings, inputs.len(), "task")
}
More in Rust

rust-borrow-checker-error-explainer

Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.

rust-cargo-workspace-designer

Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.

rust-error-handling-thiserror-anyhow-designer

Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.

rust-lifetime-annotation-advisor

Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.

rust-trait-design-reviewer

Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.

rust-unsafe-block-auditor

Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.