apache-airflow-providers-standard 0.0.2rc1__py3-none-any.whl → 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. airflow/providers/standard/__init__.py +3 -3
  2. airflow/providers/standard/get_provider_info.py +15 -3
  3. airflow/providers/standard/operators/bash.py +17 -10
  4. airflow/providers/standard/operators/latest_only.py +78 -0
  5. airflow/providers/standard/operators/python.py +33 -53
  6. airflow/providers/standard/operators/trigger_dagrun.py +1 -10
  7. airflow/providers/standard/sensors/date_time.py +3 -3
  8. airflow/providers/standard/sensors/external_task.py +512 -0
  9. airflow/providers/standard/sensors/filesystem.py +18 -3
  10. airflow/providers/standard/sensors/time.py +3 -3
  11. airflow/providers/standard/sensors/time_delta.py +22 -3
  12. airflow/providers/standard/{utils/version_references.py → triggers/__init__.py} +0 -10
  13. airflow/providers/standard/triggers/external_task.py +216 -0
  14. airflow/providers/standard/triggers/file.py +77 -0
  15. airflow/providers/standard/triggers/temporal.py +114 -0
  16. airflow/providers/standard/utils/python_virtualenv_script.jinja2 +2 -2
  17. airflow/providers/standard/utils/sensor_helper.py +123 -0
  18. airflow/providers/standard/version_compat.py +36 -0
  19. {apache_airflow_providers_standard-0.0.2rc1.dist-info → apache_airflow_providers_standard-0.0.3.dist-info}/METADATA +10 -10
  20. apache_airflow_providers_standard-0.0.3.dist-info/RECORD +37 -0
  21. apache_airflow_providers_standard-0.0.2rc1.dist-info/RECORD +0 -30
  22. {apache_airflow_providers_standard-0.0.2rc1.dist-info → apache_airflow_providers_standard-0.0.3.dist-info}/WHEEL +0 -0
  23. {apache_airflow_providers_standard-0.0.2rc1.dist-info → apache_airflow_providers_standard-0.0.3.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,512 @@
1
+ #
2
+ # Licensed to the Apache Software Foundation (ASF) under one
3
+ # or more contributor license agreements. See the NOTICE file
4
+ # distributed with this work for additional information
5
+ # regarding copyright ownership. The ASF licenses this file
6
+ # to you under the Apache License, Version 2.0 (the
7
+ # "License"); you may not use this file except in compliance
8
+ # with the License. You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing,
13
+ # software distributed under the License is distributed on an
14
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ # KIND, either express or implied. See the License for the
16
+ # specific language governing permissions and limitations
17
+ # under the License.
18
+ from __future__ import annotations
19
+
20
+ import datetime
21
+ import os
22
+ import warnings
23
+ from collections.abc import Collection, Iterable
24
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar
25
+
26
+ from airflow.configuration import conf
27
+ from airflow.exceptions import AirflowException, AirflowSkipException
28
+ from airflow.models.baseoperatorlink import BaseOperatorLink
29
+ from airflow.models.dag import DagModel
30
+ from airflow.models.dagbag import DagBag
31
+ from airflow.models.taskinstance import TaskInstance
32
+ from airflow.operators.empty import EmptyOperator
33
+ from airflow.providers.standard.triggers.external_task import WorkflowTrigger
34
+ from airflow.providers.standard.utils.sensor_helper import _get_count, _get_external_task_group_task_ids
35
+ from airflow.sensors.base import BaseSensorOperator
36
+ from airflow.utils.file import correct_maybe_zipped
37
+ from airflow.utils.helpers import build_airflow_url_with_query
38
+ from airflow.utils.session import NEW_SESSION, provide_session
39
+ from airflow.utils.state import State, TaskInstanceState
40
+
41
+ if TYPE_CHECKING:
42
+ from sqlalchemy.orm import Session
43
+
44
+ from airflow.models.baseoperator import BaseOperator
45
+ from airflow.models.taskinstancekey import TaskInstanceKey
46
+ from airflow.utils.context import Context
47
+
48
+
49
+ class ExternalDagLink(BaseOperatorLink):
50
+ """
51
+ Operator link for ExternalTaskSensor and ExternalTaskMarker.
52
+
53
+ It allows users to access DAG waited with ExternalTaskSensor or cleared by ExternalTaskMarker.
54
+ """
55
+
56
+ name = "External DAG"
57
+
58
+ def get_link(self, operator: BaseOperator, *, ti_key: TaskInstanceKey) -> str:
59
+ from airflow.models.renderedtifields import RenderedTaskInstanceFields
60
+
61
+ ti = TaskInstance.get_task_instance(
62
+ dag_id=ti_key.dag_id, run_id=ti_key.run_id, task_id=ti_key.task_id, map_index=ti_key.map_index
63
+ )
64
+
65
+ if TYPE_CHECKING:
66
+ assert ti is not None
67
+
68
+ template_fields = RenderedTaskInstanceFields.get_templated_fields(ti)
69
+ external_dag_id = (
70
+ template_fields["external_dag_id"] if template_fields else operator.external_dag_id # type: ignore[attr-defined]
71
+ )
72
+ query = {
73
+ "dag_id": external_dag_id,
74
+ "logical_date": ti.logical_date.isoformat(), # type: ignore[union-attr]
75
+ }
76
+
77
+ return build_airflow_url_with_query(query)
78
+
79
+
80
+ class ExternalTaskSensor(BaseSensorOperator):
81
+ """
82
+ Waits for a different DAG, task group, or task to complete for a specific logical date.
83
+
84
+ If both `external_task_group_id` and `external_task_id` are ``None`` (default), the sensor
85
+ waits for the DAG.
86
+ Values for `external_task_group_id` and `external_task_id` can't be set at the same time.
87
+
88
+ By default, the ExternalTaskSensor will wait for the external task to
89
+ succeed, at which point it will also succeed. However, by default it will
90
+ *not* fail if the external task fails, but will continue to check the status
91
+ until the sensor times out (thus giving you time to retry the external task
92
+ without also having to clear the sensor).
93
+
94
+ By default, the ExternalTaskSensor will not skip if the external task skips.
95
+ To change this, simply set ``skipped_states=[TaskInstanceState.SKIPPED]``.
96
+ Note that if you are monitoring multiple tasks, and one enters error state
97
+ and the other enters a skipped state, then the external task will react to
98
+ whichever one it sees first. If both happen together, then the failed state
99
+ takes priority.
100
+
101
+ It is possible to alter the default behavior by setting states which
102
+ cause the sensor to fail, e.g. by setting ``allowed_states=[DagRunState.FAILED]``
103
+ and ``failed_states=[DagRunState.SUCCESS]`` you will flip the behaviour to
104
+ get a sensor which goes green when the external task *fails* and immediately
105
+ goes red if the external task *succeeds*!
106
+
107
+ Note that ``soft_fail`` is respected when examining the failed_states. Thus
108
+ if the external task enters a failed state and ``soft_fail == True`` the
109
+ sensor will _skip_ rather than fail. As a result, setting ``soft_fail=True``
110
+ and ``failed_states=[DagRunState.SKIPPED]`` will result in the sensor
111
+ skipping if the external task skips. However, this is a contrived
112
+ example---consider using ``skipped_states`` if you would like this
113
+ behaviour. Using ``skipped_states`` allows the sensor to skip if the target
114
+ fails, but still enter failed state on timeout. Using ``soft_fail == True``
115
+ as above will cause the sensor to skip if the target fails, but also if it
116
+ times out.
117
+
118
+ :param external_dag_id: The dag_id that contains the task you want to
119
+ wait for. (templated)
120
+ :param external_task_id: The task_id that contains the task you want to
121
+ wait for. (templated)
122
+ :param external_task_ids: The list of task_ids that you want to wait for. (templated)
123
+ If ``None`` (default value) the sensor waits for the DAG. Either
124
+ external_task_id or external_task_ids can be passed to
125
+ ExternalTaskSensor, but not both.
126
+ :param external_task_group_id: The task_group_id that contains the task you want to
127
+ wait for. (templated)
128
+ :param allowed_states: Iterable of allowed states, default is ``['success']``
129
+ :param skipped_states: Iterable of states to make this task mark as skipped, default is ``None``
130
+ :param failed_states: Iterable of failed or dis-allowed states, default is ``None``
131
+ :param execution_delta: time difference with the previous execution to
132
+ look at, the default is the same logical date as the current task or DAG.
133
+ For yesterday, use [positive!] datetime.timedelta(days=1). Either
134
+ execution_delta or execution_date_fn can be passed to
135
+ ExternalTaskSensor, but not both.
136
+ :param execution_date_fn: function that receives the current execution's logical date as the first
137
+ positional argument and optionally any number of keyword arguments available in the
138
+ context dictionary, and returns the desired logical dates to query.
139
+ Either execution_delta or execution_date_fn can be passed to ExternalTaskSensor,
140
+ but not both.
141
+ :param check_existence: Set to `True` to check if the external task exists (when
142
+ external_task_id is not None) or check if the DAG to wait for exists (when
143
+ external_task_id is None), and immediately cease waiting if the external task
144
+ or DAG does not exist (default value: False).
145
+ :param poll_interval: polling period in seconds to check for the status
146
+ :param deferrable: Run sensor in deferrable mode
147
+ """
148
+
149
+ template_fields = ["external_dag_id", "external_task_id", "external_task_ids", "external_task_group_id"]
150
+ ui_color = "#4db7db"
151
+ operator_extra_links = [ExternalDagLink()]
152
+
153
+ def __init__(
154
+ self,
155
+ *,
156
+ external_dag_id: str,
157
+ external_task_id: str | None = None,
158
+ external_task_ids: Collection[str] | None = None,
159
+ external_task_group_id: str | None = None,
160
+ allowed_states: Iterable[str] | None = None,
161
+ skipped_states: Iterable[str] | None = None,
162
+ failed_states: Iterable[str] | None = None,
163
+ execution_delta: datetime.timedelta | None = None,
164
+ execution_date_fn: Callable | None = None,
165
+ check_existence: bool = False,
166
+ poll_interval: float = 2.0,
167
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
168
+ **kwargs,
169
+ ):
170
+ super().__init__(**kwargs)
171
+
172
+ self.allowed_states = list(allowed_states) if allowed_states else [TaskInstanceState.SUCCESS.value]
173
+ self.skipped_states = list(skipped_states) if skipped_states else []
174
+ self.failed_states = list(failed_states) if failed_states else []
175
+
176
+ total_states = set(self.allowed_states + self.skipped_states + self.failed_states)
177
+
178
+ if len(total_states) != len(self.allowed_states) + len(self.skipped_states) + len(self.failed_states):
179
+ raise AirflowException(
180
+ "Duplicate values provided across allowed_states, skipped_states and failed_states."
181
+ )
182
+
183
+ # convert [] to None
184
+ if not external_task_ids:
185
+ external_task_ids = None
186
+
187
+ # can't set both single task id and a list of task ids
188
+ if external_task_id is not None and external_task_ids is not None:
189
+ raise ValueError(
190
+ "Only one of `external_task_id` or `external_task_ids` may "
191
+ "be provided to ExternalTaskSensor; "
192
+ "use external_task_id or external_task_ids or external_task_group_id."
193
+ )
194
+
195
+ # since both not set, convert the single id to a 1-elt list - from here on, we only consider the list
196
+ if external_task_id is not None:
197
+ external_task_ids = [external_task_id]
198
+
199
+ if external_task_group_id is not None and external_task_ids is not None:
200
+ raise ValueError(
201
+ "Only one of `external_task_group_id` or `external_task_ids` may "
202
+ "be provided to ExternalTaskSensor; "
203
+ "use external_task_id or external_task_ids or external_task_group_id."
204
+ )
205
+
206
+ # check the requested states are all valid states for the target type, be it dag or task
207
+ if external_task_ids or external_task_group_id:
208
+ if not total_states <= set(State.task_states):
209
+ raise ValueError(
210
+ "Valid values for `allowed_states`, `skipped_states` and `failed_states` "
211
+ "when `external_task_id` or `external_task_ids` or `external_task_group_id` "
212
+ f"is not `None`: {State.task_states}"
213
+ )
214
+
215
+ elif not total_states <= set(State.dag_states):
216
+ raise ValueError(
217
+ "Valid values for `allowed_states`, `skipped_states` and `failed_states` "
218
+ f"when `external_task_id` and `external_task_group_id` is `None`: {State.dag_states}"
219
+ )
220
+
221
+ if execution_delta is not None and execution_date_fn is not None:
222
+ raise ValueError(
223
+ "Only one of `execution_delta` or `execution_date_fn` may "
224
+ "be provided to ExternalTaskSensor; not both."
225
+ )
226
+
227
+ self.execution_delta = execution_delta
228
+ self.execution_date_fn = execution_date_fn
229
+ self.external_dag_id = external_dag_id
230
+ self.external_task_id = external_task_id
231
+ self.external_task_ids = external_task_ids
232
+ self.external_task_group_id = external_task_group_id
233
+ self.check_existence = check_existence
234
+ self._has_checked_existence = False
235
+ self.deferrable = deferrable
236
+ self.poll_interval = poll_interval
237
+
238
+ def _get_dttm_filter(self, context):
239
+ if self.execution_delta:
240
+ dttm = context["logical_date"] - self.execution_delta
241
+ elif self.execution_date_fn:
242
+ dttm = self._handle_execution_date_fn(context=context)
243
+ else:
244
+ dttm = context["logical_date"]
245
+ return dttm if isinstance(dttm, list) else [dttm]
246
+
247
+ @provide_session
248
+ def poke(self, context: Context, session: Session = NEW_SESSION) -> bool:
249
+ # delay check to poke rather than __init__ in case it was supplied as XComArgs
250
+ if self.external_task_ids and len(self.external_task_ids) > len(set(self.external_task_ids)):
251
+ raise ValueError("Duplicate task_ids passed in external_task_ids parameter")
252
+
253
+ dttm_filter = self._get_dttm_filter(context)
254
+ serialized_dttm_filter = ",".join(dt.isoformat() for dt in dttm_filter)
255
+
256
+ if self.external_task_ids:
257
+ self.log.info(
258
+ "Poking for tasks %s in dag %s on %s ... ",
259
+ self.external_task_ids,
260
+ self.external_dag_id,
261
+ serialized_dttm_filter,
262
+ )
263
+
264
+ if self.external_task_group_id:
265
+ self.log.info(
266
+ "Poking for task_group '%s' in dag '%s' on %s ... ",
267
+ self.external_task_group_id,
268
+ self.external_dag_id,
269
+ serialized_dttm_filter,
270
+ )
271
+
272
+ if self.external_dag_id and not self.external_task_group_id and not self.external_task_ids:
273
+ self.log.info(
274
+ "Poking for DAG '%s' on %s ... ",
275
+ self.external_dag_id,
276
+ serialized_dttm_filter,
277
+ )
278
+
279
+ # In poke mode this will check dag existence only once
280
+ if self.check_existence and not self._has_checked_existence:
281
+ self._check_for_existence(session=session)
282
+
283
+ count_failed = -1
284
+ if self.failed_states:
285
+ count_failed = self.get_count(dttm_filter, session, self.failed_states)
286
+
287
+ # Fail if anything in the list has failed.
288
+ if count_failed > 0:
289
+ if self.external_task_ids:
290
+ if self.soft_fail:
291
+ raise AirflowSkipException(
292
+ f"Some of the external tasks {self.external_task_ids} "
293
+ f"in DAG {self.external_dag_id} failed. Skipping due to soft_fail."
294
+ )
295
+ raise AirflowException(
296
+ f"Some of the external tasks {self.external_task_ids} "
297
+ f"in DAG {self.external_dag_id} failed."
298
+ )
299
+ elif self.external_task_group_id:
300
+ if self.soft_fail:
301
+ raise AirflowSkipException(
302
+ f"The external task_group '{self.external_task_group_id}' "
303
+ f"in DAG '{self.external_dag_id}' failed. Skipping due to soft_fail."
304
+ )
305
+ raise AirflowException(
306
+ f"The external task_group '{self.external_task_group_id}' "
307
+ f"in DAG '{self.external_dag_id}' failed."
308
+ )
309
+
310
+ else:
311
+ if self.soft_fail:
312
+ raise AirflowSkipException(
313
+ f"The external DAG {self.external_dag_id} failed. Skipping due to soft_fail."
314
+ )
315
+ raise AirflowException(f"The external DAG {self.external_dag_id} failed.")
316
+
317
+ count_skipped = -1
318
+ if self.skipped_states:
319
+ count_skipped = self.get_count(dttm_filter, session, self.skipped_states)
320
+
321
+ # Skip if anything in the list has skipped. Note if we are checking multiple tasks and one skips
322
+ # before another errors, we'll skip first.
323
+ if count_skipped > 0:
324
+ if self.external_task_ids:
325
+ raise AirflowSkipException(
326
+ f"Some of the external tasks {self.external_task_ids} "
327
+ f"in DAG {self.external_dag_id} reached a state in our states-to-skip-on list. Skipping."
328
+ )
329
+ elif self.external_task_group_id:
330
+ raise AirflowSkipException(
331
+ f"The external task_group '{self.external_task_group_id}' "
332
+ f"in DAG {self.external_dag_id} reached a state in our states-to-skip-on list. Skipping."
333
+ )
334
+ else:
335
+ raise AirflowSkipException(
336
+ f"The external DAG {self.external_dag_id} reached a state in our states-to-skip-on list. "
337
+ "Skipping."
338
+ )
339
+
340
+ # only go green if every single task has reached an allowed state
341
+ count_allowed = self.get_count(dttm_filter, session, self.allowed_states)
342
+ return count_allowed == len(dttm_filter)
343
+
344
+ def execute(self, context: Context) -> None:
345
+ """Run on the worker and defer using the triggers if deferrable is set to True."""
346
+ if not self.deferrable:
347
+ super().execute(context)
348
+ else:
349
+ self.defer(
350
+ timeout=self.execution_timeout,
351
+ trigger=WorkflowTrigger(
352
+ external_dag_id=self.external_dag_id,
353
+ external_task_group_id=self.external_task_group_id,
354
+ external_task_ids=self.external_task_ids,
355
+ logical_dates=self._get_dttm_filter(context),
356
+ allowed_states=self.allowed_states,
357
+ poke_interval=self.poll_interval,
358
+ soft_fail=self.soft_fail,
359
+ ),
360
+ method_name="execute_complete",
361
+ )
362
+
363
+ def execute_complete(self, context, event=None):
364
+ """Execute when the trigger fires - return immediately."""
365
+ if event["status"] == "success":
366
+ self.log.info("External tasks %s has executed successfully.", self.external_task_ids)
367
+ elif event["status"] == "skipped":
368
+ raise AirflowSkipException("External job has skipped skipping.")
369
+ else:
370
+ if self.soft_fail:
371
+ raise AirflowSkipException("External job has failed skipping.")
372
+ else:
373
+ raise AirflowException(
374
+ "Error occurred while trying to retrieve task status. Please, check the "
375
+ "name of executed task and Dag."
376
+ )
377
+
378
+ def _check_for_existence(self, session) -> None:
379
+ dag_to_wait = DagModel.get_current(self.external_dag_id, session)
380
+
381
+ if not dag_to_wait:
382
+ raise AirflowException(f"The external DAG {self.external_dag_id} does not exist.")
383
+
384
+ if not os.path.exists(correct_maybe_zipped(dag_to_wait.fileloc)):
385
+ raise AirflowException(f"The external DAG {self.external_dag_id} was deleted.")
386
+
387
+ if self.external_task_ids:
388
+ refreshed_dag_info = DagBag(dag_to_wait.fileloc).get_dag(self.external_dag_id)
389
+ for external_task_id in self.external_task_ids:
390
+ if not refreshed_dag_info.has_task(external_task_id):
391
+ raise AirflowException(
392
+ f"The external task {external_task_id} in "
393
+ f"DAG {self.external_dag_id} does not exist."
394
+ )
395
+
396
+ if self.external_task_group_id:
397
+ refreshed_dag_info = DagBag(dag_to_wait.fileloc).get_dag(self.external_dag_id)
398
+ if not refreshed_dag_info.has_task_group(self.external_task_group_id):
399
+ raise AirflowException(
400
+ f"The external task group '{self.external_task_group_id}' in "
401
+ f"DAG '{self.external_dag_id}' does not exist."
402
+ )
403
+
404
+ self._has_checked_existence = True
405
+
406
+ def get_count(self, dttm_filter, session, states) -> int:
407
+ """
408
+ Get the count of records against dttm filter and states.
409
+
410
+ :param dttm_filter: date time filter for logical date
411
+ :param session: airflow session object
412
+ :param states: task or dag states
413
+ :return: count of record against the filters
414
+ """
415
+ warnings.warn(
416
+ "This method is deprecated and will be removed in future.", DeprecationWarning, stacklevel=2
417
+ )
418
+ return _get_count(
419
+ dttm_filter,
420
+ self.external_task_ids,
421
+ self.external_task_group_id,
422
+ self.external_dag_id,
423
+ states,
424
+ session,
425
+ )
426
+
427
+ def get_external_task_group_task_ids(self, session, dttm_filter):
428
+ warnings.warn(
429
+ "This method is deprecated and will be removed in future.", DeprecationWarning, stacklevel=2
430
+ )
431
+ return _get_external_task_group_task_ids(
432
+ dttm_filter, self.external_task_group_id, self.external_dag_id, session
433
+ )
434
+
435
+ def _handle_execution_date_fn(self, context) -> Any:
436
+ """
437
+ Handle backward compatibility.
438
+
439
+ This function is to handle backwards compatibility with how this operator was
440
+ previously where it only passes the logical date, but also allow for the newer
441
+ implementation to pass all context variables as keyword arguments, to allow
442
+ for more sophisticated returns of dates to return.
443
+ """
444
+ from airflow.utils.operator_helpers import make_kwargs_callable
445
+
446
+ # Remove "logical_date" because it is already a mandatory positional argument
447
+ logical_date = context["logical_date"]
448
+ kwargs = {k: v for k, v in context.items() if k not in {"execution_date", "logical_date"}}
449
+ # Add "context" in the kwargs for backward compatibility (because context used to be
450
+ # an acceptable argument of execution_date_fn)
451
+ kwargs["context"] = context
452
+ if TYPE_CHECKING:
453
+ assert self.execution_date_fn is not None
454
+ kwargs_callable = make_kwargs_callable(self.execution_date_fn)
455
+ return kwargs_callable(logical_date, **kwargs)
456
+
457
+
458
+ class ExternalTaskMarker(EmptyOperator):
459
+ """
460
+ Use this operator to indicate that a task on a different DAG depends on this task.
461
+
462
+ When this task is cleared with "Recursive" selected, Airflow will clear the task on
463
+ the other DAG and its downstream tasks recursively. Transitive dependencies are followed
464
+ until the recursion_depth is reached.
465
+
466
+ :param external_dag_id: The dag_id that contains the dependent task that needs to be cleared.
467
+ :param external_task_id: The task_id of the dependent task that needs to be cleared.
468
+ :param logical_date: The logical date of the dependent task execution that needs to be cleared.
469
+ :param recursion_depth: The maximum level of transitive dependencies allowed. Default is 10.
470
+ This is mostly used for preventing cyclic dependencies. It is fine to increase
471
+ this number if necessary. However, too many levels of transitive dependencies will make
472
+ it slower to clear tasks in the web UI.
473
+ """
474
+
475
+ template_fields = ["external_dag_id", "external_task_id", "logical_date"]
476
+ ui_color = "#4db7db"
477
+ operator_extra_links = [ExternalDagLink()]
478
+
479
+ # The _serialized_fields are lazily loaded when get_serialized_fields() method is called
480
+ __serialized_fields: ClassVar[frozenset[str] | None] = None
481
+
482
+ def __init__(
483
+ self,
484
+ *,
485
+ external_dag_id: str,
486
+ external_task_id: str,
487
+ logical_date: str | datetime.datetime | None = "{{ logical_date.isoformat() }}",
488
+ recursion_depth: int = 10,
489
+ **kwargs,
490
+ ):
491
+ super().__init__(**kwargs)
492
+ self.external_dag_id = external_dag_id
493
+ self.external_task_id = external_task_id
494
+ if isinstance(logical_date, datetime.datetime):
495
+ self.logical_date = logical_date.isoformat()
496
+ elif isinstance(logical_date, str):
497
+ self.logical_date = logical_date
498
+ else:
499
+ raise TypeError(
500
+ f"Expected str or datetime.datetime type for logical_date. Got {type(logical_date)}"
501
+ )
502
+
503
+ if recursion_depth <= 0:
504
+ raise ValueError("recursion_depth should be a positive integer")
505
+ self.recursion_depth = recursion_depth
506
+
507
+ @classmethod
508
+ def get_serialized_fields(cls):
509
+ """Serialize ExternalTaskMarker to contain exactly these fields + templated_fields ."""
510
+ if not cls.__serialized_fields:
511
+ cls.__serialized_fields = frozenset(super().get_serialized_fields() | {"recursion_depth"})
512
+ return cls.__serialized_fields
@@ -20,6 +20,7 @@ from __future__ import annotations
20
20
  import datetime
21
21
  import os
22
22
  from collections.abc import Sequence
23
+ from dataclasses import dataclass
23
24
  from functools import cached_property
24
25
  from glob import glob
25
26
  from typing import TYPE_CHECKING, Any
@@ -27,9 +28,23 @@ from typing import TYPE_CHECKING, Any
27
28
  from airflow.configuration import conf
28
29
  from airflow.exceptions import AirflowException
29
30
  from airflow.providers.standard.hooks.filesystem import FSHook
31
+ from airflow.providers.standard.triggers.file import FileTrigger
30
32
  from airflow.sensors.base import BaseSensorOperator
31
- from airflow.triggers.base import StartTriggerArgs
32
- from airflow.triggers.file import FileTrigger
33
+
34
+ try:
35
+ from airflow.triggers.base import StartTriggerArgs
36
+ except ImportError:
37
+ # TODO: Remove this when min airflow version is 2.10.0 for standard provider
38
+ @dataclass
39
+ class StartTriggerArgs: # type: ignore[no-redef]
40
+ """Arguments required for start task execution from triggerer."""
41
+
42
+ trigger_cls: str
43
+ next_method: str
44
+ trigger_kwargs: dict[str, Any] | None = None
45
+ next_kwargs: dict[str, Any] | None = None
46
+ timeout: datetime.timedelta | None = None
47
+
33
48
 
34
49
  if TYPE_CHECKING:
35
50
  from airflow.utils.context import Context
@@ -64,7 +79,7 @@ class FileSensor(BaseSensorOperator):
64
79
  template_fields: Sequence[str] = ("filepath",)
65
80
  ui_color = "#91818a"
66
81
  start_trigger_args = StartTriggerArgs(
67
- trigger_cls="airflow.triggers.file.FileTrigger",
82
+ trigger_cls="airflow.providers.standard.triggers.file.FileTrigger",
68
83
  trigger_kwargs={},
69
84
  next_method="execute_complete",
70
85
  next_kwargs=None,
@@ -21,7 +21,8 @@ import datetime
21
21
  from dataclasses import dataclass
22
22
  from typing import TYPE_CHECKING, Any, NoReturn
23
23
 
24
- from airflow.providers.standard.utils.version_references import AIRFLOW_V_2_10_PLUS
24
+ from airflow.providers.standard.triggers.temporal import DateTimeTrigger
25
+ from airflow.providers.standard.version_compat import AIRFLOW_V_2_10_PLUS
25
26
  from airflow.sensors.base import BaseSensorOperator
26
27
 
27
28
  try:
@@ -39,7 +40,6 @@ except ImportError:
39
40
  timeout: datetime.timedelta | None = None
40
41
 
41
42
 
42
- from airflow.triggers.temporal import DateTimeTrigger
43
43
  from airflow.utils import timezone
44
44
 
45
45
  if TYPE_CHECKING:
@@ -85,7 +85,7 @@ class TimeSensorAsync(BaseSensorOperator):
85
85
  """
86
86
 
87
87
  start_trigger_args = StartTriggerArgs(
88
- trigger_cls="airflow.triggers.temporal.DateTimeTrigger",
88
+ trigger_cls="airflow.providers.standard.triggers.temporal.DateTimeTrigger",
89
89
  trigger_kwargs={"moment": "", "end_from_trigger": False},
90
90
  next_method="execute_complete",
91
91
  next_kwargs=None,
@@ -21,17 +21,25 @@ from datetime import timedelta
21
21
  from time import sleep
22
22
  from typing import TYPE_CHECKING, Any, NoReturn
23
23
 
24
+ from packaging.version import Version
25
+
24
26
  from airflow.configuration import conf
25
27
  from airflow.exceptions import AirflowSkipException
26
- from airflow.providers.standard.utils.version_references import AIRFLOW_V_3_0_PLUS
28
+ from airflow.providers.standard.triggers.temporal import DateTimeTrigger, TimeDeltaTrigger
29
+ from airflow.providers.standard.version_compat import AIRFLOW_V_3_0_PLUS
27
30
  from airflow.sensors.base import BaseSensorOperator
28
- from airflow.triggers.temporal import DateTimeTrigger, TimeDeltaTrigger
29
31
  from airflow.utils import timezone
30
32
 
31
33
  if TYPE_CHECKING:
32
34
  from airflow.utils.context import Context
33
35
 
34
36
 
37
+ def _get_airflow_version():
38
+ from airflow import __version__ as airflow_version
39
+
40
+ return Version(Version(airflow_version).base_version)
41
+
42
+
35
43
  class TimeDeltaSensor(BaseSensorOperator):
36
44
  """
37
45
  Waits for a timedelta after the run's data interval.
@@ -91,7 +99,18 @@ class TimeDeltaSensorAsync(TimeDeltaSensor):
91
99
  raise AirflowSkipException("Skipping due to soft_fail is set to True.") from e
92
100
  raise
93
101
 
94
- self.defer(trigger=trigger, method_name="execute_complete")
102
+ # todo: remove backcompat when min airflow version greater than 2.11
103
+ timeout: int | float | timedelta
104
+ if _get_airflow_version() >= Version("2.11.0"):
105
+ timeout = self.timeout
106
+ else:
107
+ timeout = timedelta(seconds=self.timeout)
108
+
109
+ self.defer(
110
+ trigger=trigger,
111
+ method_name="execute_complete",
112
+ timeout=timeout,
113
+ )
95
114
 
96
115
  def execute_complete(self, context: Context, event: Any = None) -> None:
97
116
  """Handle the event when the trigger fires and return immediately."""
@@ -1,4 +1,3 @@
1
- #
2
1
  # Licensed to the Apache Software Foundation (ASF) under one
3
2
  # or more contributor license agreements. See the NOTICE file
4
3
  # distributed with this work for additional information
@@ -15,12 +14,3 @@
15
14
  # KIND, either express or implied. See the License for the
16
15
  # specific language governing permissions and limitations
17
16
  # under the License.
18
- from __future__ import annotations
19
-
20
- from packaging.version import Version
21
-
22
- from airflow import __version__ as airflow_version
23
-
24
- AIRFLOW_VERSION = Version(airflow_version)
25
- AIRFLOW_V_2_10_PLUS = Version(AIRFLOW_VERSION.base_version) >= Version("2.10.0")
26
- AIRFLOW_V_3_0_PLUS = Version(AIRFLOW_VERSION.base_version) >= Version("3.0.0")