|
17 | 17 | from __future__ import annotations
|
18 | 18 |
|
19 | 19 | import logging
|
| 20 | +from abc import ABC, abstractmethod |
| 21 | +from dataclasses import dataclass |
20 | 22 | from datetime import datetime, timedelta
|
21 |
| -from enum import Enum |
22 |
| -from typing import TYPE_CHECKING, Callable |
| 23 | +from typing import TYPE_CHECKING, Any, Callable |
23 | 24 |
|
24 | 25 | import sqlalchemy_jsonfield
|
25 | 26 | import uuid6
|
26 |
| -from sqlalchemy import Column, ForeignKey, Index, Integer, String |
| 27 | +from sqlalchemy import Column, ForeignKey, Index, Integer, String, select |
| 28 | +from sqlalchemy.exc import SQLAlchemyError |
27 | 29 | from sqlalchemy.orm import relationship
|
28 | 30 | from sqlalchemy_utils import UUIDType
|
29 | 31 |
|
30 | 32 | from airflow.models.base import Base, StringID
|
31 | 33 | from airflow.settings import json
|
| 34 | +from airflow.utils.log.logging_mixin import LoggingMixin |
32 | 35 | from airflow.utils.module_loading import import_string, is_valid_dotpath
|
33 | 36 | from airflow.utils.session import NEW_SESSION, provide_session
|
34 | 37 | from airflow.utils.sqlalchemy import UtcDateTime
|
35 | 38 |
|
36 | 39 | if TYPE_CHECKING:
|
37 | 40 | from sqlalchemy.orm import Session
|
38 | 41 |
|
| 42 | + from airflow.sdk.definitions.deadline import DeadlineReference |
| 43 | + |
39 | 44 | logger = logging.getLogger(__name__)
|
40 | 45 |
|
41 | 46 |
|
@@ -100,33 +105,67 @@ def add_deadline(cls, deadline: Deadline, session: Session = NEW_SESSION):
|
100 | 105 | session.add(deadline)
|
101 | 106 |
|
102 | 107 |
|
103 |
| -class DeadlineReference(Enum): |
| 108 | +class ReferenceModels: |
104 | 109 | """
|
105 |
| - Store the calculation methods for the various Deadline Alert triggers. |
| 110 | + Store the implementations for the different Deadline References. |
106 | 111 |
|
107 |
| - TODO: PLEASE NOTE This class is a placeholder and will be expanded in the next PR. |
| 112 | + After adding the implementations here, all DeadlineReferences should be added |
| 113 | + to the user interface in airflow.sdk.definitions.deadline.DeadlineReference |
| 114 | + """ |
108 | 115 |
|
109 |
| - ------ |
110 |
| - Usage: |
111 |
| - ------ |
| 116 | + class BaseDeadlineReference(LoggingMixin, ABC): |
| 117 | + """Base class for all Deadline implementations.""" |
112 | 118 |
|
113 |
| - Example use when defining a deadline in a DAG: |
| 119 | + # Set of required kwargs - subclasses should override this. |
| 120 | + required_kwargs: set[str] = set() |
114 | 121 |
|
115 |
| - DAG( |
116 |
| - dag_id='dag_with_deadline', |
117 |
| - deadline=DeadlineAlert( |
118 |
| - reference=DeadlineReference.DAGRUN_LOGICAL_DATE, |
119 |
| - interval=timedelta(hours=1), |
120 |
| - callback=hello_callback, |
121 |
| - ) |
122 |
| - ) |
| 122 | + def evaluate_with(self, **kwargs: Any) -> datetime: |
| 123 | + """Validate the provided kwargs and evaluate this deadline with the given conditions.""" |
| 124 | + filtered_kwargs = {k: v for k, v in kwargs.items() if k in self.required_kwargs} |
123 | 125 |
|
124 |
| - To parse the deadline reference later we will use something like: |
| 126 | + if missing_kwargs := self.required_kwargs - filtered_kwargs.keys(): |
| 127 | + raise ValueError( |
| 128 | + f"{self.__class__.__name__} is missing required parameters: {', '.join(missing_kwargs)}" |
| 129 | + ) |
125 | 130 |
|
126 |
| - dag.deadline.reference.evaluate_with(dag_id=dag.dag_id) |
127 |
| - """ |
| 131 | + if extra_kwargs := kwargs.keys() - filtered_kwargs.keys(): |
| 132 | + self.log.debug("Ignoring unexpected parameters: %s", ", ".join(extra_kwargs)) |
| 133 | + |
| 134 | + return self._evaluate_with(**filtered_kwargs) |
| 135 | + |
| 136 | + @abstractmethod |
| 137 | + def _evaluate_with(self, **kwargs: Any) -> datetime: |
| 138 | + """Must be implemented by subclasses to perform the actual evaluation.""" |
| 139 | + raise NotImplementedError |
| 140 | + |
| 141 | + @dataclass |
| 142 | + class FixedDatetimeDeadline(BaseDeadlineReference): |
| 143 | + """A deadline that always returns a fixed datetime.""" |
| 144 | + |
| 145 | + _datetime: datetime |
| 146 | + |
| 147 | + def _evaluate_with(self, **kwargs: Any) -> datetime: |
| 148 | + return self._datetime |
| 149 | + |
| 150 | + class DagRunLogicalDateDeadline(BaseDeadlineReference): |
| 151 | + """A deadline that returns a DagRun's logical date.""" |
| 152 | + |
| 153 | + required_kwargs = {"dag_id"} |
| 154 | + |
| 155 | + def _evaluate_with(self, **kwargs: Any) -> datetime: |
| 156 | + from airflow.models import DagRun |
| 157 | + |
| 158 | + return _fetch_from_db(DagRun.logical_date, **kwargs) |
| 159 | + |
| 160 | + class DagRunQueuedAtDeadline(BaseDeadlineReference): |
| 161 | + """A deadline that returns when a DagRun was queued.""" |
128 | 162 |
|
129 |
| - DAGRUN_LOGICAL_DATE = "dagrun_logical_date" |
| 163 | + required_kwargs = {"dag_id"} |
| 164 | + |
| 165 | + def _evaluate_with(self, **kwargs: Any) -> datetime: |
| 166 | + from airflow.models import DagRun |
| 167 | + |
| 168 | + return _fetch_from_db(DagRun.queued_at, **kwargs) |
130 | 169 |
|
131 | 170 |
|
132 | 171 | class DeadlineAlert:
|
@@ -186,3 +225,52 @@ def serialize_deadline_alert(self):
|
186 | 225 | "callback_kwargs": self.callback_kwargs,
|
187 | 226 | }
|
188 | 227 | )
|
| 228 | + |
| 229 | + |
| 230 | +@provide_session |
| 231 | +def _fetch_from_db(model_reference: Column, session=None, **conditions) -> datetime: |
| 232 | + """ |
| 233 | + Fetch a datetime value from the database using the provided model reference and filtering conditions. |
| 234 | +
|
| 235 | + For example, to fetch a TaskInstance's start_date: |
| 236 | + _fetch_from_db( |
| 237 | + TaskInstance.start_date, dag_id='example_dag', task_id='example_task', run_id='example_run' |
| 238 | + ) |
| 239 | +
|
| 240 | + This generates SQL equivalent to: |
| 241 | + SELECT start_date |
| 242 | + FROM task_instance |
| 243 | + WHERE dag_id = 'example_dag' |
| 244 | + AND task_id = 'example_task' |
| 245 | + AND run_id = 'example_run' |
| 246 | +
|
| 247 | + :param model_reference: SQLAlchemy Column to select (e.g., DagRun.logical_date, TaskInstance.start_date) |
| 248 | + :param conditions: Filtering conditions applied as equality comparisons in the WHERE clause. |
| 249 | + Multiple conditions are combined with AND. |
| 250 | + :param session: SQLAlchemy session (auto-provided by decorator) |
| 251 | + """ |
| 252 | + query = select(model_reference) |
| 253 | + |
| 254 | + for key, value in conditions.items(): |
| 255 | + query = query.where(getattr(model_reference.class_, key) == value) |
| 256 | + |
| 257 | + compiled_query = query.compile(compile_kwargs={"literal_binds": True}) |
| 258 | + pretty_query = "\n ".join(str(compiled_query).splitlines()) |
| 259 | + logger.debug( |
| 260 | + "Executing query:\n %r\nAs SQL:\n %s", |
| 261 | + query, |
| 262 | + pretty_query, |
| 263 | + ) |
| 264 | + |
| 265 | + try: |
| 266 | + result = session.scalar(query) |
| 267 | + except SQLAlchemyError: |
| 268 | + logger.exception("Database query failed.") |
| 269 | + raise |
| 270 | + |
| 271 | + if result is None: |
| 272 | + message = f"No matching record found in the database for query:\n {pretty_query}" |
| 273 | + logger.error(message) |
| 274 | + raise ValueError(message) |
| 275 | + |
| 276 | + return result |
0 commit comments