-
Notifications
You must be signed in to change notification settings - Fork 17.7k
Add WebSocketSensor and WebSocketTrigger to the standard provider #72133
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
Open
ColtenOuO
wants to merge
6
commits into
apache:main
Choose a base branch
from
ColtenOuO:websocket-trigger-standard-provider
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e8d955b
Add WebSocketSensor and WebSocketTrigger to the standard provider
ColtenOuO 2c17a30
Fix WebSocketSensor connection reuse and base class per review
ColtenOuO 22dd11b
Fix CI by restoring the amazon/azure uv.lock version bump
ColtenOuO 22f1226
Keep one WebSocket connection open across sensor pokes
ColtenOuO d4ea6bf
Fix CI, sensor timeout handling, and document trigger idempotency
ColtenOuO 8905318
Bound the WebSocket handshake too, and fix CI spellcheck
ColtenOuO 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| .. 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. | ||
|
|
||
|
|
||
|
|
||
| .. _howto/operator:WebSocketSensor: | ||
|
|
||
| WebSocketSensor | ||
| ================ | ||
|
|
||
| Use the :class:`~airflow.providers.standard.sensors.websocket.WebSocketSensor` to wait for a message on a | ||
| ``ws://`` or ``wss://`` WebSocket connection. This is useful when a remote server accepts a long-lived | ||
| connection and replies asynchronously once it has handled the requested work, since a plain HTTP request | ||
| is not well suited to that kind of long-lived connection. Requires the ``websocket`` extra | ||
| (``apache-airflow-providers-standard[websocket]``). | ||
|
|
||
| .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_sensors.py | ||
| :language: python | ||
| :dedent: 4 | ||
| :start-after: [START example_websocket_sensor] | ||
| :end-before: [END example_websocket_sensor] | ||
|
|
||
| Also for this job you can use sensor in the deferrable mode: | ||
|
|
||
| .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_sensors.py | ||
| :language: python | ||
| :dedent: 4 | ||
| :start-after: [START example_websocket_sensor_async] | ||
| :end-before: [END example_websocket_sensor_async] | ||
|
|
||
| A common use case is to send a request over the connection right after it opens (via | ||
| ``message_to_send``) and then wait for the remote server's asynchronous reply, optionally | ||
| passing connection headers such as an auth token via ``header``: | ||
|
|
||
| .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_sensors.py | ||
| :language: python | ||
| :dedent: 4 | ||
| :start-after: [START example_websocket_sensor_send_message_async] | ||
| :end-before: [END example_websocket_sensor_send_message_async] | ||
|
|
||
| .. warning:: | ||
| In deferrable mode, ``message_to_send`` may be sent more than once for a single task | ||
| run. Airflow triggers are not guaranteed to execute exactly once — a triggerer | ||
| restart or redistribution to another host re-runs the trigger from scratch, opening | ||
| a new connection and re-sending ``message_to_send``. If that message has a side | ||
| effect on the remote server, such as starting a job, the server must treat a resend | ||
| as safe — for example by deduplicating on a request id embedded in the message. | ||
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
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
107 changes: 107 additions & 0 deletions
107
providers/standard/src/airflow/providers/standard/sensors/websocket.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,107 @@ | ||
| # 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. | ||
| from __future__ import annotations | ||
|
|
||
| import datetime | ||
| import time | ||
| from collections.abc import Sequence | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| from websockets.sync.client import connect | ||
|
|
||
| from airflow.providers.common.compat.sdk import BaseSensorOperator, conf, poke_mode_only | ||
| from airflow.providers.standard.triggers.websocket import WebSocketTrigger | ||
|
|
||
| if TYPE_CHECKING: | ||
| from airflow.sdk import Context | ||
|
|
||
|
|
||
| @poke_mode_only | ||
| class WebSocketSensor(BaseSensorOperator): | ||
|
ColtenOuO marked this conversation as resolved.
|
||
| """ | ||
| Waits for a message on a WebSocket connection. | ||
|
|
||
| WebSocket messages are consumptive: once read, a message cannot be read again, and | ||
| reconnecting can duplicate ``message_to_send`` against the remote server. The | ||
| non-deferrable path therefore opens exactly one connection and blocks on it for up to | ||
| ``timeout`` seconds instead of reconnecting every ``poke_interval`` (which has no | ||
| effect on this sensor), and this sensor is marked poke-mode-only since a rescheduled | ||
| invocation would need a new connection anyway. | ||
|
|
||
| :param url: The ``ws://`` or ``wss://`` URL of the WebSocket server to connect to. | ||
| :param header: Optional headers sent when opening the connection. | ||
| :param message_to_send: Optional message sent right after the connection is established. | ||
| :param deferrable: If waiting for completion, whether to defer the task until done, | ||
| default is ``False``. | ||
|
|
||
| .. seealso:: | ||
| For more information on how to use this sensor, take a look at the guide: | ||
| :ref:`howto/operator:WebSocketSensor` | ||
|
ColtenOuO marked this conversation as resolved.
|
||
| """ | ||
|
|
||
| template_fields: Sequence[str] = ("url", "header", "message_to_send") | ||
| template_fields_renderers = {"header": "json"} | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| url: str, | ||
| header: dict[str, str] | None = None, | ||
| message_to_send: str | bytes | None = None, | ||
| deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), | ||
| **kwargs, | ||
| ): | ||
| super().__init__(**kwargs) | ||
| self.url = url | ||
| self.header = header | ||
| self.message_to_send = message_to_send | ||
| self.deferrable = deferrable | ||
|
|
||
| def poke(self, context: Context) -> bool: | ||
| self.log.info("Connecting to WebSocket %s", self.url) | ||
| deadline = time.monotonic() + self.timeout | ||
| try: | ||
| with connect(self.url, additional_headers=self.header, open_timeout=self.timeout) as websocket: | ||
| if self.message_to_send is not None: | ||
| websocket.send(self.message_to_send) | ||
| websocket.recv(timeout=max(deadline - time.monotonic(), 0)) | ||
| except TimeoutError: | ||
| return False | ||
| self.log.info("Received message from %s", self.url) | ||
| return True | ||
|
|
||
| def execute(self, context: Context) -> None: | ||
| if not self.deferrable: | ||
| super().execute(context=context) | ||
| return | ||
| # Each poke opens and consumes a WebSocket connection, so the deferrable path must | ||
| # defer immediately: polling here first would send message_to_send and consume the | ||
| # reply before handing off, leaving the trigger to open a second connection and | ||
| # re-send the request. | ||
| self.defer( | ||
| timeout=datetime.timedelta(seconds=self.timeout), | ||
| trigger=WebSocketTrigger( | ||
| url=self.url, | ||
| header=self.header, | ||
| message_to_send=self.message_to_send, | ||
| ), | ||
| method_name="execute_complete", | ||
| ) | ||
|
|
||
| def execute_complete(self, context: Context, event: Any = None) -> None: | ||
| """Handle the event when the trigger fires and return immediately.""" | ||
| self.log.info("%s completed successfully with message: %s", self.task_id, event) | ||
76 changes: 76 additions & 0 deletions
76
providers/standard/src/airflow/providers/standard/triggers/websocket.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,76 @@ | ||
| # 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. | ||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import AsyncIterator | ||
| from typing import Any | ||
|
|
||
| from websockets.asyncio.client import connect | ||
|
|
||
| from airflow.triggers.base import BaseTrigger, TriggerEvent | ||
|
|
||
|
|
||
| class WebSocketTrigger(BaseTrigger): | ||
| """ | ||
| A trigger that opens a WebSocket connection and fires once a message is received. | ||
|
|
||
| This is meant for deferrable operators that hand off a long-lived request to a remote | ||
| WebSocket server and resume once that server replies, without occupying a worker slot | ||
| while waiting. | ||
|
|
||
| Like any Airflow trigger, ``run()`` is not guaranteed to execute only once: a | ||
| triggerer restart or redistribution to another host re-runs it from scratch. Each | ||
| execution opens a new connection and re-sends ``message_to_send`` if one is set, so | ||
| if that message starts a remote job, the remote server must treat a resend as safe — | ||
| for example by deduplicating on a request id embedded in the message. | ||
|
|
||
| :param url: The ``ws://`` or ``wss://`` URL of the WebSocket server to connect to. | ||
| :param header: Optional headers sent when opening the connection. | ||
| :param message_to_send: Optional message sent right after the connection is established. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| url: str, | ||
| header: dict[str, str] | None = None, | ||
| message_to_send: str | bytes | None = None, | ||
| **kwargs, | ||
| ): | ||
| super().__init__() | ||
| self.url = url | ||
| self.header = header | ||
| self.message_to_send = message_to_send | ||
|
|
||
| def serialize(self) -> tuple[str, dict[str, Any]]: | ||
| """Serialize WebSocketTrigger arguments and classpath.""" | ||
| return ( | ||
| "airflow.providers.standard.triggers.websocket.WebSocketTrigger", | ||
| { | ||
| "url": self.url, | ||
| "header": self.header, | ||
| "message_to_send": self.message_to_send, | ||
| }, | ||
| ) | ||
|
|
||
| async def run(self) -> AsyncIterator[TriggerEvent]: | ||
| """Connect to the WebSocket server and wait for the first message.""" | ||
| async with connect(self.url, additional_headers=self.header) as websocket: | ||
| if self.message_to_send is not None: | ||
| await websocket.send(self.message_to_send) | ||
|
ColtenOuO marked this conversation as resolved.
|
||
| message = await websocket.recv() | ||
| self.log.info("Received message from %s", self.url) | ||
| yield TriggerEvent(message) | ||
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.
Uh oh!
There was an error while loading. Please reload this page.