| 1 |
# This file is part of Hypothesis, which may be found at |
| 2 |
# https://github.com/HypothesisWorks/hypothesis/ |
| 3 |
# |
| 4 |
# Copyright the Hypothesis Authors. |
| 5 |
# Individual contributors are listed in AUTHORS.rst and the git log. |
| 6 |
# |
| 7 |
# This Source Code Form is subject to the terms of the Mozilla Public License, |
| 8 |
# v. 2.0. If a copy of the MPL was not distributed with this file, You can |
| 9 |
# obtain one at https://mozilla.org/MPL/2.0/. |
| 10 |
|
| 11 |
import base64 |
| 12 |
import json |
| 13 |
from collections.abc import Iterable |
| 14 |
from contextlib import contextmanager |
| 15 |
from datetime import timedelta |
| 16 |
from typing import Any |
| 17 |
|
| 18 |
from redis import Redis |
| 19 |
|
| 20 |
from hypothesis.database import ExampleDatabase |
| 21 |
from hypothesis.internal.validation import check_type |
| 22 |
|
| 23 |
|
| 24 |
class RedisExampleDatabase(ExampleDatabase): |
| 25 |
"""Store Hypothesis examples as sets in the given :class:`~redis.Redis` datastore. |
| 26 |
|
| 27 |
This is particularly useful for shared databases, as per the recipe |
| 28 |
for a :class:`~hypothesis.database.MultiplexedDatabase`. |
| 29 |
|
| 30 |
.. note:: |
| 31 |
|
| 32 |
If a test has not been run for ``expire_after``, those examples will be allowed |
| 33 |
to expire. The default time-to-live persists examples between weekly runs. |
| 34 |
""" |
| 35 |
|
| 36 |
def __init__( |
| 37 |
self, |
| 38 |
redis: Redis, |
| 39 |
*, |
| 40 |
expire_after: timedelta = timedelta(days=8), |
| 41 |
key_prefix: bytes = b"hypothesis-example:", |
| 42 |
listener_channel: str = "hypothesis-changes", |
| 43 |
): |
| 44 |
super().__init__() |
| 45 |
check_type(Redis, redis, "redis") |
| 46 |
check_type(timedelta, expire_after, "expire_after") |
| 47 |
check_type(bytes, key_prefix, "key_prefix") |
| 48 |
check_type(str, listener_channel, "listener_channel") |
| 49 |
self.redis = redis |
| 50 |
self._expire_after = expire_after |
| 51 |
self._prefix = key_prefix |
| 52 |
self.listener_channel = listener_channel |
| 53 |
self._pubsub: Any = None |
| 54 |
|
| 55 |
def __repr__(self) -> str: |
| 56 |
return ( |
| 57 |
f"RedisExampleDatabase({self.redis!r}, expire_after={self._expire_after!r})" |
| 58 |
) |
| 59 |
|
| 60 |
def __eq__(self, other: object) -> bool: |
| 61 |
return ( |
| 62 |
isinstance(other, RedisExampleDatabase) |
| 63 |
and self.redis == other.redis |
| 64 |
and self._prefix == other._prefix |
| 65 |
and self.listener_channel == other.listener_channel |
| 66 |
) |
| 67 |
|
| 68 |
@contextmanager |
| 69 |
def _pipeline( |
| 70 |
self, |
| 71 |
*reset_expire_keys, |
| 72 |
execute_and_publish=True, |
| 73 |
event_type=None, |
| 74 |
to_publish=None, |
| 75 |
): |
| 76 |
# Context manager to batch updates and expiry reset, reducing TCP roundtrips |
| 77 |
pipe = self.redis.pipeline() |
| 78 |
yield pipe |
| 79 |
for key in reset_expire_keys: |
| 80 |
pipe.expire(self._prefix + key, self._expire_after) |
| 81 |
if execute_and_publish: |
| 82 |
changed = pipe.execute() |
| 83 |
# pipe.execute returns the rows modified for each operation, which includes |
| 84 |
# the operations performed during the yield, followed by the n operations |
| 85 |
# from pipe.exire. Look at just the operations from during the yield. |
| 86 |
changed = changed[: -len(reset_expire_keys)] |
| 87 |
if any(count > 0 for count in changed): |
| 88 |
assert to_publish is not None |
| 89 |
assert event_type is not None |
| 90 |
self._publish((event_type, to_publish)) |
| 91 |
|
| 92 |
def _publish(self, event): |
| 93 |
event = (event[0], tuple(self._encode(v) for v in event[1])) |
| 94 |
self.redis.publish(self.listener_channel, json.dumps(event)) |
| 95 |
|
| 96 |
def _encode(self, value: bytes) -> str: |
| 97 |
return base64.b64encode(value).decode("ascii") |
| 98 |
|
| 99 |
def _decode(self, value: str) -> bytes: |
| 100 |
return base64.b64decode(value) |
| 101 |
|
| 102 |
def fetch(self, key: bytes) -> Iterable[bytes]: |
| 103 |
with self._pipeline(key, execute_and_publish=False) as pipe: |
| 104 |
pipe.smembers(self._prefix + key) |
| 105 |
yield from pipe.execute()[0] |
| 106 |
|
| 107 |
def save(self, key: bytes, value: bytes) -> None: |
| 108 |
with self._pipeline(key, event_type="save", to_publish=(key, value)) as pipe: |
| 109 |
pipe.sadd(self._prefix + key, value) |
| 110 |
|
| 111 |
def delete(self, key: bytes, value: bytes) -> None: |
| 112 |
with self._pipeline(key, event_type="delete", to_publish=(key, value)) as pipe: |
| 113 |
pipe.srem(self._prefix + key, value) |
| 114 |
|
| 115 |
def move(self, src: bytes, dest: bytes, value: bytes) -> None: |
| 116 |
if src == dest: |
| 117 |
self.save(dest, value) |
| 118 |
return |
| 119 |
|
| 120 |
with self._pipeline(src, dest, execute_and_publish=False) as pipe: |
| 121 |
pipe.srem(self._prefix + src, value) |
| 122 |
pipe.sadd(self._prefix + dest, value) |
| 123 |
|
| 124 |
changed = pipe.execute() |
| 125 |
if changed[0] > 0: |
| 126 |
# did the value set of the first key change? |
| 127 |
self._publish(("delete", (src, value))) |
| 128 |
if changed[1] > 0: |
| 129 |
# did the value set of the second key change? |
| 130 |
self._publish(("save", (dest, value))) |
| 131 |
|
| 132 |
def _handle_message(self, message: dict) -> None: |
| 133 |
# other message types include "subscribe" and "unsubscribe". these are |
| 134 |
# sent to the client, but not to the pubsub channel. |
| 135 |
assert message["type"] == "message" |
| 136 |
data = json.loads(message["data"]) |
| 137 |
event_type = data[0] |
| 138 |
self._broadcast_change( |
| 139 |
(event_type, tuple(self._decode(v) for v in data[1])) # type: ignore |
| 140 |
) |
| 141 |
|
| 142 |
def _start_listening(self) -> None: |
| 143 |
self._pubsub = self.redis.pubsub() |
| 144 |
self._pubsub.subscribe(**{self.listener_channel: self._handle_message}) |
| 145 |
|
| 146 |
def _stop_listening(self) -> None: |
| 147 |
self._pubsub.unsubscribe() |
| 148 |
self._pubsub.close() |
| 149 |
self._pubsub = None |