jason810496 commented on code in PR #62343: URL: https://github.com/apache/airflow/pull/62343#discussion_r2839476949
########## 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: May I ask why not just using `ConnectionTest.id` instead of `ConnectionTest.token` as identifier to poll the status of `ConnectionTest`? Since the authentication is already handled by the JWT layer, the `token` here will still be served as _another_ identifier for retrieving the corresponding `ConnectionTest` model. ########## airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py: ########## @@ -249,6 +277,99 @@ 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() + + # ExecutorCallback requires an object satisfying ImportPathExecutorCallbackDefProtocol, + # but the only concrete impl (SyncCallback) lives in task-sdk which core API cannot + # import. This adapter will be replaced by ExecuteCallback.make() once #61153 merges. + callback_def = _ImportPathCallbackDef( + path=RUN_CONNECTION_TEST_PATH, + kwargs={ + "connection_id": test_body.connection_id, + "connection_test_id": str(connection_test.id), + }, + ) + callback = ExecutorCallback(callback_def, fetch_method=CallbackFetchMethod.IMPORT_PATH) Review Comment: How above moving `_ImportPathCallbackDef` to `models.test_connection` module and add a factory method for constructing `ExecutorCallback`? ########## airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py: ########## @@ -56,13 +59,38 @@ from airflow.configuration import conf from airflow.exceptions import AirflowNotFoundException from airflow.models import Connection +from airflow.models.callback import CallbackFetchMethod, ExecutorCallback +from airflow.models.connection_test import ( + RUN_CONNECTION_TEST_PATH, + ConnectionTest, + ConnectionTestState, +) from airflow.secrets.environment_variables import CONN_ENV_PREFIX from airflow.utils.db import create_default_connections as db_create_default_connections from airflow.utils.strings import get_random_string connections_router = AirflowRouter(tags=["Connection"], prefix="/connections") Review Comment: Just FYI that if rest of the reviewers also agree with current approach, we could refactor the existing synchronous test connection route like https://github.com/apache/airflow/blob/01318970138e873deb5b6e5883cb1a33b0d15a04/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dag_run.py#L527-L537 ########## 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) + connection_id: Mapped[str] = mapped_column(String(250), nullable=False) + state: Mapped[str] = mapped_column(String(10), nullable=False, default=ConnectionTestState.PENDING) + result_status: Mapped[bool | None] = mapped_column(Boolean, nullable=True) Review Comment: The `state` column should be sufficient, do we still need `result_status`? ########## airflow-core/src/airflow/api_fastapi/execution_api/routes/connection_tests.py: ########## @@ -0,0 +1,65 @@ +# 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 uuid import UUID + +from fastapi import APIRouter, HTTPException, status + +from airflow.api_fastapi.common.db.common import SessionDep +from airflow.api_fastapi.execution_api.datamodels.connection_test import ConnectionTestResultBody +from airflow.models.connection_test import TERMINAL_STATES, ConnectionTest + +router = APIRouter() + + Review Comment: This route is not currently used in TaskSDK, but I think it's fine to keep it in current PR. Since the synchronous callback _might_ be executed under TaskSDK instead directly being executed under Scheduler/Executor process in the long-term. Will confirm in https://github.com/apache/airflow/pull/61153#discussion_r2839816002 -- 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]
