1# -*- coding: utf-8 -*-
2# Copyright 2026 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17"""OpenTelemetry helpers for resolving and instantiating interceptors."""
18
19from __future__ import annotations
20
21import contextlib
22import urllib.parse
23from typing import TYPE_CHECKING, Any, Callable, Sequence
24
25from google.api_core import _feature_gating_helpers
26from google.api_core.client_options import ClientOptions
27
28try:
29 from opentelemetry.instrumentation.utils import (
30 suppress_instrumentation as _suppress_instrumentation,
31 )
32except ImportError:
33 _suppress_instrumentation = contextlib.nullcontext
34
35if TYPE_CHECKING:
36 # flake8: grpc, trace, and ClientInterceptor are imported only for static analysis and type annotations
37 # The 'noqa: F401' comment avoids flake8 "imported but not used" errors.
38 import grpc # noqa: F401
39 import opentelemetry.trace # noqa: F401
40
41 from google.api_core.grpc_helpers import ClientInterceptor # noqa: F401
42
43_TRACER_PROVIDER = "tracer_provider"
44
45
46def is_otel_capabilities_enabled(
47 client_options: ClientOptions | dict[str, Any] | None = None,
48 env_var: str = "GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED",
49) -> bool:
50 """Checks if OTel capabilities are enabled and installed.
51
52 Args:
53 client_options (Optional[Union[ClientOptions, dict[str, Any]]]): The client options
54 object or dictionary.
55 env_var (str): The environment variable to check for enablement.
56
57 Returns:
58 bool: True if enabled and installed, False otherwise.
59 """
60 is_tracing_enabled = _feature_gating_helpers.resolve_feature_flags(
61 env_var=env_var,
62 feature_key=_TRACER_PROVIDER,
63 configuration=client_options,
64 )
65
66 if is_tracing_enabled:
67 try:
68 import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found] # noqa: F401
69
70 return True
71 except ImportError:
72 pass
73
74 return False
75
76
77def _extract_endpoint_attributes(
78 client_options: ClientOptions | dict[str, Any] | None = None,
79) -> dict[str, Any]:
80 """Extracts server.address, server.port (if non-default), and url.domain from client options if present.
81
82 Args:
83 client_options (Optional[Union[ClientOptions, dict[str, Any]]]): The client options
84 object or dictionary.
85
86 Returns:
87 dict[str, Any]: A dictionary containing url.domain and, if an api_endpoint is configured,
88 server.address and non-default server.port.
89 """
90 attrs: dict[str, Any] = {}
91 endpoint = None
92 universe_domain = None
93
94 if isinstance(client_options, dict):
95 endpoint = client_options.get("api_endpoint")
96 universe_domain = client_options.get("universe_domain")
97 elif client_options is not None:
98 endpoint = getattr(client_options, "api_endpoint", None)
99 universe_domain = getattr(client_options, "universe_domain", None)
100
101 attrs["url.domain"] = universe_domain or "googleapis.com"
102
103 if endpoint and isinstance(endpoint, str):
104 target = endpoint if "//" in endpoint else f"//{endpoint}"
105 parsed = None
106 hostname = None
107 port = None
108 try:
109 parsed = urllib.parse.urlsplit(target)
110 hostname = parsed.hostname
111 port = parsed.port
112 except ValueError:
113 pass
114
115 if hostname:
116 attrs["server.address"] = hostname
117 if port and parsed:
118 scheme = parsed.scheme.lower()
119 is_default_port = (port == 443 and scheme in ("https", "")) or (
120 port == 80 and scheme == "http"
121 )
122 if not is_default_port:
123 attrs["server.port"] = port
124 return attrs
125
126
127def _make_grpc_client_request_hook(
128 endpoint_attrs: dict[str, Any] | None = None,
129) -> Callable[[Any, Any], None]:
130 """Creates an OpenTelemetry gRPC client request hook with optional endpoint attributes.
131
132 Args:
133 endpoint_attrs (Optional[dict[str, Any]]): Optional static endpoint attributes to attach
134 to every span.
135
136 Returns:
137 Callable[[Any, Any], None]: The request hook callback.
138 """
139 static_attrs = dict(endpoint_attrs) if endpoint_attrs else {}
140
141 def client_request_hook(span: Any, request: Any) -> None:
142 if span is None or not getattr(span, "is_recording", lambda: True)():
143 return
144
145 # Upstream opentelemetry-instrumentation-grpc may format span names with a
146 # leading slash (e.g. "/package.Service/Method"). Normalize the span name
147 # and ensure rpc.method is always captured as the clean, fully-qualified name.
148 span_name = getattr(span, "name", None)
149 if isinstance(span_name, str) and span_name:
150 clean_method_name = span_name.lstrip("/")
151 if span_name.startswith("/") and hasattr(span, "update_name"):
152 span.update_name(clean_method_name)
153 span.set_attribute("rpc.method", clean_method_name)
154
155 attrs: dict[str, Any] = {
156 "rpc.system.name": "grpc",
157 }
158 if static_attrs:
159 attrs.update(static_attrs)
160 for key, value in attrs.items():
161 span.set_attribute(key, value)
162
163 return client_request_hook
164
165
166_grpc_client_request_hook = _make_grpc_client_request_hook()
167
168
169def _grpc_client_response_hook(span: Any, response: Any) -> None:
170 """OpenTelemetry gRPC client response hook to record successful response status.
171
172 Upstream ``opentelemetry-instrumentation-grpc`` sets the integer status code
173 ``rpc.grpc.status_code`` (e.g. 0), but does not record the modern string status
174 ``rpc.response.status_code`` (e.g. "OK") required by Cloud Trace and current
175 OpenTelemetry semantic conventions (v1.27.0+).
176
177 This hook enriches successful RPC attempt spans with ``rpc.response.status_code = "OK"``.
178 Errors and non-OK statuses are handled at the Tier 3 method span layer or upstream.
179
180 Upstream handles synchronous and asynchronous invocations differently:
181 - **Synchronous gRPC**: Upstream only invokes the response hook when an RPC call
182 succeeds. On failure, the hook is bypassed entirely.
183 - **Asynchronous gRPC**: Upstream invokes the response hook unconditionally for
184 both successes and failures (passing exception details on error). However, it
185 always marks ``span.status`` with an error status before calling the hook.
186
187 Because of this disparity, this hook checks ``span.status`` to guard against
188 async failure callbacks while allowing synchronous and successful asynchronous
189 calls to be marked "OK".
190
191 Note:
192 If upstream ``opentelemetry-instrumentation-grpc`` adds native support for
193 modern ``rpc.response.status_code`` in future releases, this hook can be retired.
194
195 Args:
196 span (Optional[Any]): The OpenTelemetry span.
197 response (Any): The gRPC response object or details.
198 """
199 if span is None or not getattr(span, "is_recording", lambda: False)():
200 return
201
202 # Guard against upstream async calls that invoke this hook on failures.
203 status = getattr(span, "status", None)
204 status_code = getattr(status, "status_code", None)
205 if (
206 getattr(status_code, "name", None) == "ERROR"
207 or getattr(status_code, "value", None) == 2
208 ):
209 return
210
211 span.set_attribute("rpc.response.status_code", "OK")
212
213
214def _get_tracer_provider(
215 client_options: ClientOptions | dict[str, Any] | None = None,
216) -> opentelemetry.trace.TracerProvider | None:
217 """Extracts the OpenTelemetry tracer provider from client options if present.
218
219 Args:
220 client_options (Optional[Union[ClientOptions, dict[str, Any]]]): The client options
221 object or dictionary.
222
223 Returns:
224 opentelemetry.trace.TracerProvider | None: The tracer provider if present,
225 None otherwise.
226 """
227 if isinstance(client_options, dict):
228 return client_options.get(_TRACER_PROVIDER)
229 elif client_options is not None:
230 return getattr(client_options, _TRACER_PROVIDER, None)
231 return None
232
233
234try:
235 # flake8: `grpc` imported conditionally for runtime interceptor base classes
236 import grpc # noqa: F811
237 from grpc import (
238 StreamStreamClientInterceptor as _SyncStreamStreamClientInterceptor,
239 )
240 from grpc import (
241 StreamUnaryClientInterceptor as _SyncStreamUnaryClientInterceptor,
242 )
243 from grpc import (
244 UnaryStreamClientInterceptor as _SyncUnaryStreamClientInterceptor,
245 )
246 from grpc import (
247 UnaryUnaryClientInterceptor as _SyncUnaryUnaryClientInterceptor,
248 )
249 from grpc.aio import (
250 StreamStreamClientInterceptor as _AsyncStreamStreamClientInterceptor,
251 )
252 from grpc.aio import (
253 StreamUnaryClientInterceptor as _AsyncStreamUnaryClientInterceptor,
254 )
255 from grpc.aio import (
256 UnaryStreamClientInterceptor as _AsyncUnaryStreamClientInterceptor,
257 )
258 from grpc.aio import (
259 UnaryUnaryClientInterceptor as _AsyncUnaryUnaryClientInterceptor,
260 )
261except ImportError: # pragma: NO COVER
262 # mypy: Fallbacks: grpc sentinel when optional grpc is not installed in the environment.
263 # and distinct empty classes avoid duplicate base class 'object' TypeError at runtime.
264 grpc = None # type: ignore[assignment]
265
266 class _SyncUnaryUnaryClientInterceptor: # type: ignore[no-redef]
267 __slots__ = ()
268
269 class _SyncUnaryStreamClientInterceptor: # type: ignore[no-redef]
270 __slots__ = ()
271
272 class _SyncStreamUnaryClientInterceptor: # type: ignore[no-redef]
273 __slots__ = ()
274
275 class _SyncStreamStreamClientInterceptor: # type: ignore[no-redef]
276 __slots__ = ()
277
278 class _AsyncUnaryUnaryClientInterceptor: # type: ignore[no-redef]
279 __slots__ = ()
280
281 class _AsyncUnaryStreamClientInterceptor: # type: ignore[no-redef]
282 __slots__ = ()
283
284 class _AsyncStreamUnaryClientInterceptor: # type: ignore[no-redef]
285 __slots__ = ()
286
287 class _AsyncStreamStreamClientInterceptor: # type: ignore[no-redef]
288 __slots__ = ()
289
290
291class _SuppressingClientInterceptor(
292 _SyncUnaryUnaryClientInterceptor,
293 _SyncUnaryStreamClientInterceptor,
294 _SyncStreamUnaryClientInterceptor,
295 _SyncStreamStreamClientInterceptor,
296):
297 """Client interceptor that suppresses redundant downstream generic auto-instrumentation spans.
298
299 When users enable global OpenTelemetry gRPC auto-instrumentation (e.g. GrpcInstrumentorClient),
300 the underlying channel is wrapped with generic interceptors that emit bare-bones spans.
301 This interceptor wraps downstream calls in OpenTelemetry's native `suppress_instrumentation`
302 context manager so that our feature-rich Google Cloud SDK T4 span is emitted while
303 redundant generic downstream spans are bypassed.
304 """
305
306 __slots__ = ()
307
308 def intercept_unary_unary(
309 self, continuation: Any, client_call_details: Any, request: Any
310 ) -> Any:
311 with _suppress_instrumentation():
312 return continuation(client_call_details, request)
313
314 def intercept_unary_stream(
315 self, continuation: Any, client_call_details: Any, request: Any
316 ) -> Any:
317 with _suppress_instrumentation():
318 return continuation(client_call_details, request)
319
320 def intercept_stream_unary(
321 self, continuation: Any, client_call_details: Any, request_iterator: Any
322 ) -> Any:
323 with _suppress_instrumentation():
324 return continuation(client_call_details, request_iterator)
325
326 def intercept_stream_stream(
327 self, continuation: Any, client_call_details: Any, request_iterator: Any
328 ) -> Any:
329 with _suppress_instrumentation():
330 return continuation(client_call_details, request_iterator)
331
332
333class _AsyncSuppressingClientInterceptor(
334 _AsyncUnaryUnaryClientInterceptor,
335 _AsyncUnaryStreamClientInterceptor,
336 _AsyncStreamUnaryClientInterceptor,
337 _AsyncStreamStreamClientInterceptor,
338):
339 """AsyncIO client interceptor that suppresses redundant downstream generic auto-instrumentation spans."""
340
341 __slots__ = ()
342
343 async def intercept_unary_unary(
344 self, continuation: Any, client_call_details: Any, request: Any
345 ) -> Any:
346 with _suppress_instrumentation():
347 return await continuation(client_call_details, request)
348
349 async def intercept_unary_stream(
350 self, continuation: Any, client_call_details: Any, request: Any
351 ) -> Any:
352 with _suppress_instrumentation():
353 return await continuation(client_call_details, request)
354
355 async def intercept_stream_unary(
356 self, continuation: Any, client_call_details: Any, request_iterator: Any
357 ) -> Any:
358 with _suppress_instrumentation():
359 return await continuation(client_call_details, request_iterator)
360
361 async def intercept_stream_stream(
362 self, continuation: Any, client_call_details: Any, request_iterator: Any
363 ) -> Any:
364 with _suppress_instrumentation():
365 return await continuation(client_call_details, request_iterator)
366
367
368def get_otel_interceptor(
369 client_options: ClientOptions | dict[str, Any] | None = None,
370) -> Callable[[grpc.Channel], grpc.Channel] | None:
371 """Returns an interceptor callable that wraps a sync gRPC channel with OpenTelemetry tracing.
372
373 Args:
374 client_options (Optional[Union[ClientOptions, dict[str, Any]]]): The client options
375 object or dictionary used for feature gating and extracting the tracer provider.
376
377 Returns:
378 Callable[[grpc.Channel], grpc.Channel] | None: An interceptor callable if OpenTelemetry
379 tracing is enabled and installed, None otherwise.
380 """
381 if not is_otel_capabilities_enabled(client_options):
382 return None
383
384 import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found]
385
386 endpoint_attrs = _extract_endpoint_attributes(client_options)
387 request_hook = _make_grpc_client_request_hook(endpoint_attrs)
388
389 interceptor: ClientInterceptor = otel_grpc.client_interceptor(
390 tracer_provider=_get_tracer_provider(client_options),
391 request_hook=request_hook,
392 response_hook=_grpc_client_response_hook,
393 )
394 suppressor = _SuppressingClientInterceptor()
395
396 def otel_interceptor(channel: grpc.Channel) -> grpc.Channel:
397 if grpc is not None:
398 try:
399 channel = grpc.intercept_channel(channel, suppressor)
400 except (AttributeError, TypeError):
401 # Fallback if grpc lacks intercept_channel or custom channel type rejects it.
402 pass
403 return otel_grpc.intercept_channel(channel, interceptor)
404
405 otel_interceptor._is_otel_interceptor = True # type: ignore[attr-defined]
406 return otel_interceptor
407
408
409def get_otel_async_interceptor(
410 client_options: ClientOptions | dict[str, Any] | None = None,
411) -> Sequence[grpc.aio.ClientInterceptor] | None:
412 """Returns async gRPC client interceptors for OpenTelemetry tracing.
413
414 Args:
415 client_options (Optional[Union[ClientOptions, dict[str, Any]]]): The client options
416 object or dictionary used for feature gating and extracting the tracer provider.
417
418 Returns:
419 Sequence[grpc.aio.ClientInterceptor] | None: Instantiated OpenTelemetry async
420 client interceptors if tracing is enabled and installed, None otherwise.
421 """
422 if not is_otel_capabilities_enabled(client_options):
423 return None
424
425 # Ignored by mypy: Optional dependency only loaded if early-return is skipped
426 import opentelemetry.instrumentation.grpc as otel_grpc # type: ignore[import-not-found]
427
428 endpoint_attrs = _extract_endpoint_attributes(client_options)
429 request_hook = _make_grpc_client_request_hook(endpoint_attrs)
430
431 raw_interceptors = otel_grpc.aio_client_interceptors(
432 tracer_provider=_get_tracer_provider(client_options),
433 request_hook=request_hook,
434 response_hook=_grpc_client_response_hook,
435 )
436 interceptors = (
437 list(raw_interceptors)
438 if isinstance(raw_interceptors, (list, tuple))
439 else [raw_interceptors]
440 )
441 interceptors.append(_AsyncSuppressingClientInterceptor())
442
443 return interceptors
444
445
446_CHANNEL_INTERCEPTOR_MAPPING = (
447 ("intercept_unary_unary", "_unary_unary_interceptors"),
448 ("intercept_unary_stream", "_unary_stream_interceptors"),
449 ("intercept_stream_unary", "_stream_unary_interceptors"),
450 ("intercept_stream_stream", "_stream_stream_interceptors"),
451)
452
453
454def apply_otel_async_channel_interceptors(
455 channel: Any,
456 client_options: ClientOptions | dict[str, Any] | Sequence[Any] | None = None,
457) -> Any:
458 """Creates and attaches OpenTelemetry client interceptors to the front of an async gRPC channel.
459
460 In grpc.aio, channels maintain internal interceptor lists evaluated in index order.
461 To ensure Google Cloud SDK telemetry wraps outside downstream interceptors and
462 suppresses ambient generic auto-instrumentation, our interceptors are prepended
463 to the front of the channel's interceptor lists.
464
465 Args:
466 channel: The async gRPC channel to intercept.
467 client_options (Optional[Union[ClientOptions, dict[str, Any], Sequence[Any]]]): The client
468 options used to resolve feature flags and tracer provider, or a sequence of
469 pre-resolved interceptors.
470
471 Returns:
472 The channel with interceptors prepended to its internal lists,
473 or the original channel if tracing is disabled or not installed.
474 """
475 otel_interceptors: Sequence[Any] | None
476 if isinstance(client_options, (ClientOptions, dict)) or client_options is None:
477 otel_interceptors = get_otel_async_interceptor(client_options)
478 elif isinstance(client_options, Sequence):
479 otel_interceptors = client_options
480 else:
481 otel_interceptors = None
482
483 if not otel_interceptors:
484 return channel
485
486 interceptor_list = list(otel_interceptors)
487
488 # Section 1: Typed interceptors - prepend matching interceptors to each
489 # corresponding channel list (unary-unary, unary-stream, etc.) in order.
490 # See note in the docstring about why prepending is important here.
491 for method_name, attr_name in _CHANNEL_INTERCEPTOR_MAPPING:
492 target_list = getattr(channel, attr_name, None)
493 if isinstance(target_list, list):
494 matching = [
495 i
496 for i in interceptor_list
497 if hasattr(i, method_name) and i not in target_list
498 ]
499 if matching:
500 target_list[:0] = matching
501
502 # Section 2: Untyped/generic fallback - prepend any remaining interceptors
503 # lacking standard method names directly to the unary-unary list.
504 unary_list = getattr(channel, "_unary_unary_interceptors", None)
505 if isinstance(unary_list, list):
506 standard_methods = tuple(method for method, _ in _CHANNEL_INTERCEPTOR_MAPPING)
507 fallback_items = [
508 i
509 for i in interceptor_list
510 if not any(hasattr(i, m) for m in standard_methods) and i not in unary_list
511 ]
512 if fallback_items:
513 unary_list[:0] = fallback_items
514
515 return channel
516
517
518_TRACE_CONTEXT_PROPAGATOR: Any = None
519
520
521class _TraceContext:
522 """Context manager for tracing an HTTP wire request with OpenTelemetry.
523
524 Manages span creation, semantic attribute attachment, W3C traceparent injection,
525 and automatic error recording on failure without suppressing caller exceptions.
526
527 Supports two calling conventions:
528 - Pass a single `request` object (such as `requests.PreparedRequest`).
529 - Pass explicit keyword arguments (`method`, `url`, `headers`, `body`, `client_options`).
530 """
531
532 @staticmethod
533 def _get_trace_context_propagator() -> Any:
534 global _TRACE_CONTEXT_PROPAGATOR
535 if _TRACE_CONTEXT_PROPAGATOR is None:
536 from opentelemetry.trace.propagation.tracecontext import ( # type: ignore[import-not-found]
537 TraceContextTextMapPropagator,
538 )
539
540 _TRACE_CONTEXT_PROPAGATOR = TraceContextTextMapPropagator()
541 return _TRACE_CONTEXT_PROPAGATOR
542
543 # The HTTP tracing context manager deliberately supports two distinct invocation styles:
544 # 1. Bundled Request Object: `trace_http_request(request, ...)`
545 # Used when callers already possess an HTTP request instance (such as
546 # requests.PreparedRequest or urllib.request.Request) with `.method`, `.url`, etc.
547 # 2. Unpacked Keyword Arguments: `trace_http_request(method=..., url=..., headers=..., body=...)`
548 # Used by generated GAPIC REST transports (_shared_macros.j2).
549 # In GAPIC templates, requests are assembled from local strings and dictionaries before
550 # hitting the session. Supporting keyword arguments avoids the CPU and memory overhead
551 # of instantiating a throwaway dummy request object on every single RPC execution.
552 @staticmethod
553 def _build_http_span_attributes(
554 request: Any = None,
555 *,
556 method: str | None = None,
557 url: str | None = None,
558 url_template: str | None = None,
559 headers: dict[str, Any] | None = None,
560 body: Any = None,
561 client_options: ClientOptions | dict[str, Any] | None = None,
562 ) -> tuple[str, dict[str, Any], Any]:
563 """Extract span name, semantic attributes dictionary, and resolved headers.
564
565 Supports two calling conventions:
566 - Pass a single `request` object (such as `requests.PreparedRequest`).
567 - Pass explicit keyword arguments (`method`, `url`, `headers`, `body`, `client_options`).
568
569 Returns:
570 tuple[str, dict[str, Any], Any]: A tuple of (span_name, attributes, resolved_headers).
571 """
572 if request is not None:
573 resolved_method = getattr(request, "method", "HTTP") or "HTTP"
574 resolved_url = getattr(request, "url", "") or ""
575 resolved_headers = getattr(request, "headers", None)
576 resolved_body = getattr(request, "body", None)
577 else:
578 resolved_method = method or "HTTP"
579 resolved_url = url or ""
580 resolved_headers = headers
581 resolved_body = body
582
583 resolved_method = resolved_method.upper()
584 endpoint_attrs = _extract_endpoint_attributes(client_options)
585
586 server_address = endpoint_attrs.get("server.address")
587 server_port = endpoint_attrs.get("server.port")
588 if not server_address and resolved_url:
589 try:
590 parsed = urllib.parse.urlsplit(resolved_url)
591 server_address = parsed.hostname
592 if not server_port and parsed.port:
593 server_port = parsed.port
594 except Exception: # Fail-open on malformed URL parsing
595 pass
596
597 span_name = (
598 f"{resolved_method} {url_template}" if url_template else resolved_method
599 )
600 span_attributes: dict[str, Any] = {
601 "rpc.system.name": "http",
602 "http.request.method": resolved_method,
603 "server.address": server_address or "",
604 "server.port": server_port or 443,
605 "url.domain": endpoint_attrs.get("url.domain", "googleapis.com"),
606 }
607 if url_template:
608 span_attributes["url.template"] = url_template
609 if resolved_url:
610 span_attributes["url.full"] = resolved_url
611
612 if resolved_body is not None and isinstance(resolved_body, (bytes, str)):
613 span_attributes["http.request.body.size"] = len(resolved_body)
614
615 return span_name, span_attributes, resolved_headers
616
617 @staticmethod
618 def _extract_http_error_message(response: Any) -> str | None:
619 """Extract a human-readable error message from an HTTP error response."""
620 json_fn = getattr(response, "json", None)
621 if callable(json_fn):
622 try:
623 payload = json_fn()
624 if isinstance(payload, dict):
625 err_obj = payload.get("error")
626 if isinstance(err_obj, dict):
627 msg = err_obj.get("message")
628 if isinstance(msg, str) and msg:
629 return msg
630 elif isinstance(err_obj, str) and err_obj:
631 return err_obj
632 # Intentionally catch broad Exception so telemetry extraction
633 # fails open and never disrupts the caller's RPC flow.
634 except Exception:
635 pass
636 for attr in ("text", "reason"):
637 try:
638 val = getattr(response, attr, None)
639 if isinstance(val, str) and val.strip():
640 return val.strip()
641 # Intentionally catch broad Exception so telemetry extraction
642 # fails open and never disrupts the caller's RPC flow.
643 except Exception:
644 continue
645 return None
646
647 def __init__(
648 self,
649 request: Any = None,
650 *,
651 method: str | None = None,
652 url: str | None = None,
653 url_template: str | None = None,
654 headers: dict[str, Any] | None = None,
655 body: Any = None,
656 client_options: ClientOptions | dict[str, Any] | None = None,
657 ):
658 self._request = request
659 self._method = method
660 self._url = url
661 self._url_template = url_template
662 self._headers = headers
663 self._body = body
664 self._client_options = client_options
665 self._span: Any = None
666 self._parent_span: Any = None
667 self._cm: Any = None
668
669 def record_response(self, response: Any) -> None:
670 """Record HTTP response attributes on the active span.
671
672 Args:
673 response (Any): The HTTP response object (e.g. requests.Response).
674 """
675 span = self._span
676 if span is None or not hasattr(span, "set_attribute"):
677 return
678
679 try:
680 from opentelemetry.trace.status import ( # type: ignore[import-not-found]
681 Status,
682 StatusCode,
683 )
684
685 status_code = getattr(
686 response, "status_code", getattr(response, "status", None)
687 )
688 if status_code is not None:
689 code_int = int(status_code)
690 span.set_attribute("http.response.status_code", code_int)
691 if self._parent_span is not None:
692 self._parent_span.set_attribute(
693 "http.response.status_code", code_int
694 )
695 if code_int >= 400:
696 span.set_status(Status(StatusCode.ERROR))
697 span.set_attribute("error.type", str(code_int))
698 error_msg = self._extract_http_error_message(response)
699 if error_msg:
700 span.set_attribute("status.message", error_msg)
701
702 headers = getattr(response, "headers", None)
703 if headers and "Content-Length" in headers:
704 try:
705 span.set_attribute(
706 "http.response.body.size", int(headers["Content-Length"])
707 )
708 except (ValueError, TypeError):
709 pass
710 elif hasattr(response, "_content") and response._content is not None:
711 try:
712 span.set_attribute(
713 "http.response.body.size", len(response._content)
714 )
715 except Exception:
716 pass
717 except Exception:
718 pass
719
720 # Alias for method name parity with Daniel's suggested convention
721 record_http_response = record_response
722
723 def record_error(self, exc: BaseException | None) -> None:
724 """Record supplemental Cloud Observability error attributes on the active span.
725
726 Upstream OpenTelemetry's ``start_as_current_span`` context manager automatically
727 records the exception event and marks the span status as ERROR when an unhandled
728 exception escapes (via its default ``record_exception=True`` and
729 ``set_status_on_exception=True`` settings).
730
731 This method supplements that base OpenTelemetry behavior by enriching the span
732 with semantic attributes required by Cloud Trace and the Google Cloud Observability
733 specification:
734 - ``error.type``: Low-cardinality status code string (e.g. "404") or exception class name.
735 - ``status.message``: Error description message.
736
737 Args:
738 exc (Optional[BaseException]): The exception raised during dispatch.
739 """
740 span = self._span
741 if span is None or exc is None:
742 return
743
744 try:
745 if hasattr(span, "set_attribute"):
746 status_code = getattr(exc, "code", None) or getattr(
747 exc, "status_code", None
748 )
749 if status_code:
750 span.set_attribute("error.type", str(status_code))
751 else:
752 span.set_attribute("error.type", exc.__class__.__name__)
753 msg = str(exc)
754 if msg:
755 span.set_attribute("status.message", msg)
756 except Exception: # Fail-open on error attribute extraction failure
757 pass
758
759 # Alias for method name parity with Daniel's suggested convention
760 record_http_error = record_error
761
762 def __enter__(self) -> "_TraceContext":
763 if not is_otel_capabilities_enabled(self._client_options):
764 return self
765
766 try:
767 from opentelemetry import trace
768
769 tracer_provider = _get_tracer_provider(self._client_options)
770 if tracer_provider is not None:
771 tracer = tracer_provider.get_tracer("google.api_core")
772 else:
773 tracer = trace.get_tracer("google.api_core")
774
775 span_name, span_attributes, resolved_headers = (
776 self._build_http_span_attributes(
777 self._request,
778 method=self._method,
779 url=self._url,
780 url_template=self._url_template,
781 headers=self._headers,
782 body=self._body,
783 client_options=self._client_options,
784 )
785 )
786
787 parent_span = trace.get_current_span()
788 if (
789 parent_span is not None
790 and getattr(parent_span, "is_recording", lambda: False)() is True
791 and hasattr(parent_span, "set_attribute")
792 ):
793 self._parent_span = parent_span
794 if self._url_template:
795 try:
796 parent_attrs = getattr(parent_span, "attributes", None)
797 if parent_attrs is None or "url.template" not in parent_attrs:
798 parent_span.set_attribute(
799 "url.template", self._url_template
800 )
801 # Intentionally catch broad Exception so telemetry extraction
802 # fails open and never disrupts the caller's RPC flow.
803 except Exception:
804 pass
805
806 self._cm = tracer.start_as_current_span(
807 span_name,
808 kind=trace.SpanKind.CLIENT,
809 attributes=span_attributes,
810 )
811 self._span = self._cm.__enter__()
812
813 if resolved_headers is not None and hasattr(
814 resolved_headers, "__setitem__"
815 ):
816 try:
817 self._get_trace_context_propagator().inject(resolved_headers)
818 except Exception: # Fail-open on header injection failure
819 pass
820
821 return self
822 except Exception:
823 # Fail-open: telemetry failures must never disrupt core RPC execution
824 return self
825
826 def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
827 if self._cm is not None:
828 try:
829 if exc_val is not None and self._span is not None:
830 self.record_error(exc_val)
831 finally:
832 self._cm.__exit__(exc_type, exc_val, exc_tb)
833 # Always return None so caller exceptions are never suppressed
834 return None
835
836
837def trace_http_request(
838 request: Any = None,
839 *,
840 method: str | None = None,
841 url: str | None = None,
842 url_template: str | None = None,
843 headers: dict[str, Any] | None = None,
844 body: Any = None,
845 client_options: ClientOptions | dict[str, Any] | None = None,
846) -> _TraceContext:
847 """Context manager factory for tracing an HTTP wire request with OpenTelemetry.
848
849 Manages span creation, semantic attribute attachment, W3C traceparent injection,
850 and automatic error recording on failure without suppressing caller exceptions.
851
852 Supports two calling conventions:
853 1. Bundled Request Object: `trace_http_request(request, ...)`
854 Used when callers already possess an HTTP request instance (such as
855 `requests.PreparedRequest` or `urllib.request.Request`) with `.method`, `.url`, etc.
856 2. Unpacked Keyword Arguments: `trace_http_request(method=..., url=..., headers=..., body=...)`
857 Used by generated GAPIC REST transports (_shared_macros.j2).
858 In GAPIC templates, requests are assembled from local strings and dictionaries before
859 hitting the session. Supporting keyword arguments avoids the CPU and memory overhead
860 of instantiating a throwaway dummy request object on every single RPC execution.
861
862 Args:
863 request (Optional[Any]): Bundled HTTP request object with .method, .url, .headers.
864 method (Optional[str]): Explicit HTTP method (e.g. "GET", "POST").
865 url (Optional[str]): Fully qualified request URL.
866 url_template (Optional[str]): Parameterized path template for url.template.
867 headers (Optional[dict[str, Any]]): Mutable dictionary of request headers.
868 body (Optional[Any]): Request payload (used for body size calculation).
869 client_options (Optional[Union[ClientOptions, dict[str, Any]]]): Client options
870 containing custom endpoint and tracer provider configurations.
871
872 Returns:
873 _TraceContext: An active context manager managing the HTTP client span.
874 """
875 return _TraceContext(
876 request=request,
877 method=method,
878 url=url,
879 url_template=url_template,
880 headers=headers,
881 body=body,
882 client_options=client_options,
883 )