pierrejeambrun commented on code in PR #64523: URL: https://github.com/apache/airflow/pull/64523#discussion_r3796063924
########## airflow-core/src/airflow/api_fastapi/common/http_metrics.py: ########## @@ -0,0 +1,149 @@ +# 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 API metrics middleware.""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +import structlog + +from airflow._shared.observability.metrics.stats import Stats + +if TYPE_CHECKING: + from starlette.types import ASGIApp, Message, Receive, Scope, Send + +logger = structlog.get_logger(logger_name="http.metrics") + +_ROUTE_PATHS_BY_ROUTER_ID: dict[int, dict[object, str]] = {} +_API_METRICS_PATH_PREFIXES = ("/api/v2", "/ui") + + +def _is_api_metrics_path(path: str) -> bool: + return any(path == prefix or path.startswith(f"{prefix}/") for prefix in _API_METRICS_PATH_PREFIXES) + + +def _get_status_family(status_code: int) -> str: + return f"{status_code // 100}xx" + + +def _get_route_template(scope: Scope) -> str: + route = scope.get("route") Review Comment: Heads up — I think the tests and production take different branches here. FastAPI sets `scope["route"]`, so in the real app this returns on the `scope.get("route")` line and the `router.routes` fallback below never runs. But `test_http_metrics.py` builds a plain Starlette app, which doesn't set `scope["route"]` — so the tests only ever hit the fallback, and the path that actually runs in production is untested. Could we build the test app with FastAPI (or add an integration test against the core_api app) so route extraction is covered as it really behaves? And if `scope["route"]` is always set under FastAPI, the fallback + `_ROUTE_PATHS_BY_ROUTER_ID` cache may be removable. ########## airflow-core/src/airflow/api_fastapi/common/http_metrics.py: ########## @@ -0,0 +1,149 @@ +# 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 API metrics middleware.""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +import structlog + +from airflow._shared.observability.metrics.stats import Stats + +if TYPE_CHECKING: + from starlette.types import ASGIApp, Message, Receive, Scope, Send + +logger = structlog.get_logger(logger_name="http.metrics") + +_ROUTE_PATHS_BY_ROUTER_ID: dict[int, dict[object, str]] = {} +_API_METRICS_PATH_PREFIXES = ("/api/v2", "/ui") + + +def _is_api_metrics_path(path: str) -> bool: + return any(path == prefix or path.startswith(f"{prefix}/") for prefix in _API_METRICS_PATH_PREFIXES) + + +def _get_status_family(status_code: int) -> str: + return f"{status_code // 100}xx" + + +def _get_route_template(scope: Scope) -> str: + route = scope.get("route") + route_path = getattr(route, "path", None) + if isinstance(route_path, str) and route_path: + return route_path + + router = scope.get("router") + endpoint = scope.get("endpoint") + if router is not None and endpoint is not None: + route_paths = _ROUTE_PATHS_BY_ROUTER_ID.get(id(router)) + if route_paths is None: + route_paths = { + candidate_endpoint: candidate_route_path + for candidate_route in getattr(router, "routes", ()) + for candidate_endpoint, candidate_route_path in [ + ( + getattr(candidate_route, "endpoint", None), + getattr(candidate_route, "path", None), + ) + ] + if candidate_endpoint is not None + and isinstance(candidate_route_path, str) + and candidate_route_path + } + _ROUTE_PATHS_BY_ROUTER_ID[id(router)] = route_paths + + endpoint_route_path = route_paths.get(endpoint) + if isinstance(endpoint_route_path, str) and endpoint_route_path: + return endpoint_route_path + + return "unmatched" + + +def _emit_api_metrics( + *, + scope: Scope, + path: str, + method: str, + status_code: int, + duration_us: int, +) -> None: + if not _is_api_metrics_path(path): + return + + # Keep tags bounded so API metrics remain usable across supported backends. + tags = { + "method": method, + "route": _get_route_template(scope), + "status_family": _get_status_family(status_code), + } + duration_ms = duration_us / 1000.0 + + Stats.incr("http_requests_total", tags=tags) + Stats.timing("http_request_duration_seconds", duration_ms, tags=tags) Review Comment: The value here is milliseconds (`Stats.timing` records ms across the backends, and the metric's yaml description says "Milliseconds…"), but the name is `http_request_duration_seconds`. Anyone reading a `_seconds` metric will be off by 1000×. Could we rename to `http_request_duration_milliseconds` (or `_ms`)? Minor: the test asserts the value as `mock.ANY`, so it won't catch this — worth pinning the unit there. ########## airflow-core/src/airflow/api_fastapi/common/http_metrics.py: ########## @@ -0,0 +1,149 @@ +# 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 API metrics middleware.""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +import structlog + +from airflow._shared.observability.metrics.stats import Stats + +if TYPE_CHECKING: + from starlette.types import ASGIApp, Message, Receive, Scope, Send + +logger = structlog.get_logger(logger_name="http.metrics") + +_ROUTE_PATHS_BY_ROUTER_ID: dict[int, dict[object, str]] = {} Review Comment: Minor, and moot if the fallback goes away per the other comment: this module-level cache is keyed by `id(router)`, which can be reused after GC. Routers live for the app lifetime so it's unlikely to bite, but a `WeakKeyDictionary` (or dropping the fallback) would remove the footgun. -- 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]
