ashb commented on code in PR #45043:
URL: https://github.com/apache/airflow/pull/45043#discussion_r1890866907
##########
task_sdk/src/airflow/sdk/api/client.py:
##########
@@ -161,9 +164,19 @@ class ConnectionOperations:
def __init__(self, client: Client):
self.client = client
- def get(self, conn_id: str) -> ConnectionResponse:
+ def get(self, conn_id: str) -> ConnectionResponse | ErrorResponse:
"""Get a connection from the API server."""
- resp = self.client.get(f"connections/{conn_id}")
+ try:
+ resp = self.client.get(f"connections/{conn_id}")
+ except ServerResponseError as e:
+ if e.response.status_code == HTTPStatus.NOT_FOUND:
+ log.error(
+ "Connection not found",
+ conn_id=conn_id,
+ detail=e.detail,
+ status_code=e.response.status_code,
+ )
+ return ErrorResponse(error=ErrorType.CONNECTION_NOT_FOUND,
detail={"conn_id": conn_id})
Review Comment:
Return seems an odd choice to me. Was there a reason you didn't throw?
##########
task_sdk/tests/execution_time/test_task_runner.py:
##########
@@ -399,6 +406,7 @@ def test_get_context_without_ti_context_from_server(self,
mocked_parse, make_ti_
# Verify the context keys and values
assert context == {
+ "conn": None,
Review Comment:
Shouldn't we be able to populate a conn accessor here?
##########
task_sdk/src/airflow/sdk/execution_time/context.py:
##########
@@ -0,0 +1,70 @@
+# 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 typing import TYPE_CHECKING, Any
+
+import structlog
+
+if TYPE_CHECKING:
+ from airflow.sdk.execution_time.comms import ConnectionResult
+
+
+def _convert_connection_result_conn(conn_result: ConnectionResult):
+ from airflow.sdk.definitions.connection import Connection
+
+ return Connection(**conn_result.model_dump(exclude={"type"},
by_alias=True))
+
+
+def get_connection(conn_id: str):
+ # TODO: This should probably be moved to a separate module like
`airflow.sdk.execution_time.comms`
+ # or `airflow.sdk.execution_time.connection`
+ # A reason to not move it to `airflow.sdk.execution_time.comms` is that
it
+ # will make that module depend on Task SDK, which is not ideal because
we intend to
+ # keep Task SDK as a separate package than execution time mods.
+ from airflow.sdk.execution_time.comms import GetConnection
+ from airflow.sdk.execution_time.task_runner import SUPERVISOR_COMMS
+
+ log = structlog.get_logger(logger_name="task")
+ SUPERVISOR_COMMS.send_request(log=log, msg=GetConnection(conn_id=conn_id))
+ msg = SUPERVISOR_COMMS.get_message()
+ return _convert_connection_result_conn(msg)
+
+
+class ConnectionAccessor:
+ """Wrapper to access Connection entries in template."""
+
+ def __init__(self) -> None:
+ self.var: Any = None
+
+ def __getattr__(self, key: str) -> Any:
+ self.var = get_connection(key)
Review Comment:
This doesn't make any sense to me - if I do `{{ conn.myconn }}` that
shouldn't have any side effects on `{{conn}}` should it?
##########
task_sdk/tests/execution_time/test_context.py:
##########
@@ -0,0 +1,106 @@
+# 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 unittest import mock
+
+from airflow.sdk.definitions.connection import Connection
+from airflow.sdk.exceptions import ErrorType
+from airflow.sdk.execution_time.comms import ConnectionResult, ErrorResponse
+from airflow.sdk.execution_time.context import ConnectionAccessor,
_convert_connection_result_conn
+
+
+def test_convert_connection_result_conn():
+ """Test that the ConnectionResult is converted to a Connection object."""
+ conn = ConnectionResult(
+ conn_id="test_conn",
+ conn_type="mysql",
+ host="mysql",
+ schema="airflow",
+ login="root",
+ password="password",
+ port=1234,
+ extra='{"extra_key": "extra_value"}',
+ )
+ conn = _convert_connection_result_conn(conn)
+ assert conn == Connection(
+ conn_id="test_conn",
+ conn_type="mysql",
+ host="mysql",
+ schema="airflow",
+ login="root",
+ password="password",
+ port=1234,
+ extra='{"extra_key": "extra_value"}',
+ )
+
+
+class TestConnectionAccessor:
+ def test_lazy_fetch_connection(self):
+ """
+ Test that the connection is lazily fetched when accessed and also
using __getattr__.
+
+ The __getattr__ method is used for template rendering. Example: ``{{
conn.mysql_conn.host }}``.
+ """
+ accessor = ConnectionAccessor()
+ # conn is not fetched yet
+ assert accessor.conn is None
Review Comment:
```suggestion
```
##########
task_sdk/src/airflow/sdk/exceptions.py:
##########
@@ -14,3 +14,24 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+
+from __future__ import annotations
+
+import enum
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from airflow.sdk.execution_time.comms import ErrorResponse
+
+
+class AirflowRuntimeError(Exception):
+ def __init__(self, error: ErrorResponse):
+ self.error = error
+ super().__init__(f"{error.error.value}: {error.detail}")
Review Comment:
I feel this should be a classmethod and pull out the fields we want from the
Error response, not store it.
Also a sort of nit: by having the raise inside this function the first item
on the call stack is going to be this which will make the source of the error
somewhat.
I think it should be used as something like this - separate create exception
from raise it.
```python
raise error_reponse.to_exception()
```
##########
task_sdk/tests/execution_time/test_context.py:
##########
@@ -0,0 +1,106 @@
+# 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 unittest import mock
+
+from airflow.sdk.definitions.connection import Connection
+from airflow.sdk.exceptions import ErrorType
+from airflow.sdk.execution_time.comms import ConnectionResult, ErrorResponse
+from airflow.sdk.execution_time.context import ConnectionAccessor,
_convert_connection_result_conn
+
+
+def test_convert_connection_result_conn():
+ """Test that the ConnectionResult is converted to a Connection object."""
+ conn = ConnectionResult(
+ conn_id="test_conn",
+ conn_type="mysql",
+ host="mysql",
+ schema="airflow",
+ login="root",
+ password="password",
+ port=1234,
+ extra='{"extra_key": "extra_value"}',
+ )
+ conn = _convert_connection_result_conn(conn)
+ assert conn == Connection(
+ conn_id="test_conn",
+ conn_type="mysql",
+ host="mysql",
+ schema="airflow",
+ login="root",
+ password="password",
+ port=1234,
+ extra='{"extra_key": "extra_value"}',
+ )
+
+
+class TestConnectionAccessor:
+ def test_lazy_fetch_connection(self):
+ """
+ Test that the connection is lazily fetched when accessed and also
using __getattr__.
+
+ The __getattr__ method is used for template rendering. Example: ``{{
conn.mysql_conn.host }}``.
+ """
+ accessor = ConnectionAccessor()
+ # conn is not fetched yet
+ assert accessor.conn is None
+
+ # Conn from the supervisor / API Server
+ conn_result = ConnectionResult(conn_id="mysql_conn",
conn_type="mysql", host="mysql", port=3306)
+
+ with mock.patch(
+ "airflow.sdk.execution_time.task_runner.SUPERVISOR_COMMS",
create=True
+ ) as mock_supervisor_comms:
+ mock_supervisor_comms.get_message.return_value = conn_result
+
+ # Fetch the connection; Triggers __getattr__
+ conn = accessor.mysql_conn
+
+ expected_conn = Connection(conn_id="mysql_conn",
conn_type="mysql", host="mysql", port=3306)
+ assert conn == expected_conn
+ assert accessor.conn == expected_conn
Review Comment:
```suggestion
```
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]