Repository navigation
feat(gapic-generator): wire async REST total_attempts and async trace response recording #19154
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: feat/otel-logging-m3-s7-grpc-rpc-method
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -77,6 +77,11 @@ else: # pragma: NO COVER | |
|
|
||
| record_http_response = record_response | ||
|
|
||
| async def record_response_async(self, response: Any) -> None: | ||
| pass | ||
|
|
||
| record_http_response_async = record_response_async | ||
|
|
||
| def record_error(self, exc: BaseException | None) -> None: | ||
| pass | ||
|
|
||
|
|
@@ -89,6 +94,14 @@ else: # pragma: NO COVER | |
| def trace_http_request(*args: Any, **kwargs: Any) -> _FallbackTraceContext: # type: ignore[misc] | ||
| return _FallbackTraceContext() | ||
|
|
||
|
|
||
| async def record_http_response_async(trace_ctx: Any, response: Any) -> None: | ||
| """Records an async HTTP response with fallback for older google-api-core.""" | ||
| if hasattr(trace_ctx, "record_response_async"): | ||
| await trace_ctx.record_response_async(response) | ||
| else: | ||
| trace_ctx.record_response(response) | ||
|
|
||
| # The `kind` parameter in gapic_v1.method_async.wrap_method was introduced in | ||
| # google-api-core 2.29.0 (PR #688) alongside _DEFAULT_ASYNC_TRANSPORT_KIND to prevent | ||
| # async REST callables from being wrapped with gRPC error handlers. | ||
|
|
@@ -108,6 +121,36 @@ SUPPORTS_DEFAULT_HOST = ( | |
| "default_host" in inspect.signature(gapic_v1.method.wrap_method).parameters | ||
| ) | ||
|
|
||
| # google-auth >= 2.49.0 accepts `total_attempts` on AsyncAuthorizedSession | ||
| # methods so GAPIC can disable google-auth's internal 5xx status-code retries | ||
| # and let GAPIC retry and observability wrappers observe every wire attempt. | ||
| _AsyncAuthorizedSession: Any = None | ||
| try: | ||
| from google.auth.aio.transport import sessions as _ga_async_sessions | ||
|
|
||
| _AsyncAuthorizedSession = getattr( # pragma: NO COVER | ||
| _ga_async_sessions, "AsyncAuthorizedSession", None | ||
| ) | ||
| except ImportError: # pragma: NO COVER | ||
| _AsyncAuthorizedSession = None | ||
|
|
||
| ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS = ( | ||
| _AsyncAuthorizedSession is not None | ||
| and "total_attempts" | ||
| in inspect.signature(_AsyncAuthorizedSession.request).parameters | ||
| ) | ||
|
Comment on lines
+137
to
+141
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Using |
||
|
|
||
|
|
||
| def async_rest_request_kwargs(session: Any) -> Dict[str, Any]: | ||
| """Returns extra kwargs for async REST dispatch when supported by google-auth.""" | ||
| if ( | ||
| ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS | ||
| and _AsyncAuthorizedSession is not None | ||
| and isinstance(session, _AsyncAuthorizedSession) | ||
| ): | ||
| return {"total_attempts": 1} | ||
| return {} | ||
|
|
||
| try: | ||
| from google.api_core import grpc_helpers | ||
| except ImportError: # pragma: NO COVER | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ google-api-core has the functions in `_compat.py.j2`. #} | |
| {# TODO(https://github.com/googleapis/google-cloud-python/issues/17883): | ||
| Backfill compatibility functions tests being removed from the client layer. #} | ||
|
|
||
| import asyncio | ||
| import json | ||
| import pytest | ||
| import os | ||
|
|
@@ -31,6 +32,8 @@ from {{package_path}}._compat import ( | |
| read_environment_variables, | ||
| _observability, | ||
| trace_http_request, | ||
| record_http_response_async, | ||
| async_rest_request_kwargs, | ||
| apply_channel_interceptors, | ||
| apply_async_channel_interceptors, | ||
| ) | ||
|
|
@@ -591,12 +594,41 @@ def test_observability_compat_fallback(monkeypatch): | |
| assert reloaded._observability is None | ||
| with reloaded.trace_http_request(method="GET", url="https://example.com") as trace_ctx: | ||
| trace_ctx.record_response(None) | ||
| asyncio.run(trace_ctx.record_response_async(None)) | ||
| finally: | ||
| # Restore _compat to normal environment | ||
| monkeypatch.undo() | ||
| importlib.reload(_compat) | ||
|
|
||
|
|
||
| def test_record_http_response_async_compat(): | ||
| resp = mock.Mock() | ||
|
|
||
| async_ctx = mock.Mock(spec_set=["record_response_async"]) | ||
| async_ctx.record_response_async = mock.AsyncMock() | ||
| asyncio.run(record_http_response_async(async_ctx, resp)) | ||
| async_ctx.record_response_async.assert_awaited_once_with(resp) | ||
|
|
||
| sync_only_ctx = mock.Mock(spec_set=["record_response"]) | ||
| asyncio.run(record_http_response_async(sync_only_ctx, resp)) | ||
| sync_only_ctx.record_response.assert_called_once_with(resp) | ||
|
Comment on lines
+604
to
+614
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Update the unit test to verify that |
||
|
|
||
|
|
||
| def test_async_rest_request_kwargs_compat(monkeypatch): | ||
| from {{package_path}} import _compat | ||
|
|
||
| class _FakeAsyncSession: | ||
| pass | ||
|
|
||
| monkeypatch.setattr(_compat, "_AsyncAuthorizedSession", _FakeAsyncSession) | ||
| monkeypatch.setattr(_compat, "ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS", True) | ||
| assert async_rest_request_kwargs(_FakeAsyncSession()) == {"total_attempts": 1} | ||
| assert async_rest_request_kwargs(object()) == {} | ||
|
|
||
| monkeypatch.setattr(_compat, "ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS", False) | ||
| assert async_rest_request_kwargs(_FakeAsyncSession()) == {} | ||
|
|
||
|
|
||
| def test_apply_channel_interceptors_compat(): | ||
| # apply_channel_interceptors is exposed from _compat and callable | ||
| dummy_channel = mock.Mock() | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To enforce defensive programming and prevent potential
AttributeErrorexceptions, we should check iftrace_ctxisNonebefore attempting to access its attributes or methods.