|
| 1 | +use ruff_macros::{ViolationMetadata, derive_message_formats}; |
| 2 | +use ruff_python_ast::{self as ast, Expr, StmtFunctionDef}; |
| 3 | +use ruff_python_semantic::analyze::class::any_qualified_base_class; |
| 4 | +use ruff_python_semantic::{Imported, Modules, ScopeKind, SemanticModel}; |
| 5 | +use ruff_text_size::Ranged; |
| 6 | + |
| 7 | +use crate::Violation; |
| 8 | +use crate::checkers::ast::Checker; |
| 9 | +use crate::rules::airflow::helpers::is_airflow_task; |
| 10 | + |
| 11 | +/// ## What it does |
| 12 | +/// Checks for `Variable.get()` calls outside of Airflow task execution |
| 13 | +/// context (i.e., outside `@task`-decorated functions and operator |
| 14 | +/// `execute()` methods). |
| 15 | +/// |
| 16 | +/// ## Why is this bad? |
| 17 | +/// Calling `Variable.get()` at module level or in operator constructor |
| 18 | +/// arguments causes a database query every time the Dag file is parsed |
| 19 | +/// by the scheduler. This can degrade Dag parsing performance and, in |
| 20 | +/// some cases, cause the Dag file to time out before it is fully parsed. |
| 21 | +/// |
| 22 | +/// Instead, pass Airflow Variables to operators via Jinja templates |
| 23 | +/// (`{{ var.value.my_var }}` or `{{ var.json.my_var }}`), which defer |
| 24 | +/// the lookup until task execution. |
| 25 | +/// |
| 26 | +/// `Variable.get()` inside `@task`-decorated functions and operator |
| 27 | +/// `execute()` methods is fine because those only run during task |
| 28 | +/// execution, not during Dag parsing. |
| 29 | +/// |
| 30 | +/// Note that this rule may produce false positives for helper functions |
| 31 | +/// that are only invoked at task execution time (e.g., passed as |
| 32 | +/// `python_callable` to `PythonOperator`). In such cases, suppress the |
| 33 | +/// diagnostic with `# noqa: AIR003`. |
| 34 | +/// |
| 35 | +/// ## Example |
| 36 | +/// ```python |
| 37 | +/// from airflow.sdk import Variable |
| 38 | +/// from airflow.operators.bash import BashOperator |
| 39 | +/// |
| 40 | +/// |
| 41 | +/// foo = Variable.get("foo") |
| 42 | +/// BashOperator(task_id="bad", bash_command="echo $FOO", env={"FOO": foo}) |
| 43 | +/// ``` |
| 44 | +/// |
| 45 | +/// Use instead: |
| 46 | +/// ```python |
| 47 | +/// from airflow.operators.bash import BashOperator |
| 48 | +/// |
| 49 | +/// |
| 50 | +/// BashOperator( |
| 51 | +/// task_id="good", |
| 52 | +/// bash_command="echo $FOO", |
| 53 | +/// env={"FOO": "{{ var.value.foo }}"}, |
| 54 | +/// ) |
| 55 | +/// ``` |
| 56 | +#[derive(ViolationMetadata)] |
| 57 | +#[violation_metadata(preview_since = "NEXT_RUFF_VERSION")] |
| 58 | +pub(crate) struct AirflowVariableGetOutsideTask { |
| 59 | + in_function: bool, |
| 60 | +} |
| 61 | + |
| 62 | +impl Violation for AirflowVariableGetOutsideTask { |
| 63 | + #[derive_message_formats] |
| 64 | + fn message(&self) -> String { |
| 65 | + "`Variable.get()` outside of a task".to_string() |
| 66 | + } |
| 67 | + |
| 68 | + fn fix_title(&self) -> Option<String> { |
| 69 | + if self.in_function { |
| 70 | + Some("Move into a `@task`-decorated function".to_string()) |
| 71 | + } else { |
| 72 | + Some("Use Jinja templates instead".to_string()) |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +/// AIR003 |
| 78 | +pub(crate) fn variable_get_outside_task(checker: &Checker, expr: &Expr) { |
| 79 | + if !checker.semantic().seen_module(Modules::AIRFLOW) { |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + let Expr::Call(ast::ExprCall { func, .. }) = expr else { |
| 84 | + return; |
| 85 | + }; |
| 86 | + |
| 87 | + if !is_variable_get(func, checker.semantic()) { |
| 88 | + return; |
| 89 | + } |
| 90 | + |
| 91 | + if !is_dag_file(checker.semantic()) { |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + if in_task_execution_context(checker.semantic()) { |
| 96 | + return; |
| 97 | + } |
| 98 | + |
| 99 | + let in_function = matches!( |
| 100 | + checker.semantic().current_scope().kind, |
| 101 | + ScopeKind::Function(_) | ScopeKind::Lambda(_) |
| 102 | + ); |
| 103 | + |
| 104 | + checker.report_diagnostic(AirflowVariableGetOutsideTask { in_function }, expr.range()); |
| 105 | +} |
| 106 | + |
| 107 | +/// Returns `true` if the file imports `DAG` or `dag` from airflow, which |
| 108 | +/// indicates it is a Dag definition file. |
| 109 | +fn is_dag_file(semantic: &SemanticModel) -> bool { |
| 110 | + semantic.global_scope().binding_ids().any(|binding_id| { |
| 111 | + semantic |
| 112 | + .binding(binding_id) |
| 113 | + .as_any_import() |
| 114 | + .is_some_and(|import| { |
| 115 | + matches!( |
| 116 | + import.qualified_name().segments(), |
| 117 | + ["airflow", .., "DAG" | "dag"] |
| 118 | + ) |
| 119 | + }) |
| 120 | + }) |
| 121 | +} |
| 122 | + |
| 123 | +/// Returns `true` if `func` resolves to `Variable.get`. |
| 124 | +fn is_variable_get(func: &Expr, semantic: &SemanticModel) -> bool { |
| 125 | + semantic |
| 126 | + .resolve_qualified_name(func) |
| 127 | + .is_some_and(|qualified_name| { |
| 128 | + matches!( |
| 129 | + qualified_name.segments(), |
| 130 | + ["airflow", "models" | "sdk", .., "Variable", "get"] |
| 131 | + ) |
| 132 | + }) |
| 133 | +} |
| 134 | + |
| 135 | +/// Returns `true` if the current location is inside a `@task`-decorated function |
| 136 | +/// or a task-execution-time method on an Airflow operator subclass. |
| 137 | +fn in_task_execution_context(semantic: &SemanticModel) -> bool { |
| 138 | + semantic |
| 139 | + .current_statements() |
| 140 | + .find_map(|stmt| stmt.as_function_def_stmt()) |
| 141 | + .is_some_and(|function_def| { |
| 142 | + is_airflow_task(function_def, semantic) |
| 143 | + || is_operator_task_method(function_def, semantic) |
| 144 | + }) |
| 145 | +} |
| 146 | + |
| 147 | +/// Returns `true` if the function is a task-execution-time method (`execute`, |
| 148 | +/// `pre_execute`, or `post_execute`) defined inside a class that inherits from |
| 149 | +/// an Airflow operator. |
| 150 | +/// |
| 151 | +/// This is similar to `helpers::is_method_in_subclass` but can't reuse it |
| 152 | +/// directly because we're called from inside the function body (need to walk up |
| 153 | +/// to the parent class scope), whereas `is_method_in_subclass` expects to already |
| 154 | +/// be at the class scope. |
| 155 | +fn is_operator_task_method(function_def: &StmtFunctionDef, semantic: &SemanticModel) -> bool { |
| 156 | + if !matches!( |
| 157 | + function_def.name.as_str(), |
| 158 | + "execute" | "pre_execute" | "post_execute" |
| 159 | + ) { |
| 160 | + return false; |
| 161 | + } |
| 162 | + |
| 163 | + let Some(parent_scope) = semantic.first_non_type_parent_scope(semantic.current_scope()) else { |
| 164 | + return false; |
| 165 | + }; |
| 166 | + |
| 167 | + let ScopeKind::Class(class_def) = parent_scope.kind else { |
| 168 | + return false; |
| 169 | + }; |
| 170 | + |
| 171 | + any_qualified_base_class(class_def, semantic, &|qn| { |
| 172 | + matches!( |
| 173 | + qn.segments(), |
| 174 | + ["airflow", "models" | "sdk", .., "BaseOperator"] |
| 175 | + ) |
| 176 | + }) |
| 177 | +} |
0 commit comments