|
| 1 | +# Copyright 2025 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 | +from typing import Callable, List, Optional, Tuple, TypeVar |
| 15 | + |
| 16 | +from grpc import StatusCode |
| 17 | +from google.api_core.exceptions import GoogleAPICallError |
| 18 | +from google.api_core.retry import RetryFailureReason |
| 19 | +from google.cloud.bigtable.data.exceptions import _MutateRowsIncomplete |
| 20 | +from google.cloud.bigtable.data._helpers import _retry_exception_factory |
| 21 | +from google.cloud.bigtable.data._metrics import ActiveOperationMetric |
| 22 | +from google.cloud.bigtable.data._metrics import OperationState |
| 23 | + |
| 24 | + |
| 25 | +T = TypeVar("T") |
| 26 | + |
| 27 | + |
| 28 | +ExceptionFactoryType = Callable[ |
| 29 | + [List[Exception], RetryFailureReason, Optional[float]], |
| 30 | + Tuple[Exception, Optional[Exception]], |
| 31 | +] |
| 32 | + |
| 33 | + |
| 34 | +def _track_retryable_error( |
| 35 | + operation: ActiveOperationMetric, |
| 36 | +) -> Callable[[Exception], None]: |
| 37 | + """ |
| 38 | + Used as input to api_core.Retry classes, to track when retryable errors are encountered |
| 39 | +
|
| 40 | + Should be passed as on_error callback |
| 41 | + """ |
| 42 | + |
| 43 | + def wrapper(exc: Exception) -> None: |
| 44 | + try: |
| 45 | + # record metadata from failed rpc |
| 46 | + if isinstance(exc, GoogleAPICallError) and exc.errors: |
| 47 | + rpc_error = exc.errors[-1] |
| 48 | + metadata = list(rpc_error.trailing_metadata()) + list( |
| 49 | + rpc_error.initial_metadata() |
| 50 | + ) |
| 51 | + operation.add_response_metadata({k: v for k, v in metadata}) |
| 52 | + except Exception: |
| 53 | + # ignore errors in metadata collection |
| 54 | + pass |
| 55 | + if isinstance(exc, _MutateRowsIncomplete): |
| 56 | + # _MutateRowsIncomplete represents a successful rpc with some failed mutations |
| 57 | + # mark the attempt as successful |
| 58 | + operation.end_attempt_with_status(StatusCode.OK) |
| 59 | + else: |
| 60 | + operation.end_attempt_with_status(exc) |
| 61 | + |
| 62 | + return wrapper |
| 63 | + |
| 64 | + |
| 65 | +def _track_terminal_error( |
| 66 | + operation: ActiveOperationMetric, exception_factory: ExceptionFactoryType |
| 67 | +) -> ExceptionFactoryType: |
| 68 | + """ |
| 69 | + Used as input to api_core.Retry classes, to track when terminal errors are encountered |
| 70 | +
|
| 71 | + Should be used as a wrapper over an exception_factory callback |
| 72 | + """ |
| 73 | + |
| 74 | + def wrapper( |
| 75 | + exc_list: list[Exception], |
| 76 | + reason: RetryFailureReason, |
| 77 | + timeout_val: float | None, |
| 78 | + ) -> tuple[Exception, Exception | None]: |
| 79 | + source_exc, cause_exc = exception_factory(exc_list, reason, timeout_val) |
| 80 | + try: |
| 81 | + # record metadata from failed rpc |
| 82 | + if isinstance(source_exc, GoogleAPICallError) and source_exc.errors: |
| 83 | + rpc_error = source_exc.errors[-1] |
| 84 | + metadata = list(rpc_error.trailing_metadata()) + list( |
| 85 | + rpc_error.initial_metadata() |
| 86 | + ) |
| 87 | + operation.add_response_metadata({k: v for k, v in metadata}) |
| 88 | + except Exception: |
| 89 | + # ignore errors in metadata collection |
| 90 | + pass |
| 91 | + if ( |
| 92 | + reason == RetryFailureReason.TIMEOUT |
| 93 | + and operation.state == OperationState.ACTIVE_ATTEMPT |
| 94 | + and exc_list |
| 95 | + ): |
| 96 | + # record ending attempt for timeout failures |
| 97 | + attempt_exc = exc_list[-1] |
| 98 | + _track_retryable_error(operation)(attempt_exc) |
| 99 | + operation.end_with_status(source_exc) |
| 100 | + return source_exc, cause_exc |
| 101 | + |
| 102 | + return wrapper |
| 103 | + |
| 104 | + |
| 105 | +def tracked_retry( |
| 106 | + *, |
| 107 | + retry_fn: Callable[..., T], |
| 108 | + operation: ActiveOperationMetric, |
| 109 | + **kwargs, |
| 110 | +) -> T: |
| 111 | + """ |
| 112 | + Wrapper for retry_rarget or retry_target_stream, which injects methods to |
| 113 | + track the lifecycle of the retry using the provided ActiveOperationMetric |
| 114 | + """ |
| 115 | + in_exception_factory = kwargs.pop("exception_factory", _retry_exception_factory) |
| 116 | + kwargs.pop("on_error", None) |
| 117 | + kwargs.pop("sleep_generator", None) |
| 118 | + return retry_fn( |
| 119 | + sleep_generator=operation.backoff_generator, |
| 120 | + on_error=_track_retryable_error(operation), |
| 121 | + exception_factory=_track_terminal_error(operation, in_exception_factory), |
| 122 | + **kwargs, |
| 123 | + ) |
0 commit comments