Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Comment on lines +98 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)


# 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.
Expand All @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ def _get_http_options():
{% if body_spec %}
data=body,
{% endif %}
{% if is_async %}
**async_rest_request_kwargs(session),
{% endif %}
{% if not is_async and is_streaming_method %}
{# NOTE: The underlying `requests` library used for making a sync request
# requires us to set `stream=True` to avoid loading the entire response
Expand All @@ -194,7 +197,11 @@ def _get_http_options():
stream=True,
{% endif %}
)
{% if is_async %}
await record_http_response_async(trace_ctx, response)
{% else %}
trace_ctx.record_response(response)
{% endif %}
return response
{% endmacro %}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,16 @@ from google.api_core import retry_async as retries
from google.api_core import rest_helpers
from google.api_core import rest_streaming_async # type: ignore
{% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %}
{% if rest_async_io_enabled %}
from {{package_path}}._compat import (
async_rest_request_kwargs,
record_http_response_async,
trace_http_request,
transcode_request,
)
{% else %}
from {{package_path}}._compat import transcode_request, trace_http_request
{% endif %}

import google.protobuf

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
)
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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))



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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ def record_response(self, response: Any) -> None:

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

Expand All @@ -80,6 +85,14 @@ def record_error(self, exc: BaseException | None) -> None:
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.
Expand All @@ -99,6 +112,36 @@ def trace_http_request(*args: Any, **kwargs: Any) -> _FallbackTraceContext: # t
"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
)


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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#
"""Tests for the compatibility module for older versions of google-api-core."""

import asyncio
import json
import pytest
import os
Expand All @@ -32,6 +33,8 @@
read_environment_variables,
_observability,
trace_http_request,
record_http_response_async,
async_rest_request_kwargs,
apply_channel_interceptors,
apply_async_channel_interceptors,
)
Expand Down Expand Up @@ -484,12 +487,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)


def test_async_rest_request_kwargs_compat(monkeypatch):
from google.cloud.asset_v1 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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ def record_response(self, response: Any) -> None:

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

Expand All @@ -80,6 +85,14 @@ def record_error(self, exc: BaseException | None) -> None:
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.
Expand All @@ -99,6 +112,36 @@ def trace_http_request(*args: Any, **kwargs: Any) -> _FallbackTraceContext: # t
"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
)


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
Expand Down
Loading
Loading