1# Copyright 2017 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Helpers for wrapping low-level gRPC methods with common functionality.
16
17This is used by gapic clients to provide common error mapping, retry, timeout,
18compression, pagination, and long-running operations to gRPC methods.
19"""
20
21import contextlib
22import enum
23import functools
24from typing import Any, List, Optional, Tuple
25
26from google.api_core import _observability, grpc_helpers
27from google.api_core.gapic_v1 import client_info
28from google.api_core.gapic_v1.client_info import METRICS_METADATA_KEY
29from google.api_core.timeout import TimeToDeadlineTimeout
30
31USE_DEFAULT_METADATA = object()
32
33
34class _MethodDefault(enum.Enum):
35 # Uses enum so that pytype/mypy knows that this is the only possible value.
36 # https://stackoverflow.com/a/60605919/101923
37 _DEFAULT_VALUE = object()
38
39
40DEFAULT = _MethodDefault._DEFAULT_VALUE
41"""Sentinel value indicating that a retry, timeout, or compression argument was unspecified,
42so the default should be used."""
43
44_TRANSPORT_KIND_GRPC = "grpc"
45_TRANSPORT_KIND_REST = "rest"
46_DEFAULT_TRANSPORT_KIND = _TRANSPORT_KIND_GRPC
47
48
49def _is_not_none_or_false(value):
50 return value is not None and value is not False
51
52
53def _apply_decorators(func, decorators):
54 """Apply a list of decorators to a given function.
55
56 ``decorators`` may contain items that are ``None`` or ``False`` which will
57 be ignored.
58 """
59 filtered_decorators = filter(_is_not_none_or_false, reversed(decorators))
60
61 for decorator in filtered_decorators:
62 func = decorator(func)
63
64 return func
65
66
67def _deduplicate_metadata_tokens(*headers: str | None) -> str:
68 """
69 Given one or more metadata payload strings, create a combined
70 string with deduplicated tokens, while preserving token order.
71
72 Inputs are expected to contain a set of metadata tokens separated by spaces
73 Example: `gl-python/3.14.0 grpc/1.76.0 gax/2.29.0 gapic/3.8.0 pb/6.33.4`
74
75 Args:
76 *headers: one or more metadata payload strings
77
78 Returns:
79 a single combined payload string
80 """
81 # Split all non-empty headers into individual tokens
82 token_list = " ".join(filter(None, headers)).split()
83 # Deduplicate while preserving order
84 return " ".join(dict.fromkeys(token_list))
85
86
87def _extract_metrics_header(metadata) -> Tuple[str, List[Tuple[str, str]]]:
88 """Extract x-google-api-client header from metadata list.
89
90 Args:
91 metadata (Sequence[Tuple[str, str]]): The metadata to extract from.
92
93 Returns:
94 A tuple containing:
95 - a string representing the header value.
96 - A sequence of remaining metadata tuples.
97 """
98 if not metadata:
99 return "", []
100
101 key_to_find = METRICS_METADATA_KEY
102
103 metric_str = _deduplicate_metadata_tokens(
104 " ".join([v for k, v in metadata if k == key_to_find])
105 )
106 if not metric_str:
107 return "", list(metadata)
108
109 arbitrary_metadata = [item for item in metadata if item[0] != key_to_find]
110 return metric_str, arbitrary_metadata
111
112
113def _extract_rpc_identity(
114 method_name: str,
115) -> Tuple[str, str, str]:
116 """Extract (full_rpc_name, service_name, rpc_method_name) from an explicit method name.
117
118 Args:
119 method_name: Explicit RPC name (e.g. "/google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion").
120
121 Returns:
122 Tuple[str, str, str]: A 3-tuple of (full_rpc_name, service_name, rpc_method_name).
123 """
124 method_str = method_name.lstrip("/")
125 service, _, method = method_str.rpartition("/")
126 return method_str, service, method
127
128
129def _extract_status_code(exc: Optional[BaseException]) -> str:
130 """Extract canonical status code name string from an exception.
131
132 Status code name strings are resolved by inspecting the following locations:
133 * Chained exceptions: Unwraps RetryError or __cause__ to the root exception.
134 * Enum & code attributes: Inspects .grpc_status_code on GoogleAPICallError or .code on gRPC errors.
135 * Integer status codes: Maps raw gRPC integer status codes to canonical enum names.
136 * Fallback: Defaults to the exception class name for standard Python errors.
137
138 Args:
139 exc (Optional[BaseException]): The exception to extract the status code name from.
140
141 Returns:
142 str: The canonical status code name (e.g. "NOT_FOUND", "UNAVAILABLE") or class name.
143 """
144 if exc is None:
145 return ""
146
147 # 1. Unwrap chained exceptions: unwrap RetryError or __cause__ to the root failure
148 target = getattr(exc, "cause", None) or getattr(exc, "__cause__", None) or exc
149
150 # 2. Check enum & code attributes: .grpc_status_code enum or callable/non-callable .code
151 status = getattr(target, "grpc_status_code", None)
152 if status is None and hasattr(target, "code"):
153 try:
154 status = target.code() if callable(target.code) else target.code
155 except Exception:
156 status = None
157
158 name = getattr(status, "name", None)
159 if name:
160 return str(name)
161
162 # 3. Check integer status codes: map raw gRPC integer status codes to canonical enum names
163 if isinstance(status, int):
164 from google.api_core import exceptions
165
166 status = exceptions._INT_TO_GRPC_CODE.get(status, status)
167 return getattr(status, "name", str(status))
168
169 # 4. Fallback: default to the exception class name for standard Python errors
170 return target.__class__.__name__
171
172
173def _extract_error_attributes(exc: Optional[BaseException]) -> dict[str, Any]:
174 """Extract gcp.errors.* and error.type attributes from an exception.
175
176 Error details and ErrorInfo structures are resolved by inspecting the following locations:
177 * Chained exceptions: Unwraps RetryError or __cause__ to the root exception.
178 * GoogleAPICallError attributes: Reads ErrorInfo from ._error_info or .error_info.
179 * Native gRPC trailing metadata: Parses google.rpc.Status binary details from trailing_metadata.
180 * Unified attribute extraction: Extracts domain, reason, and metadata from ErrorInfo or exception attributes.
181
182 Args:
183 exc (Optional[BaseException]): An exception (such as GoogleAPICallError or grpc.RpcError) or ErrorInfo object.
184
185 Returns:
186 dict[str, Any]: Extracted error attributes (e.g. gcp.errors.domain, error.type, gcp.errors.metadata.*).
187 """
188 attrs: dict[str, Any] = {}
189 if exc is None:
190 return attrs
191
192 # 1. Unwrap chained exceptions: unwrap RetryError or __cause__ to the root failure
193 target_exc = getattr(exc, "cause", None) or getattr(exc, "__cause__", None) or exc
194
195 # 2. Check GoogleAPICallError ErrorInfo attributes
196 error_info = getattr(target_exc, "_error_info", None) or getattr(
197 target_exc, "error_info", None
198 )
199
200 # 3. Check native gRPC trailing metadata for binary google.rpc.Status details
201 if error_info is None:
202 rpc_call = (
203 target_exc
204 if hasattr(target_exc, "trailing_metadata")
205 else getattr(target_exc, "response", None)
206 )
207 if rpc_call is not None and hasattr(rpc_call, "trailing_metadata"):
208 try:
209 from google.api_core import exceptions
210
211 _, error_info = exceptions._parse_grpc_error_details(rpc_call)
212 except Exception:
213 pass
214
215 # 4. Unified attribute extraction: extract domain, reason, and metadata from ErrorInfo or exception attributes
216 http_response = getattr(target_exc, "response", None)
217 http_status = (
218 getattr(http_response, "status_code", getattr(http_response, "status", None))
219 if http_response is not None and not hasattr(http_response, "trailing_metadata")
220 else None
221 )
222
223 source = error_info or target_exc
224 if isinstance(source, dict):
225 domain = source.get("domain")
226 reason = source.get("reason")
227 metadata = source.get("metadata")
228 else:
229 domain = getattr(source, "domain", None)
230 reason = getattr(source, "reason", None)
231 metadata = getattr(source, "metadata", None)
232
233 if domain:
234 attrs["gcp.errors.domain"] = domain
235 if reason:
236 attrs["error.type"] = reason
237 elif isinstance(http_status, int):
238 attrs["error.type"] = str(http_status)
239 else:
240 # Fallback per OpenTelemetry Semantic Conventions: every failed span should record
241 # a low-cardinality error.type. Use canonical status code name or exception class name.
242 status_code = _extract_status_code(target_exc)
243 attrs["error.type"] = status_code or target_exc.__class__.__name__
244 if metadata:
245 for k, v in metadata.items():
246 attrs[f"gcp.errors.metadata.{k}"] = str(v)
247
248 # 5. Extract human-readable error description for cross-language PRD parity
249 message = (
250 _observability._TraceContext._extract_http_error_message(http_response)
251 if http_status is not None
252 else None
253 )
254 if not message:
255 message = getattr(target_exc, "message", None)
256 if not message and hasattr(target_exc, "details"):
257 details = target_exc.details
258 message = details() if callable(details) else details
259 if not message and isinstance(target_exc, BaseException):
260 message = str(target_exc)
261 if message:
262 attrs["status.message"] = str(message)
263
264 return attrs
265
266
267class _GapicCallable(object):
268 """Callable that applies retry, timeout, and metadata logic.
269
270 Args:
271 target (Callable): The low-level RPC method.
272 retry (google.api_core.retry.Retry): The default retry for the
273 callable. If ``None``, this callable will not retry by default
274 timeout (google.api_core.timeout.Timeout): The default timeout for the
275 callable (i.e. duration of time within which an RPC must terminate
276 after its start, not to be confused with deadline). If ``None``,
277 this callable will not specify a timeout argument to the low-level
278 RPC method.
279 compression (grpc.Compression): The default compression for the callable.
280 If ``None``, this callable will not specify a compression argument
281 to the low-level RPC method.
282 metadata (Sequence[Tuple[str, str]]): Additional metadata that is
283 provided to the RPC method on every invocation. This is merged with
284 any metadata specified during invocation. If ``None``, no
285 additional metadata will be passed to the RPC method.
286 client_options
287 (Optional[google.api_core.client_options.ClientOptions]):
288 Client options used to configure client-level behavior, such as
289 custom OpenTelemetry tracer providers. Defaults to None.
290 method_name (Optional[str]): The optional explicit full RPC method name
291 (e.g. "/google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion").
292 is_streaming (bool): Whether the RPC method is streaming. Defaults to False.
293 Note: Streaming methods do not currently generate Tier 3 observability spans.
294 client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]):
295 Client information used for metadata headers. Defaults to None.
296 kind (str): The transport kind for the RPC method. Defaults to "grpc".
297 Allowed values for OpenTelemetry method tracing are "grpc" and "rest".
298 """
299
300 _SUPPORTED_TRACING_KINDS = (_TRANSPORT_KIND_GRPC, _TRANSPORT_KIND_REST)
301
302 def __init__(
303 self,
304 target,
305 retry,
306 timeout,
307 compression,
308 metadata=None,
309 client_options=None,
310 method_name=None,
311 is_streaming=False,
312 client_info=None,
313 kind=_DEFAULT_TRANSPORT_KIND,
314 ):
315 self._target = target
316 self._retry = retry
317 self._timeout = timeout
318 self._compression = compression
319
320 # Pre-extract the x-goog-api-client header from the initialized metadata.
321 self._x_goog_api_client, remaining = _extract_metrics_header(metadata)
322 self._static_metadata = tuple(remaining)
323 if self._x_goog_api_client:
324 self._default_metadata = (
325 (METRICS_METADATA_KEY, self._x_goog_api_client),
326 *self._static_metadata,
327 )
328 else:
329 self._default_metadata = self._static_metadata
330
331 # Configure the OpenTelemetry span factory once at initialization.
332 # For now, method tracing is gated to non-streaming calls where an explicit method_name is provided.
333 self._start_span_fn = None
334 if (
335 not is_streaming
336 and kind in self._SUPPORTED_TRACING_KINDS
337 and method_name is not None
338 and _observability.is_otel_capabilities_enabled(client_options)
339 ):
340 try:
341 from opentelemetry import trace
342
343 tracer_provider = None
344 if isinstance(client_options, dict):
345 tracer_provider = client_options.get("tracer_provider")
346 elif client_options is not None:
347 tracer_provider = getattr(client_options, "tracer_provider", None)
348 if tracer_provider is not None:
349 tracer = tracer_provider.get_tracer("google.api_core")
350 else:
351 tracer = trace.get_tracer("google.api_core")
352
353 span_name, _, _ = _extract_rpc_identity(method_name)
354 endpoint_attrs = _observability._extract_endpoint_attributes(
355 client_options
356 )
357 span_attributes = {
358 "rpc.system.name": "http" if kind.startswith("rest") else "grpc",
359 "rpc.method": span_name,
360 **endpoint_attrs,
361 }
362 self._start_span_fn = functools.partial(
363 tracer.start_as_current_span,
364 span_name,
365 kind=trace.SpanKind.INTERNAL,
366 attributes=span_attributes,
367 )
368 except (ImportError, AttributeError, TypeError):
369 # Gracefully disable tracing if OpenTelemetry or custom provider fails
370 self._start_span_fn = None
371
372 def _prepare_call(self, timeout, retry, compression, kwargs):
373 if retry is DEFAULT:
374 retry = self._retry
375
376 if timeout is DEFAULT:
377 timeout = self._timeout
378
379 if compression is DEFAULT:
380 compression = self._compression
381
382 if isinstance(timeout, (int, float)):
383 timeout = TimeToDeadlineTimeout(timeout=timeout)
384
385 # Apply all applicable decorators.
386 wrapped_func = _apply_decorators(self._target, [retry, timeout])
387
388 if user_metadata := kwargs.get("metadata"):
389 # Add the user agent metadata to the call.
390 final_metadata = list(self._static_metadata)
391 user_x_goog, remaining = _extract_metrics_header(user_metadata)
392
393 merged_header = _deduplicate_metadata_tokens(
394 self._x_goog_api_client, user_x_goog
395 )
396 if merged_header:
397 final_metadata.append((METRICS_METADATA_KEY, merged_header))
398 final_metadata.extend(remaining)
399 kwargs["metadata"] = final_metadata
400 elif self._default_metadata:
401 kwargs["metadata"] = self._default_metadata
402
403 if compression is not None:
404 kwargs["compression"] = compression
405
406 return wrapped_func
407
408 @contextlib.contextmanager
409 def _trace_span(self):
410 span_cm = contextlib.nullcontext()
411 if self._start_span_fn is not None:
412 try:
413 span_cm = self._start_span_fn()
414 except Exception:
415 # Fail-open: proceed without span if tracing initialization fails
416 span_cm = contextlib.nullcontext()
417
418 with span_cm as span:
419 try:
420 yield
421 if span is not None and hasattr(span, "set_attribute"):
422 span.set_attribute("rpc.response.status_code", "OK")
423 except (KeyboardInterrupt, SystemExit, GeneratorExit):
424 raise
425 except BaseException as exc:
426 if span is not None and hasattr(span, "set_attribute"):
427 span.set_attribute(
428 "rpc.response.status_code", _extract_status_code(exc)
429 )
430 for k, v in _extract_error_attributes(exc).items():
431 span.set_attribute(k, v)
432 raise
433
434 def __call__(
435 self, *args, timeout=DEFAULT, retry=DEFAULT, compression=DEFAULT, **kwargs
436 ):
437 """Invoke the low-level RPC with retry, timeout, compression, and metadata."""
438 wrapped_func = self._prepare_call(timeout, retry, compression, kwargs)
439 with self._trace_span():
440 return wrapped_func(*args, **kwargs)
441
442
443def wrap_method(
444 func,
445 default_retry=None,
446 default_timeout=None,
447 default_compression=None,
448 client_info=client_info.DEFAULT_CLIENT_INFO,
449 *,
450 with_call=False,
451 client_options=None,
452 method_name=None,
453 is_streaming=False,
454 kind=_DEFAULT_TRANSPORT_KIND,
455):
456 """Wrap an RPC method with common behavior.
457
458 This applies common error wrapping, retry, timeout, and compression behavior to a function.
459 The wrapped function will take optional ``retry``, ``timeout``, and ``compression``
460 arguments.
461
462 For example::
463
464 import google.api_core.gapic_v1.method
465 from google.api_core import retry
466 from google.api_core import timeout
467 from grpc import Compression
468
469 # The original RPC method.
470 def get_topic(name, timeout=None):
471 request = publisher_v2.GetTopicRequest(name=name)
472 return publisher_stub.GetTopic(request, timeout=timeout)
473
474 default_retry = retry.Retry(deadline=60)
475 default_timeout = timeout.Timeout(deadline=60)
476 default_compression = Compression.NoCompression
477 wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method(
478 get_topic, default_retry)
479
480 # Execute get_topic with default retry and timeout:
481 response = wrapped_get_topic()
482
483 # Execute get_topic without doing any retying but with the default
484 # timeout:
485 response = wrapped_get_topic(retry=None)
486
487 # Execute get_topic but only retry on 5xx errors:
488 my_retry = retry.Retry(retry.if_exception_type(
489 exceptions.InternalServerError))
490 response = wrapped_get_topic(retry=my_retry)
491
492 The way this works is by late-wrapping the given function with the retry
493 and timeout decorators. Essentially, when ``wrapped_get_topic()`` is
494 called:
495
496 * ``get_topic()`` is first wrapped with the ``timeout`` into
497 ``get_topic_with_timeout``.
498 * ``get_topic_with_timeout`` is wrapped with the ``retry`` into
499 ``get_topic_with_timeout_and_retry()``.
500 * The final ``get_topic_with_timeout_and_retry`` is called passing through
501 the ``args`` and ``kwargs``.
502
503 The callstack is therefore::
504
505 method.__call__() ->
506 Retry.__call__() ->
507 Timeout.__call__() ->
508 wrap_errors() ->
509 get_topic()
510
511 Note that if ``timeout`` or ``retry`` is ``None``, then they are not
512 applied to the function. For example,
513 ``wrapped_get_topic(timeout=None, retry=None)`` is more or less
514 equivalent to just calling ``get_topic`` but with error re-mapping.
515
516 Args:
517 func (Callable[Any]): The function to wrap. It should accept an
518 optional ``timeout`` argument. If ``metadata`` is not ``None``, it
519 should accept a ``metadata`` argument.
520 default_retry (Optional[google.api_core.Retry]): The default retry
521 strategy. If ``None``, the method will not retry by default.
522 default_timeout (Optional[google.api_core.Timeout]): The default
523 timeout strategy. Can also be specified as an int or float. If
524 ``None``, the method will not have timeout specified by default.
525 default_compression (Optional[grpc.Compression]): The default
526 grpc.Compression. If ``None``, the method will not have
527 compression specified by default.
528 client_info
529 (Optional[google.api_core.gapic_v1.client_info.ClientInfo]):
530 Client information used to create a user-agent string that's
531 passed as gRPC metadata to the method. If unspecified, then
532 a sane default will be used. If ``None``, then no user agent
533 metadata will be provided to the RPC method.
534 with_call (bool): If True, wrapped grpc.UnaryUnaryMulticallables will
535 return a tuple of (response, grpc.Call) instead of just the response.
536 This is useful for extracting trailing metadata from unary calls.
537 Defaults to False.
538 client_options
539 (Optional[google.api_core.client_options.ClientOptions]):
540 Client options used to configure client-level behavior, such as
541 custom OpenTelemetry tracer providers. Defaults to None.
542 method_name (Optional[str]): Optional explicit full RPC method name
543 (e.g. "/google.cloud.secretmanager.v1.SecretManagerService/AccessSecretVersion").
544 Used to identify the RPC for observability.
545 is_streaming (bool): Whether the RPC method is streaming. Defaults to False.
546 Streaming methods are currently gated and do not generate Tier 3 spans.
547 kind (str): The transport kind for the RPC method. Defaults to "grpc".
548 Allowed values for OpenTelemetry method tracing are "grpc" and "rest".
549
550 Returns:
551 Callable: A new callable that takes optional ``retry``, ``timeout``,
552 and ``compression``
553 arguments and applies the common error mapping, retry, timeout, compression,
554 and metadata behavior to the low-level RPC method.
555 """
556 if with_call:
557 try:
558 func = func.with_call
559 except AttributeError as exc:
560 raise ValueError(
561 "with_call=True is only supported for unary calls."
562 ) from exc
563 func = grpc_helpers.wrap_errors(func)
564 if client_info is not None:
565 user_agent_metadata = [client_info.to_grpc_metadata()]
566 else:
567 user_agent_metadata = None
568
569 return functools.wraps(func)(
570 _GapicCallable(
571 func,
572 default_retry,
573 default_timeout,
574 default_compression,
575 metadata=user_agent_metadata,
576 client_options=client_options,
577 method_name=method_name,
578 is_streaming=is_streaming,
579 client_info=client_info,
580 kind=kind,
581 )
582 )