jason810496 commented on code in PR #62343:
URL: https://github.com/apache/airflow/pull/62343#discussion_r2851045539
##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -249,6 +256,88 @@ def test_connection(test_body: ConnectionBody) ->
ConnectionTestResponse:
os.environ.pop(conn_env_var, None)
+@connections_router.post(
+ "/test-async",
+ status_code=status.HTTP_202_ACCEPTED,
+ responses=create_openapi_http_exception_doc([status.HTTP_403_FORBIDDEN,
status.HTTP_404_NOT_FOUND]),
+ dependencies=[Depends(requires_access_connection(method="POST")),
Depends(action_logging())],
+)
+def test_connection_async(
+ test_body: ConnectionTestRequestBody,
+ session: SessionDep,
+) -> ConnectionTestQueuedResponse:
+ """
+ Queue an async connection test to be executed on a worker.
+
+ The connection must already be saved. Returns a token that can be used
+ to poll for the test result via GET /connections/test-async/{token}.
+ """
+ if conf.get("core", "test_connection",
fallback="Disabled").lower().strip() != "enabled":
Review Comment:
Perhaps we could have a small util for the validation here as it's same as
`test_connection` route.
##########
airflow-core/src/airflow/models/connection_test.py:
##########
@@ -0,0 +1,125 @@
+# 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 secrets
+from datetime import datetime
+from enum import Enum
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+import structlog
+import uuid6
+from sqlalchemy import Boolean, ForeignKey, Index, String, Text, Uuid
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+
+from airflow._shared.timezones import timezone
+from airflow.models.base import Base
+from airflow.utils.sqlalchemy import UtcDateTime
+
+if TYPE_CHECKING:
+ from airflow.models.callback import Callback
+
+log = structlog.get_logger(__name__)
+
+
+class ConnectionTestState(str, Enum):
+ """All possible states of a connection test."""
+
+ PENDING = "pending"
+ QUEUED = "queued"
+ RUNNING = "running"
+ SUCCESS = "success"
+ FAILED = "failed"
+
+ def __str__(self) -> str:
+ return self.value
+
+
+TERMINAL_STATES = frozenset((ConnectionTestState.SUCCESS,
ConnectionTestState.FAILED))
+
+# Path used by ExecutorCallback to locate the worker function.
+RUN_CONNECTION_TEST_PATH = "airflow.models.connection_test.run_connection_test"
+
+
+class ConnectionTest(Base):
+ """Tracks an async connection test dispatched to a worker via
ExecutorCallback."""
+
+ __tablename__ = "connection_test"
+
+ id: Mapped[UUID] = mapped_column(Uuid(), primary_key=True,
default=uuid6.uuid7)
+ token: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
Review Comment:
I see. I just checked the dev mailing list for more context and you’re
right. Thanks for the clarification!
##########
airflow-core/src/airflow/models/connection_test.py:
##########
@@ -0,0 +1,155 @@
+# 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 secrets
+from datetime import datetime
+from enum import Enum
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+import structlog
+import uuid6
+from sqlalchemy import ForeignKey, Index, String, Text, Uuid
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+
+from airflow._shared.timezones import timezone
+from airflow.models.base import Base
+from airflow.utils.sqlalchemy import UtcDateTime
+
+if TYPE_CHECKING:
+ from airflow.models.callback import Callback, ExecutorCallback
+
+log = structlog.get_logger(__name__)
+
+
+class ConnectionTestState(str, Enum):
+ """All possible states of a connection test."""
+
+ PENDING = "pending"
+ QUEUED = "queued"
+ RUNNING = "running"
+ SUCCESS = "success"
+ FAILED = "failed"
+
+ def __str__(self) -> str:
+ return self.value
+
+
+TERMINAL_STATES = frozenset((ConnectionTestState.SUCCESS,
ConnectionTestState.FAILED))
+
+# Path used by ExecutorCallback to locate the worker function.
+RUN_CONNECTION_TEST_PATH = "airflow.models.connection_test.run_connection_test"
+
+
+class _ImportPathCallbackDef:
+ """
+ Minimal implementation of ImportPathExecutorCallbackDefProtocol.
+
+ ExecutorCallback.__init__ expects an object satisfying this protocol, but
no concrete
+ implementation exists in airflow-core — the only one (SyncCallback) lives
in the task-sdk.
+ Once #61153 lands and ExecuteCallback.make() is decoupled from DagRun,
this adapter can
+ be replaced with the proper factory method.
+ """
+
+ def __init__(self, path: str, kwargs: dict, executor: str | None = None):
+ self.path = path
+ self.kwargs = kwargs
+ self.executor = executor
+
+ def serialize(self) -> dict:
+ return {"path": self.path, "kwargs": self.kwargs, "executor":
self.executor}
+
+
+class ConnectionTest(Base):
+ """Tracks an async connection test dispatched to a worker via
ExecutorCallback."""
+
+ __tablename__ = "connection_test"
+
+ id: Mapped[UUID] = mapped_column(Uuid(), primary_key=True,
default=uuid6.uuid7)
+ token: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
+ connection_id: Mapped[str] = mapped_column(String(250), nullable=False)
+ state: Mapped[str] = mapped_column(String(10), nullable=False,
default=ConnectionTestState.PENDING)
+ result_message: Mapped[str | None] = mapped_column(Text, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(UtcDateTime,
default=timezone.utcnow, nullable=False)
+ updated_at: Mapped[datetime] = mapped_column(
+ UtcDateTime, default=timezone.utcnow, onupdate=timezone.utcnow,
nullable=False
+ )
+
+ callback_id: Mapped[UUID | None] = mapped_column(
+ Uuid(), ForeignKey("callback.id", ondelete="SET NULL"), nullable=True
+ )
+ callback: Mapped[Callback | None] = relationship("Callback", uselist=False)
+
+ __table_args__ = (Index("idx_connection_test_state_created_at", state,
created_at),)
+
+ def __init__(self, *, connection_id: str, **kwargs):
+ super().__init__(**kwargs)
+ self.connection_id = connection_id
+ self.token = secrets.token_urlsafe(32)
+ self.state = ConnectionTestState.PENDING
+
+ def __repr__(self) -> str:
+ return (
+ f"<ConnectionTest token={self.token!r}
connection_id={self.connection_id!r} state={self.state}>"
Review Comment:
Do we need to show the `id` column here as well?
##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -249,6 +256,88 @@ def test_connection(test_body: ConnectionBody) ->
ConnectionTestResponse:
os.environ.pop(conn_env_var, None)
+@connections_router.post(
+ "/test-async",
+ status_code=status.HTTP_202_ACCEPTED,
+ responses=create_openapi_http_exception_doc([status.HTTP_403_FORBIDDEN,
status.HTTP_404_NOT_FOUND]),
+ dependencies=[Depends(requires_access_connection(method="POST")),
Depends(action_logging())],
+)
+def test_connection_async(
+ test_body: ConnectionTestRequestBody,
+ session: SessionDep,
+) -> ConnectionTestQueuedResponse:
+ """
+ Queue an async connection test to be executed on a worker.
+
+ The connection must already be saved. Returns a token that can be used
+ to poll for the test result via GET /connections/test-async/{token}.
+ """
+ if conf.get("core", "test_connection",
fallback="Disabled").lower().strip() != "enabled":
+ raise HTTPException(
+ status.HTTP_403_FORBIDDEN,
+ "Testing connections is disabled in Airflow configuration. "
+ "Contact your deployment admin to enable it.",
+ )
+
+ try:
+ Connection.get_connection_from_secrets(test_body.connection_id)
+ except AirflowNotFoundException:
+ raise HTTPException(
+ status.HTTP_404_NOT_FOUND,
+ f"The Connection with connection_id: `{test_body.connection_id}`
was not found. "
+ "Connection must be saved before testing.",
+ )
+
+ connection_test = ConnectionTest(connection_id=test_body.connection_id)
+ session.add(connection_test)
+ session.flush()
+
+ callback = connection_test.create_callback()
+ session.add(callback)
+ session.flush()
+
+ connection_test.callback_id = callback.id
+ connection_test.state = ConnectionTestState.QUEUED
+ callback.queue()
+
+ return ConnectionTestQueuedResponse(
+ token=connection_test.token,
+ connection_id=connection_test.connection_id,
+ state=connection_test.state,
+ )
+
+
+@connections_router.get(
+ "/test-async/{token}",
Review Comment:
How about renaming `token` to `connection_test_token` here and for the
`get_connection_test_status` route, since it might be ambiguous for users on
the Iterative OpenAPI site?
It’s fine for `POST test_connection_async` because the `token` field is
wrapped in a `ConnectionTestQueuedResponse` body.
--
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]