dabla commented on code in PR #71350: URL: https://github.com/apache/airflow/pull/71350#discussion_r3841911123
########## providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/analysis_services.py: ########## @@ -0,0 +1,280 @@ +# 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 functools import cached_property +from typing import TYPE_CHECKING, Any, Literal, get_args +from urllib.parse import quote, unquote, urlsplit + +import httpx +from azure.core.exceptions import AzureError +from azure.identity.aio import ClientSecretCredential + +from airflow.providers.common.compat.sdk import AirflowException, BaseHook + +if TYPE_CHECKING: + from urllib.parse import SplitResult + + from azure.core.credentials_async import AsyncTokenCredential + + from airflow.sdk import Connection + +TOKEN_SCOPE = "https://*.asazure.windows.net/.default" + +RefreshType = Literal["full", "clearValues", "calculate", "dataOnly", "automatic", "defragment"] +VALID_REFRESH_TYPES: frozenset[str] = frozenset(get_args(RefreshType)) + + +def _format_request_error(error: httpx.HTTPError) -> str: + # Only HTTPStatusError carries a response; transport errors have no such attribute. + response = getattr(error, "response", None) + response_body = getattr(response, "text", "").strip()[:1000] + response_detail = f"; response body: {response_body}" if response_body else "" + return f"{error}{response_detail}" + + +class AzureAnalysisServicesRefreshStatus: + """Azure Analysis Services model refresh statuses.""" + + SUCCEEDED = "succeeded" + FAILED = "failed" + CANCELLED = "cancelled" + TIMED_OUT = "timedOut" + NOT_STARTED = "notStarted" + IN_PROGRESS = "inProgress" + + FAILURE_STATUSES = frozenset({FAILED, CANCELLED, TIMED_OUT}) + VALID_STATUSES = frozenset({SUCCEEDED, FAILED, CANCELLED, TIMED_OUT, NOT_STARTED, IN_PROGRESS}) + + +class AzureAnalysisServicesRefreshException(AirflowException): + """Indicate that an Azure Analysis Services model refresh operation failed.""" + + +class AzureAnalysisServicesHook(BaseHook): + """ + Interact with the Azure Analysis Services asynchronous refresh REST API. + + All request methods are asynchronous and are meant to be awaited from a trigger. Call + :meth:`aclose` when done so the HTTP client and the credential release their resources. + + :param azure_analysis_services_conn_id: The Azure Analysis Services connection ID. + :param request_timeout: Timeout in seconds for each HTTP request. + + The connection must define the region endpoint in ``host``, the service principal client ID in + ``login``, the client secret in ``password``, and the Microsoft Entra tenant ID in the + ``tenantId`` extra field. + """ + + conn_type: str = "azure_analysis_services" + conn_name_attr: str = "azure_analysis_services_conn_id" + default_conn_name: str = "azure_analysis_services_default" + hook_name: str = "Azure Analysis Services" + + def __init__( + self, + azure_analysis_services_conn_id: str = default_conn_name, + request_timeout: float = 60, + ) -> None: + super().__init__() + if request_timeout <= 0: + raise ValueError("request_timeout must be greater than zero") + self.azure_analysis_services_conn_id = azure_analysis_services_conn_id + self.request_timeout = request_timeout + self._credential: AsyncTokenCredential | None = None + self._client: httpx.AsyncClient | None = None + + @cached_property + def connection(self) -> Connection: + """Return the Azure Analysis Services connection.""" + return self.get_connection(self.azure_analysis_services_conn_id) + + @classmethod + def get_connection_form_widgets(cls) -> dict[str, Any]: + """Return connection widgets to add to the connection form.""" + from flask_appbuilder.fieldwidgets import BS3TextFieldWidget + from flask_babel import lazy_gettext + from wtforms import StringField + + return { + "tenantId": StringField(lazy_gettext("Tenant ID"), widget=BS3TextFieldWidget()), + } + + @classmethod + def get_ui_field_behaviour(cls) -> dict[str, Any]: + """Return custom field behaviour for the connection form.""" + return { + "hidden_fields": ["schema", "port", "extra"], + "relabeling": { + "host": "Region Endpoint", + "login": "Client ID", + "password": "Client Secret", + }, + "placeholders": { + "host": "westus.asazure.windows.net", + }, + } + + @property + def client(self) -> httpx.AsyncClient: + """Return the shared HTTP client, creating it on first use.""" + if self._client is None: + self._client = httpx.AsyncClient(timeout=self.request_timeout) + return self._client + + def get_conn(self) -> AsyncTokenCredential: + """Return and cache the service principal credential.""" + if self._credential is not None: + return self._credential Review Comment: **[blocker]** ` get_conn() ` returns the auth credential, not the connection/client — inverts the Airflow hook contract. Every Airflow hook that overrides `get_conn()` returns the object callers use to *do work*: `AzureBaseHook` returns the SDK management client, `KiotaRequestAdapterHook` returns the `RequestAdapter`, `PostgresHook` returns the psycopg2 connection, etc. The credential (`ClientSecretCredential`) is an auth building block — it is not the thing operators, sensors, or triggers call to make requests. The symptom is visible in `_get_headers()`: ```python token = await self.get_conn().get_token(TOKEN_SCOPE) ``` `get_conn()` is being called as "give me the credential so I can get a token", but callers expect it to mean "give me the client so I can make requests". The fix is to swap the two: `get_conn()` should return `httpx.AsyncClient` (what is currently the `client` property), and the credential becomes a private helper: ```python def get_conn(self) -> httpx.AsyncClient: """Return the shared HTTP client, creating it on first use.""" if self._client is None: self._client = httpx.AsyncClient(timeout=self.request_timeout) return self._client def _build_credential(self) -> AsyncTokenCredential: connection = self.connection tenant_id = connection.extra_dejson.get("tenantId") if not connection.login: raise ValueError("Client ID is required for Azure Analysis Services authentication") if not connection.password: raise ValueError("Client secret is required for Azure Analysis Services authentication") if not isinstance(tenant_id, str) or not tenant_id: raise ValueError("Tenant ID is required for Azure Analysis Services authentication") return ClientSecretCredential( tenant_id=tenant_id, client_id=connection.login, client_secret=connection.password, ) ``` `_get_headers()` then calls `self._credential.get_token(...)` (lazy-init via `_build_credential()` on first use). The `_credential` field stays exactly as-is in `__init__` and `aclose()`. The public `client` property can be removed — `get_conn()` replaces it. Any caller that currently uses `self.client` (in `get_refresh_status`, `trigger_refresh`) becomes `self.get_conn()`. --- Drafted-by: Claude Sonnet 4.6 (claude-sonnet-4.6); reviewed by @dabla before posting -- 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]
