Repository navigation
feat(gapic-generator): wire async REST total_attempts and async trace response recording - #19154
chalmerlowe wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces async REST support and compatibility utilities for older versions of google-api-core and google-auth, specifically adding record_http_response_async and async_rest_request_kwargs to disable internal retries on AsyncAuthorizedSession. These changes are integrated across templates, shared macros, and generated golden files, alongside corresponding unit tests. Feedback recommends adding a defensive None check for trace_ctx in record_http_response_async (with an accompanying unit test) and wrapping the import-time inspect.signature call in a try...except block to prevent potential failures.
| 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) |
There was a problem hiding this comment.
To enforce defensive programming and prevent potential AttributeError exceptions, we should check if trace_ctx is None before attempting to access its attributes or methods.
async def record_http_response_async(trace_ctx: Any, response: Any) -> None:\n \"\"\"Records an async HTTP response with fallback for older google-api-core.\"\"\"\n if trace_ctx is None:\n return\n if hasattr(trace_ctx, \"record_response_async\"):\n await trace_ctx.record_response_async(response)\n else:\n trace_ctx.record_response(response)
| ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS = ( | ||
| _AsyncAuthorizedSession is not None | ||
| and "total_attempts" | ||
| in inspect.signature(_AsyncAuthorizedSession.request).parameters | ||
| ) |
There was a problem hiding this comment.
Using inspect.signature on third-party library methods at module import time can raise ValueError or TypeError in certain environments (e.g., when the library is mocked, has C-extensions, or has unexpected wrappers). Wrapping this check in a try...except (ValueError, TypeError) block ensures that the module imports successfully even if the signature inspection fails.
try:\n ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS = (\n _AsyncAuthorizedSession is not None\n and \"total_attempts\"\n in inspect.signature(_AsyncAuthorizedSession.request).parameters\n )\nexcept (ValueError, TypeError):\n ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS = False
| 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) |
There was a problem hiding this comment.
Update the unit test to verify that record_http_response_async handles a None trace_ctx gracefully without raising any exceptions.
def test_record_http_response_async_compat():\n resp = mock.Mock()\n\n async_ctx = mock.Mock(spec_set=[\"record_response_async\"])\n async_ctx.record_response_async = mock.AsyncMock()\n asyncio.run(record_http_response_async(async_ctx, resp))\n async_ctx.record_response_async.assert_awaited_once_with(resp)\n\n sync_only_ctx = mock.Mock(spec_set=[\"record_response\"])\n asyncio.run(record_http_response_async(sync_only_ctx, resp))\n sync_only_ctx.record_response.assert_called_once_with(resp)\n\n # Test with None trace_ctx\n asyncio.run(record_http_response_async(None, resp))
fd3ad4c to
c45a48b
Compare
… response recording
c45a48b to
b47d72d
Compare
873d998 to
367071a
Compare
Problem / Context
End-to-end compliance testing of the experimental
rest_asynciotransport surfaced two gaps in how generated async REST transports dispatch HTTP requests and report failed responses togoogle-api-core's observability hooks:google-auth503retries: Unlike synchronousAuthorizedSession,google.auth.aio.transport.sessions.AsyncAuthorizedSessionwraps every outgoing call in an internal 3-attempt retry loop on(500, 503, 504, 408, 429)unlesstotal_attempts=1is passed (google-auth >= 2.49.0). Because generated async REST transports did not passtotal_attempts=1, transient503responses were silently retried insidegoogle-authbefore GAPIC'sAsyncRetry,T4spans, orL4attempt logs could observe them._shared_macros.j2called synchronoustrace_ctx.record_response(response)onrest_asyncioresponses. Becauseaiohttpresponse bodies must be awaited viaawait response.read(),google.rpc.ErrorInfoand serverstatus.messagewere unavailable toL4attempt logs andT4spans on failed (>= 400) async REST calls.Bug: b/479827845
Solution
packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2:async def record_response_async()(andrecord_http_response_asyncalias) to_FallbackTraceContextfor parity with_TraceContext.async def record_http_response_async(trace_ctx, response)to awaittrace_ctx.record_response_async(response)when supported bygoogle-api-core, falling back to synchronoustrace_ctx.record_response(response)on older releases.ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTSandasync_rest_request_kwargs(session)(matchinggoogle.api_core.resumable_transfer.upload_async) to passtotal_attempts=1whensessionis anAsyncAuthorizedSessionbacked bygoogle-auth >= 2.49.0.packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2:_FallbackTraceContext.record_response_async,record_http_response_async(async and sync-fallback paths), andasync_rest_request_kwargs.packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2&transports/rest_asyncio.py.j2:**async_rest_request_kwargs(session)andawait record_http_response_async(trace_ctx, response)on theis_asyncHTTP dispatch path.packages/gapic-generator/tests/integration/goldens/):_compat.py,test_compat.py, andredis/redis_selectiverest_asyncio.py).packages/gapic-generator/tests/system/telemetry_requirements_matrix.csv):F2.3(rpc.response.status_code:BAD_REQUEST->INVALID_ARGUMENT) andF2.4(rpc.response.status_code:ReadTimeout->NOT SET) to match the canonical status-code normalization in fix(api_core): normalize observability log attributes and canonical status codes #19144 soshowcase-canarystays green.Notes for Reviewers
feat/otel-logging-m3-s7-grpc-rpc-method(fix(api_core): normalize observability log attributes and canonical status codes #19144), which introduces_TraceContext.record_response_async()ingoogle-api-core._compat.pyadditions remain backwards-compatible with older releasedgoogle-api-coreandgoogle-authversions.Verification
bazelisk test //tests/integration:all, Docker Noxunit-3.10,unit-3.14,showcase_unit_w_rest_async-3.14(100.00%line and branch coverage), andshowcase_mypy(0issues across 74 source files).