You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "collinmcnulty (via GitHub)" <gi...@apache.org> on 2024/08/17 18:41:19 UTC
[PR] Wait sensor async [airflow]
collinmcnulty opened a new pull request, #41557:
URL: https://github.com/apache/airflow/pull/41557
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
Thank you for contributing! Please make sure that your code changes
are covered with tests. And in case of new features or big changes
remember to adjust the documentation.
Feel free to ping committers for the review!
In case of an existing issue, reference it using one of the following:
closes: #ISSUE
related: #ISSUE
How to write a good git commit message:
http://chris.beams.io/posts/git-commit/
-->
<!-- Please keep an empty line above the dashes. -->
---
There is an example of a deferrable sensor that waits for one hour [in the documentation](https://airflow.apache.org/docs/apache-airflow/stable/authoring-and-scheduling/deferring.html#writing-deferrable-operators), but there has not yet been an implementation of such a sensor in Airflow. This seems like a such a basic use case that it would make sense to include. There is the TimeDeltaSensor, but this sensor is based on the data interval of the DAG run, not the start time of the task.
I have observed some Airflow users using BashOperators that sleep for a specified time for want of this sensor, which would be strictly better, especially when run as deferrable.
**^ Add meaningful description above**
Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Wait sensor async [airflow]
Posted by "collinmcnulty (via GitHub)" <gi...@apache.org>.
collinmcnulty commented on code in PR #41557:
URL: https://github.com/apache/airflow/pull/41557#discussion_r1723782013
##########
tests/sensors/test_time_delta.py:
##########
@@ -71,3 +71,17 @@ def test_timedelta_sensor(self, defer_mock, should_defer):
defer_mock.assert_called_once()
else:
defer_mock.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "should_defer",
+ [False, True],
+ )
+ @mock.patch("airflow.models.baseoperator.BaseOperator.defer")
+ def test_wait_sensor(self, defer_mock, should_defer):
+ delta = timedelta(seconds=30)
+ op = WaitSensor(task_id="wait_sensor_check", delta=delta, dag=self.dag, deferrable=should_defer)
+ op.execute({})
+ if should_defer:
+ defer_mock.assert_called_once()
Review Comment:
Trigger class isn't set up for this unfortunately.
```
FAILED tests/sensors/test_time_delta.py::TestTimeDeltaSensorAsync::test_wait_sensor[True] - AssertionError: expected call not found.
Expected: defer(trigger=<airflow.triggers.temporal.DateTimeTrigger moment=2024-08-01 00:00:30+00:00, end_from_trigger=True>, method_name='execute_complete')
Actual: defer(trigger=<airflow.triggers.temporal.DateTimeTrigger moment=2024-08-01 00:00:30+00:00, end_from_trigger=True>, method_name='execute_complete')
```
##########
airflow/sensors/time_delta.py:
##########
@@ -89,3 +92,38 @@ def execute(self, context: Context) -> bool | NoReturn:
def execute_complete(self, context: Context, event: Any = None) -> None:
"""Handle the event when the trigger fires and return immediately."""
return None
+
+
+class WaitSensor(BaseSensorOperator):
+ """
+ A sensor that waits a specified period of time before completing.
+
+ This differs from TimeDeltaSensor because the time to wait is measured from the start of the task, not
+ the data_interval_end of the DAG run.
+
+ :param delta: time length to wait after the task starts before succeeding.
Review Comment:
will do
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Wait sensor async [airflow]
Posted by "RNHTTR (via GitHub)" <gi...@apache.org>.
RNHTTR commented on code in PR #41557:
URL: https://github.com/apache/airflow/pull/41557#discussion_r1723492253
##########
tests/sensors/test_time_delta.py:
##########
@@ -71,3 +71,17 @@ def test_timedelta_sensor(self, defer_mock, should_defer):
defer_mock.assert_called_once()
else:
defer_mock.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "should_defer",
+ [False, True],
+ )
+ @mock.patch("airflow.models.baseoperator.BaseOperator.defer")
+ def test_wait_sensor(self, defer_mock, should_defer):
+ delta = timedelta(seconds=30)
+ op = WaitSensor(task_id="wait_sensor_check", delta=delta, dag=self.dag, deferrable=should_defer)
+ op.execute({})
+ if should_defer:
+ defer_mock.assert_called_once()
Review Comment:
Can you use `assert_called_once_with(...)`?
##########
tests/sensors/test_time_delta.py:
##########
@@ -71,3 +71,17 @@ def test_timedelta_sensor(self, defer_mock, should_defer):
defer_mock.assert_called_once()
else:
defer_mock.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "should_defer",
+ [False, True],
+ )
+ @mock.patch("airflow.models.baseoperator.BaseOperator.defer")
+ def test_wait_sensor(self, defer_mock, should_defer):
+ delta = timedelta(seconds=30)
Review Comment:
I wonder if you can patch `asyncio.sleep` so the test doesn't have to wait at all
##########
airflow/sensors/time_delta.py:
##########
@@ -89,3 +92,38 @@ def execute(self, context: Context) -> bool | NoReturn:
def execute_complete(self, context: Context, event: Any = None) -> None:
"""Handle the event when the trigger fires and return immediately."""
return None
+
+
+class WaitSensor(BaseSensorOperator):
+ """
+ A sensor that waits a specified period of time before completing.
+
+ This differs from TimeDeltaSensor because the time to wait is measured from the start of the task, not
+ the data_interval_end of the DAG run.
+
+ :param delta: time length to wait after the task starts before succeeding.
Review Comment:
What about `time_to_wait` instead of `delta`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Wait sensor async [airflow]
Posted by "RNHTTR (via GitHub)" <gi...@apache.org>.
RNHTTR commented on code in PR #41557:
URL: https://github.com/apache/airflow/pull/41557#discussion_r1723825971
##########
airflow/sensors/time_delta.py:
##########
@@ -89,3 +92,37 @@ def execute(self, context: Context) -> bool | NoReturn:
def execute_complete(self, context: Context, event: Any = None) -> None:
"""Handle the event when the trigger fires and return immediately."""
return None
+
+
+class WaitSensor(BaseSensorOperator):
+ """
+ A sensor that waits a specified period of time before completing.
+
+ This differs from TimeDeltaSensor because the time to wait is measured from the start of the task, not
+ the data_interval_end of the DAG run.
+
+ :param time_to_wait: time length to wait after the task starts before succeeding.
+ :param deferrable: Run sensor in deferrable mode
+ """
+
+ def __init__(
+ self,
+ time_to_wait: timedelta | int,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.deferrable = deferrable
+ if isinstance(time_to_wait, int):
+ self.delta = timedelta(minutes=time_to_wait)
+ else:
+ self.delta = time_to_wait
+
+ def execute(self, context: Context) -> None:
+ if self.deferrable:
+ self.defer(
+ trigger=TimeDeltaTrigger(self.delta, end_from_trigger=True),
Review Comment:
```suggestion
trigger=TimeDeltaTrigger(self.time_to_wait, end_from_trigger=True),
```
##########
airflow/sensors/time_delta.py:
##########
@@ -89,3 +92,37 @@ def execute(self, context: Context) -> bool | NoReturn:
def execute_complete(self, context: Context, event: Any = None) -> None:
"""Handle the event when the trigger fires and return immediately."""
return None
+
+
+class WaitSensor(BaseSensorOperator):
+ """
+ A sensor that waits a specified period of time before completing.
+
+ This differs from TimeDeltaSensor because the time to wait is measured from the start of the task, not
+ the data_interval_end of the DAG run.
+
+ :param time_to_wait: time length to wait after the task starts before succeeding.
+ :param deferrable: Run sensor in deferrable mode
+ """
+
+ def __init__(
+ self,
+ time_to_wait: timedelta | int,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.deferrable = deferrable
+ if isinstance(time_to_wait, int):
+ self.delta = timedelta(minutes=time_to_wait)
Review Comment:
```suggestion
self.time_to_wait = timedelta(minutes=time_to_wait)
```
##########
airflow/sensors/time_delta.py:
##########
@@ -89,3 +92,37 @@ def execute(self, context: Context) -> bool | NoReturn:
def execute_complete(self, context: Context, event: Any = None) -> None:
"""Handle the event when the trigger fires and return immediately."""
return None
+
+
+class WaitSensor(BaseSensorOperator):
+ """
+ A sensor that waits a specified period of time before completing.
+
+ This differs from TimeDeltaSensor because the time to wait is measured from the start of the task, not
+ the data_interval_end of the DAG run.
+
+ :param time_to_wait: time length to wait after the task starts before succeeding.
+ :param deferrable: Run sensor in deferrable mode
+ """
+
+ def __init__(
+ self,
+ time_to_wait: timedelta | int,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.deferrable = deferrable
+ if isinstance(time_to_wait, int):
+ self.delta = timedelta(minutes=time_to_wait)
+ else:
+ self.delta = time_to_wait
Review Comment:
```suggestion
self.time_to_wait = time_to_wait
```
##########
airflow/sensors/time_delta.py:
##########
@@ -89,3 +92,37 @@ def execute(self, context: Context) -> bool | NoReturn:
def execute_complete(self, context: Context, event: Any = None) -> None:
"""Handle the event when the trigger fires and return immediately."""
return None
+
+
+class WaitSensor(BaseSensorOperator):
+ """
+ A sensor that waits a specified period of time before completing.
+
+ This differs from TimeDeltaSensor because the time to wait is measured from the start of the task, not
+ the data_interval_end of the DAG run.
+
+ :param time_to_wait: time length to wait after the task starts before succeeding.
+ :param deferrable: Run sensor in deferrable mode
+ """
+
+ def __init__(
+ self,
+ time_to_wait: timedelta | int,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.deferrable = deferrable
+ if isinstance(time_to_wait, int):
+ self.delta = timedelta(minutes=time_to_wait)
+ else:
+ self.delta = time_to_wait
+
+ def execute(self, context: Context) -> None:
+ if self.deferrable:
+ self.defer(
+ trigger=TimeDeltaTrigger(self.delta, end_from_trigger=True),
+ method_name="execute_complete",
+ )
+ else:
+ sleep(int(self.delta.total_seconds()))
Review Comment:
```suggestion
sleep(int(self.time_to_wait.total_seconds()))
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Wait sensor async [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck merged PR #41557:
URL: https://github.com/apache/airflow/pull/41557
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org