|
| 1 | +use ruff_diagnostics::{Diagnostic, Violation}; |
| 2 | +use ruff_macros::{derive_message_formats, violation}; |
| 3 | +use ruff_python_ast as ast; |
| 4 | +use ruff_text_size::Ranged; |
| 5 | + |
| 6 | +use crate::checkers::ast::Checker; |
| 7 | + |
| 8 | +/// ## What it does |
| 9 | +/// Checks for `async` functions with a `timeout` argument. |
| 10 | +/// |
| 11 | +/// ## Why is this bad? |
| 12 | +/// Rather than implementing asynchronous timeout behavior manually, prefer |
| 13 | +/// trio's built-in timeout functionality, available as `trio.fail_after`, |
| 14 | +/// `trio.move_on_after`, `trio.fail_at`, and `trio.move_on_at`. |
| 15 | +/// |
| 16 | +/// ## Example |
| 17 | +/// ```python |
| 18 | +/// async def func(): |
| 19 | +/// await long_running_task(timeout=2) |
| 20 | +/// ``` |
| 21 | +/// |
| 22 | +/// Use instead: |
| 23 | +/// ```python |
| 24 | +/// async def func(): |
| 25 | +/// with trio.fail_after(2): |
| 26 | +/// await long_running_task() |
| 27 | +/// ``` |
| 28 | +#[violation] |
| 29 | +pub struct TrioAsyncFunctionWithTimeout; |
| 30 | + |
| 31 | +impl Violation for TrioAsyncFunctionWithTimeout { |
| 32 | + #[derive_message_formats] |
| 33 | + fn message(&self) -> String { |
| 34 | + format!("Prefer `trio.fail_after` and `trio.move_on_after` over manual `async` timeout behavior") |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/// TRIO109 |
| 39 | +pub(crate) fn async_function_with_timeout( |
| 40 | + checker: &mut Checker, |
| 41 | + function_def: &ast::StmtFunctionDef, |
| 42 | +) { |
| 43 | + if !function_def.is_async { |
| 44 | + return; |
| 45 | + } |
| 46 | + let Some(timeout) = function_def.parameters.find("timeout") else { |
| 47 | + return; |
| 48 | + }; |
| 49 | + checker.diagnostics.push(Diagnostic::new( |
| 50 | + TrioAsyncFunctionWithTimeout, |
| 51 | + timeout.range(), |
| 52 | + )); |
| 53 | +} |
0 commit comments