Skip to content
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

fix: properly handle error when clearing cache #636

Merged
merged 4 commits into from
May 10, 2021
Merged
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
21 changes: 11 additions & 10 deletions google/cloud/ndb/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,22 +165,23 @@ def retry_wrapper(*args, **kwargs):
@tasklets.tasklet
def wrapper(*args, **kwargs):
cache = _global_cache()

is_read = read
if not is_read:
is_read = kwargs.get("read", False)

strict = cache.strict_read if is_read else cache.strict_write
if strict:
function = retry(wrapped, cache.transient_errors)
else:
function = wrapped

try:
if cache.clear_cache_soon:
warnings.warn("Clearing global cache...", RuntimeWarning)
cache.clear()
cache.clear_cache_soon = False

is_read = read
if not is_read:
is_read = kwargs.get("read", False)

strict = cache.strict_read if is_read else cache.strict_write
if strict:
function = retry(wrapped, cache.transient_errors)
else:
function = wrapped

result = yield function(*args, **kwargs)
raise tasklets.Return(result)

Expand Down
30 changes: 30 additions & 0 deletions tests/unit/test__cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,36 @@ def test_global_get_clear_cache_soon(_batch, _global_cache):
_global_cache.return_value.clear.assert_called_once_with()


@pytest.mark.usefixtures("in_context")
@mock.patch("google.cloud.ndb._cache._global_cache")
@mock.patch("google.cloud.ndb._cache._batch")
def test_global_get_clear_cache_soon_with_error(_batch, _global_cache):
"""Regression test for #633

https://github.com/googleapis/python-ndb/issues/633
"""

class TransientError(Exception):
pass

batch = _batch.get_batch.return_value
future = _future_result("hi mom!")
batch.add.return_value = future
_global_cache.return_value = mock.Mock(
transient_errors=(TransientError),
clear_cache_soon=True,
strict_read=False,
clear=mock.Mock(side_effect=TransientError("oops!"), spec=()),
spec=("transient_errors", "clear_cache_soon", "clear", "strict_read"),
)

with warnings.catch_warnings(record=True) as logged:
assert _cache.global_get(b"foo").result() is None
assert len(logged) == 2

_global_cache.return_value.clear.assert_called_once_with()


@pytest.mark.usefixtures("in_context")
@mock.patch("google.cloud.ndb.tasklets.sleep")
@mock.patch("google.cloud.ndb._cache._global_cache")
Expand Down