-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[flake8-async] Implement blocking-http-call-httpx (ASYNC212)
#20091
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
7b628b5
[flake8-async] Implement `blocking-http-call-httpx` (ASYNC212)
amyreese 6686f8f
Check for annotations/assignments and report violations on method calls
amyreese 15b39c2
Example of catching a global client
amyreese 4e0882c
Address code style nits, improve lint message and include method name
amyreese File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
75 changes: 75 additions & 0 deletions
75
crates/ruff_linter/resources/test/fixtures/flake8_async/ASYNC212.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| from typing import Optional | ||
|
|
||
| import httpx | ||
|
|
||
|
|
||
| def foo(): | ||
| client = httpx.Client() | ||
| client.close() # Ok | ||
| client.delete() # Ok | ||
| client.get() # Ok | ||
| client.head() # Ok | ||
| client.options() # Ok | ||
| client.patch() # Ok | ||
| client.post() # Ok | ||
| client.put() # Ok | ||
| client.request() # Ok | ||
| client.send() # Ok | ||
| client.stream() # Ok | ||
|
|
||
| client.anything() # Ok | ||
| client.build_request() # Ok | ||
| client.is_closed # Ok | ||
|
|
||
|
|
||
| async def foo(): | ||
| client = httpx.Client() | ||
| client.close() # ASYNC212 | ||
| client.delete() # ASYNC212 | ||
| client.get() # ASYNC212 | ||
| client.head() # ASYNC212 | ||
| client.options() # ASYNC212 | ||
| client.patch() # ASYNC212 | ||
| client.post() # ASYNC212 | ||
| client.put() # ASYNC212 | ||
| client.request() # ASYNC212 | ||
| client.send() # ASYNC212 | ||
| client.stream() # ASYNC212 | ||
|
|
||
| client.anything() # Ok | ||
| client.build_request() # Ok | ||
| client.is_closed # Ok | ||
|
|
||
|
|
||
| async def foo(client: httpx.Client): | ||
| client.request() # ASYNC212 | ||
| client.anything() # Ok | ||
|
|
||
|
|
||
| async def foo(client: httpx.Client | None): | ||
| client.request() # ASYNC212 | ||
| client.anything() # Ok | ||
|
|
||
|
|
||
| async def foo(client: Optional[httpx.Client]): | ||
| client.request() # ASYNC212 | ||
| client.anything() # Ok | ||
|
|
||
|
|
||
| async def foo(): | ||
| client: httpx.Client = ... | ||
| client.request() # ASYNC212 | ||
| client.anything() # Ok | ||
|
|
||
|
|
||
| global_client = httpx.Client() | ||
|
|
||
|
|
||
| async def foo(): | ||
| global_client.request() # ASYNC212 | ||
| global_client.anything() # Ok | ||
|
|
||
|
|
||
| async def foo(): | ||
| async with httpx.AsyncClient() as client: | ||
| await client.get() # Ok | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
145 changes: 145 additions & 0 deletions
145
crates/ruff_linter/src/rules/flake8_async/rules/blocking_http_call_httpx.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| use ruff_python_ast::{self as ast, Expr, ExprCall}; | ||
|
|
||
| use ruff_macros::{ViolationMetadata, derive_message_formats}; | ||
| use ruff_python_semantic::analyze::typing::{TypeChecker, check_type, traverse_union_and_optional}; | ||
| use ruff_text_size::Ranged; | ||
|
|
||
| use crate::Violation; | ||
| use crate::checkers::ast::Checker; | ||
|
|
||
| /// ## What it does | ||
| /// Checks that async functions do not use blocking httpx clients. | ||
| /// | ||
| /// ## Why is this bad? | ||
| /// Blocking an async function via a blocking HTTP call will block the entire | ||
| /// event loop, preventing it from executing other tasks while waiting for the | ||
| /// HTTP response, negating the benefits of asynchronous programming. | ||
| /// | ||
| /// Instead of using the blocking `httpx` client, use the asynchronous client. | ||
| /// | ||
| /// ## Example | ||
| /// ```python | ||
| /// import httpx | ||
| /// | ||
| /// | ||
| /// async def fetch(): | ||
| /// client = httpx.Client() | ||
| /// response = client.get(...) | ||
| /// ``` | ||
| /// | ||
| /// Use instead: | ||
| /// ```python | ||
| /// import httpx | ||
| /// | ||
| /// | ||
| /// async def fetch(): | ||
| /// async with httpx.AsyncClient() as client: | ||
| /// response = await client.get(...) | ||
| /// ``` | ||
| #[derive(ViolationMetadata)] | ||
| pub(crate) struct BlockingHttpCallHttpxInAsyncFunction { | ||
| name: String, | ||
| call: String, | ||
| } | ||
|
|
||
| impl Violation for BlockingHttpCallHttpxInAsyncFunction { | ||
| #[derive_message_formats] | ||
| fn message(&self) -> String { | ||
| format!( | ||
| "Blocking httpx method {name}.{call}() in async context, use httpx.AsyncClient", | ||
| name = self.name, | ||
| call = self.call, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| struct HttpxClientChecker; | ||
|
|
||
| impl TypeChecker for HttpxClientChecker { | ||
| fn match_annotation( | ||
| annotation: &ruff_python_ast::Expr, | ||
| semantic: &ruff_python_semantic::SemanticModel, | ||
| ) -> bool { | ||
| // match base annotation directly | ||
| if semantic | ||
| .resolve_qualified_name(annotation) | ||
| .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["httpx", "Client"])) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| // otherwise traverse any union or optional annotation | ||
| let mut found = false; | ||
| traverse_union_and_optional( | ||
amyreese marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| &mut |inner_expr, _| { | ||
| if semantic | ||
| .resolve_qualified_name(inner_expr) | ||
| .is_some_and(|qualified_name| { | ||
| matches!(qualified_name.segments(), ["httpx", "Client"]) | ||
| }) | ||
| { | ||
| found = true; | ||
| } | ||
| }, | ||
| semantic, | ||
| annotation, | ||
| ); | ||
| found | ||
| } | ||
|
|
||
| fn match_initializer( | ||
| initializer: &ruff_python_ast::Expr, | ||
| semantic: &ruff_python_semantic::SemanticModel, | ||
| ) -> bool { | ||
| let Expr::Call(ExprCall { func, .. }) = initializer else { | ||
| return false; | ||
| }; | ||
|
|
||
| semantic | ||
| .resolve_qualified_name(func) | ||
| .is_some_and(|qualified_name| matches!(qualified_name.segments(), ["httpx", "Client"])) | ||
| } | ||
| } | ||
|
|
||
| /// ASYNC212 | ||
| pub(crate) fn blocking_http_call_httpx(checker: &Checker, call: &ExprCall) { | ||
| let semantic = checker.semantic(); | ||
| if !semantic.in_async_context() { | ||
| return; | ||
| } | ||
|
|
||
| let Some(ast::ExprAttribute { value, attr, .. }) = call.func.as_attribute_expr() else { | ||
| return; | ||
| }; | ||
| let Some(name) = value.as_name_expr() else { | ||
| return; | ||
| }; | ||
| let Some(binding) = semantic.only_binding(name).map(|id| semantic.binding(id)) else { | ||
| return; | ||
| }; | ||
|
|
||
| if check_type::<HttpxClientChecker>(binding, semantic) { | ||
| if matches!( | ||
| attr.id.as_str(), | ||
| "close" | ||
| | "delete" | ||
| | "get" | ||
| | "head" | ||
| | "options" | ||
| | "patch" | ||
| | "post" | ||
| | "put" | ||
| | "request" | ||
| | "send" | ||
| | "stream" | ||
| ) { | ||
| checker.report_diagnostic( | ||
| BlockingHttpCallHttpxInAsyncFunction { | ||
| name: name.id.to_string(), | ||
| call: attr.id.to_string(), | ||
| }, | ||
| call.func.range(), | ||
| ); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This one still isn't caught, presumably because the TypeChecker bits only capture annotations at the function level?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this should work. I played around a bit with the PTH210 rule, which uses the
PathlibPathChecker, and it will detect both module-level and function-level bindings like this:I'm wondering if the union traversal might be disrupting this check.