Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

chore: Revert "feat: add caching to GapicCallable"#744

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
parthea merged 1 commit intomainfromrevert-666-optimize_gapic_callable
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes fromall 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
80 changes: 44 additions & 36 deletionsgoogle/api_core/gapic_v1/method.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,6 +42,24 @@ class _MethodDefault(enum.Enum):
so the default should be used."""


def_is_not_none_or_false(value):
returnvalueisnotNoneandvalueisnotFalse


def_apply_decorators(func,decorators):
"""Apply a list of decorators to a given function.
``decorators`` may contain items that are ``None`` or ``False`` which will
be ignored.
"""
filtered_decorators=filter(_is_not_none_or_false,reversed(decorators))

fordecoratorinfiltered_decorators:
func=decorator(func)

returnfunc


class_GapicCallable(object):
"""Callable that applies retry, timeout, and metadata logic.
Expand DownExpand Up@@ -73,53 +91,44 @@ def __init__(
):
self._target=target
self._retry=retry
ifisinstance(timeout, (int,float)):
timeout=TimeToDeadlineTimeout(timeout=timeout)
self._timeout=timeout
self._compression=compression
self._metadata=list(metadata)ifmetadataisnotNoneelseNone
self._metadata=metadata

def__call__(
self,*args,timeout=DEFAULT,retry=DEFAULT,compression=DEFAULT,**kwargs
):
"""Invoke the low-level RPC with retry, timeout, compression, and metadata."""

ifcompressionisDEFAULT:
compression=self._compression
ifcompressionisnotNone:
kwargs["compression"]=compression
ifretryisDEFAULT:
retry=self._retry

# Add the user agent metadata to the call.
ifself._metadataisnotNone:
try:
# attempt to concatenate default metadata with user-provided metadata
kwargs["metadata"]= [*kwargs["metadata"],*self._metadata]
except (KeyError,TypeError):
# if metadata is not provided, use just the default metadata
kwargs["metadata"]=self._metadata

call=self._build_wrapped_call(timeout,retry)
returncall(*args,**kwargs)

@functools.lru_cache(maxsize=4)
def_build_wrapped_call(self,timeout,retry):
"""
Build a wrapped callable that applies retry, timeout, and metadata logic.
"""
wrapped_func=self._target
iftimeoutisDEFAULT:
timeout=self._timeout
elifisinstance(timeout, (int,float)):

ifcompressionisDEFAULT:
compression=self._compression

ifisinstance(timeout, (int,float)):
timeout=TimeToDeadlineTimeout(timeout=timeout)
iftimeoutisnotNone:
wrapped_func=timeout(wrapped_func)

ifretryisDEFAULT:
retry=self._retry
ifretryisnotNone:
wrapped_func=retry(wrapped_func)
# Apply all applicable decorators.
wrapped_func=_apply_decorators(self._target, [retry,timeout])

# Add the user agent metadata to the call.
ifself._metadataisnotNone:
metadata=kwargs.get("metadata", [])
# Due to the nature of invocation, None should be treated the same
# as not specified.
ifmetadataisNone:
metadata= []
metadata=list(metadata)
metadata.extend(self._metadata)
kwargs["metadata"]=metadata
ifself._compressionisnotNone:
kwargs["compression"]=compression

returnwrapped_func
returnwrapped_func(*args,**kwargs)


defwrap_method(
Expand DownExpand Up@@ -193,9 +202,8 @@ def get_topic(name, timeout=None):
Args:
func (Callable[Any]): The function to wrap. It should accept an
optional ``timeout`` (google.api_core.timeout.Timeout) argument.
If ``metadata`` is not ``None``, it should accept a ``metadata``
(Sequence[Tuple[str, str]]) argument.
optional ``timeout`` argument. If ``metadata`` is not ``None``, it
should accept a ``metadata`` argument.
default_retry (Optional[google.api_core.Retry]): The default retry
strategy. If ``None``, the method will not retry by default.
default_timeout (Optional[google.api_core.Timeout]): The default
Expand Down
21 changes: 0 additions & 21 deletionstests/unit/gapic/test_method.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -222,24 +222,3 @@ def test_wrap_method_with_call_not_supported():
withpytest.raises(ValueError)asexc_info:
google.api_core.gapic_v1.method.wrap_method(method,with_call=True)
assert"with_call=True is only supported for unary calls"instr(exc_info.value)


deftest_benchmark_gapic_call():
"""
Ensure the __call__ method performance does not regress from expectations
__call__ builds a new wrapped function using passed-in timeout and retry, but
subsequent calls are cached
Note: The threshold has been tuned for the CI workers. Test may flake on
slower hardware
"""
fromgoogle.api_core.gapic_v1.methodimport_GapicCallable
fromgoogle.api_core.retryimportRetry
fromtimeitimporttimeit

gapic_callable=_GapicCallable(
lambda*a,**k:1,retry=Retry(),timeout=1010,compression=False
)
avg_time=timeit(lambda:gapic_callable(),number=10_000)
assertavg_time<0.4

[8]ページ先頭

©2009-2025 Movatter.jp