klisitsynaws commented on code in PR #67878: URL: https://github.com/apache/airflow/pull/67878#discussion_r3357503793
########## airflow-core/src/airflow/dag_processing/api_client.py: ########## @@ -0,0 +1,278 @@ +# 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. +"""HTTP client used by the DAG processor to persist parse results via the API (AIP-92).""" + +from __future__ import annotations + +import logging +import time +from datetime import datetime +from importlib import import_module +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +import httpx + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + + from airflow.dag_processing.processor import DagFileParsingResult + +log = logging.getLogger(__name__) + +# Connection-level retries are safe for every request (the request never reached the server), +# so they are applied uniformly by the transport. Application-level retries (5xx / read timeout) +# are only added for idempotent calls; claim/delete calls must not be retried after the request +# may have been processed server-side, or callbacks/priority-requests could be silently lost. +_CONNECT_RETRIES = 3 +_TRANSIENT_RETRIES = 3 +_TRANSIENT_BACKOFF = 0.5 + + +def _parse_iso_datetime(value: str) -> datetime: + """ + Parse an ISO-8601 timestamp from the API server, tolerating a trailing ``Z``. + + The server emits UTC timestamps with a ``Z`` designator (e.g. ``2026-06-03T03:52:13.938753Z``), + but ``datetime.fromisoformat`` only accepts ``Z`` on Python 3.11+. Normalise it to an explicit + offset so parsing works on the oldest supported runtime (3.10). + """ + if value.endswith("Z"): + value = f"{value[:-1]}+00:00" + return datetime.fromisoformat(value) + + +# How long a token read from the provisioned file is reused before re-reading. Keeps the tight +# parse loop from stat-ing the file on every request while still picking up a rotated token quickly. +_TOKEN_CACHE_TTL = 30.0 + + +class _CallableBearerAuth(httpx.Auth): + """ + Attach a bearer token read from a callable, re-reading it as the deployment rotates it. + + The DAG processor never holds the signing key; a trusted component provisions its token to a + file (``[dag_processor] api_token_path``) and rotates it there before expiry. Reading the token + per-request (rather than baking it into the client once) lets a long-running processor pick up a + rotated token without restarting. The value is cached for ``_TOKEN_CACHE_TTL`` to avoid a file + read on every call; a ``401`` forces an immediate re-read and one retry, so a rotation that lands + mid-window is honoured without waiting out the cache. + """ + + def __init__(self, token_getter: Callable[[], str | None], *, cache_ttl: float = _TOKEN_CACHE_TTL): + self._token_getter = token_getter + self._cache_ttl = cache_ttl + self._cached: str | None = None + self._cached_at = 0.0 + + def _token(self, *, refresh: bool = False) -> str | None: + now = time.monotonic() + if refresh or self._cached is None or now - self._cached_at >= self._cache_ttl: + self._cached = self._token_getter() + self._cached_at = now + return self._cached + + def auth_flow(self, request: httpx.Request): + token = self._token() + if token: + request.headers["Authorization"] = f"Bearer {token}" + response = yield request + if response.status_code == 401: + # The token may have rotated on disk since the cached read; re-read and retry once. + fresh = self._token(refresh=True) + if fresh and fresh != token: + request.headers["Authorization"] = f"Bearer {fresh}" + yield request + + +class DagProcessingApiClient: Review Comment: Would it be beneficial to use API data models declared in `datamodels.py` here as type hints? Otherwise those are just free-form payloads and it's anyone's guess if they are current. -- 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]
