| 1 |
import datetime as dt |
| 2 |
import re |
| 3 |
import typing as _t |
| 4 |
from contextlib import contextmanager |
| 5 |
from contextlib import nullcontext |
| 6 |
from functools import partial |
| 7 |
from time import time |
| 8 |
|
| 9 |
from cachelib.base import BaseCache |
| 10 |
|
| 11 |
_test_memcached_key = re.compile(r"[^\x00-\x21\xff]{1,250}$").match |
| 12 |
_MemcacheClientLib = _t.Literal["pylibmc", "google", "memcache", "libmc"] |
| 13 |
|
| 14 |
|
| 15 |
class MemcachedCache(BaseCache): |
| 16 |
"""A cache that uses memcached as backend. |
| 17 |
|
| 18 |
The first argument can either be an object that resembles the API of a |
| 19 |
``memcache.Client`` or a tuple/list of server addresses. In the |
| 20 |
event that a tuple/list is passed, CacheLib tries to import the best |
| 21 |
available memcache library. |
| 22 |
|
| 23 |
This cache looks into the following packages/modules to find bindings for |
| 24 |
memcached: |
| 25 |
|
| 26 |
- ``pylibmc`` |
| 27 |
- ``google.appengine.api.memcached`` |
| 28 |
- ``memcache`` |
| 29 |
- ``libmc`` |
| 30 |
|
| 31 |
Implementation notes: |
| 32 |
This cache backend works around some limitations in memcached to |
| 33 |
simplify the interface. For example unicode keys are encoded to |
| 34 |
UTF-8 on the fly. Methods such as :meth:`~.BaseCache.get_dict` return |
| 35 |
the keys in the same format as passed. Furthermore all get methods |
| 36 |
silently ignore key errors to not cause problems when untrusted user data |
| 37 |
is passed to the get methods which is often the case in web applications. |
| 38 |
This cache doesn't have a serializer since the underlying memcached client |
| 39 |
libraries handle serialization internally." |
| 40 |
|
| 41 |
:param servers: a list or tuple of server addresses or alternatively |
| 42 |
a ``memcache.Client`` or a compatible client. |
| 43 |
:param default_timeout: the default timeout that is used if no timeout is |
| 44 |
specified on :meth:`~.BaseCache.set`. Either a number of seconds or a |
| 45 |
:class:`datetime.timedelta`. A timeout of |
| 46 |
0 indicates that the cache never expires. |
| 47 |
|
| 48 |
.. versionchanged:: 0.17.0 |
| 49 |
Accepts a :class:`datetime.timedelta`. |
| 50 |
:param key_prefix: a prefix that is added before all keys. This makes it |
| 51 |
possible to use the same memcached server for different |
| 52 |
applications. Keep in mind that |
| 53 |
:meth:`~.BaseCache.clear` will also clear keys with a |
| 54 |
different prefix. |
| 55 |
:param pool_size: the size of the connection pool. This is only used if |
| 56 |
the memcached client library supports connection pooling. |
| 57 |
|
| 58 |
.. versionadded:: 0.15.0 |
| 59 |
:param pool_blocking: if the connection pool is exhausted, should the |
| 60 |
client block until a connection is available or raise |
| 61 |
an exception. This is only used if the memcached |
| 62 |
client library supports connection pooling. |
| 63 |
|
| 64 |
.. versionadded:: 0.15.0 |
| 65 |
:param ignore_delete_many_errors: If False, delete_many() will raise |
| 66 |
a RuntimeError if any key fails to delete. Keys that do not |
| 67 |
exist are considered successfully deleted and do not raise. |
| 68 |
|
| 69 |
.. versionadded:: 0.16.0 |
| 70 |
:param check_connection: If True, the constructor will verify the |
| 71 |
connection to the memcached server and raise a RuntimeError if it fails. |
| 72 |
If False (default), connection errors are ignored at construction |
| 73 |
and surface on first use. |
| 74 |
|
| 75 |
.. versionadded:: 0.16.1 |
| 76 |
:param memcache_client_lib: Optional. A string indicating which memcache client |
| 77 |
library to use. Valid values are 'pylibmc', 'google', 'memcache', and 'libmc'. |
| 78 |
If not provided, the library will be auto-detected based on availability. |
| 79 |
|
| 80 |
.. versionadded:: 0.17.0 |
| 81 |
""" |
| 82 |
|
| 83 |
def __init__( |
| 84 |
self, |
| 85 |
servers: _t.Any = None, |
| 86 |
default_timeout: int | dt.timedelta = 300, |
| 87 |
key_prefix: str | None = None, |
| 88 |
pool_size: int = 1, |
| 89 |
pool_blocking: bool = True, |
| 90 |
ignore_delete_many_errors: bool = True, |
| 91 |
check_connection: bool = False, |
| 92 |
memcache_client_lib: _MemcacheClientLib | None = None, |
| 93 |
): |
| 94 |
self.check_connection = check_connection |
| 95 |
BaseCache.__init__( |
| 96 |
self, default_timeout, ignore_delete_many_errors=ignore_delete_many_errors |
| 97 |
) |
| 98 |
|
| 99 |
if servers is None or isinstance(servers, (list, tuple)): |
| 100 |
if servers is None: |
| 101 |
servers = ["127.0.0.1:11211"] |
| 102 |
self._client, self._client_context = self.import_preferred_memcache_lib( |
| 103 |
servers, pool_size, pool_blocking, memcache_client_lib |
| 104 |
) |
| 105 |
else: |
| 106 |
# NOTE: servers is actually an already initialized memcache |
| 107 |
# client. |
| 108 |
self._client = servers |
| 109 |
self._client_context = partial(nullcontext, self._client) |
| 110 |
|
| 111 |
self.key_prefix = key_prefix |
| 112 |
|
| 113 |
def _normalize_key(self, key: str) -> str: |
| 114 |
if self.key_prefix: |
| 115 |
key = self.key_prefix + key |
| 116 |
return key |
| 117 |
|
| 118 |
def _normalize_timeout(self, timeout: int | dt.timedelta | None) -> int: |
| 119 |
normalized_timeout = BaseCache._normalize_timeout(self, timeout) |
| 120 |
if normalized_timeout > 0: |
| 121 |
normalized_timeout = int(time()) + normalized_timeout |
| 122 |
return normalized_timeout |
| 123 |
|
| 124 |
def get(self, key: str) -> _t.Any: |
| 125 |
key = self._normalize_key(key) |
| 126 |
# memcached doesn't support keys longer than that. Because often |
| 127 |
# checks for so long keys can occur because it's tested from user |
| 128 |
# submitted data etc we fail silently for getting. |
| 129 |
if _test_memcached_key(key): |
| 130 |
with self._client_context() as client: |
| 131 |
return client.get(key) |
| 132 |
|
| 133 |
def get_dict(self, *keys: str) -> dict[str, _t.Any]: |
| 134 |
key_mapping = {} |
| 135 |
for key in keys: |
| 136 |
encoded_key = self._normalize_key(key) |
| 137 |
if _test_memcached_key(key): |
| 138 |
key_mapping[encoded_key] = key |
| 139 |
_keys = list(key_mapping) |
| 140 |
with self._client_context() as client: |
| 141 |
d: dict[str, _t.Any] = client.get_multi(_keys) |
| 142 |
rv = d |
| 143 |
if self.key_prefix: |
| 144 |
rv = {} |
| 145 |
for key, value in d.items(): |
| 146 |
rv[key_mapping[key]] = value |
| 147 |
if len(rv) < len(keys): |
| 148 |
for key in keys: |
| 149 |
if key not in rv: |
| 150 |
rv[key] = None |
| 151 |
return rv |
| 152 |
|
| 153 |
def add( |
| 154 |
self, key: str, value: _t.Any, timeout: int | dt.timedelta | None = None |
| 155 |
) -> bool: |
| 156 |
normalized_key = self._normalize_key(key) |
| 157 |
normalized_timeout = self._normalize_timeout(timeout) |
| 158 |
with self._client_context() as client: |
| 159 |
return bool(client.add(normalized_key, value, normalized_timeout)) |
| 160 |
|
| 161 |
def set( |
| 162 |
self, key: str, value: _t.Any, timeout: int | dt.timedelta | None = None |
| 163 |
) -> bool | None: |
| 164 |
normalized_key = self._normalize_key(key) |
| 165 |
normalized_timeout = self._normalize_timeout(timeout) |
| 166 |
with self._client_context() as client: |
| 167 |
return bool(client.set(normalized_key, value, normalized_timeout)) |
| 168 |
|
| 169 |
def get_many(self, *keys: str) -> list[_t.Any]: |
| 170 |
d = self.get_dict(*keys) |
| 171 |
return [d[key] for key in keys] |
| 172 |
|
| 173 |
def set_many( |
| 174 |
self, mapping: dict[str, _t.Any], timeout: int | dt.timedelta | None = None |
| 175 |
) -> list[_t.Any]: |
| 176 |
new_mapping = {} |
| 177 |
for key, value in mapping.items(): |
| 178 |
key = self._normalize_key(key) |
| 179 |
new_mapping[key] = value |
| 180 |
|
| 181 |
normalized_timeout = self._normalize_timeout(timeout) |
| 182 |
with self._client_context() as client: |
| 183 |
failed_keys: list[_t.Any] = client.set_multi( |
| 184 |
new_mapping, normalized_timeout |
| 185 |
) |
| 186 |
k_normkey = zip(mapping.keys(), new_mapping.keys(), strict=True) |
| 187 |
return [k for k, nkey in k_normkey if nkey not in failed_keys] |
| 188 |
|
| 189 |
def delete(self, key: str) -> bool: |
| 190 |
normalized_key = self._normalize_key(key) |
| 191 |
if _test_memcached_key(normalized_key): |
| 192 |
with self._client_context() as client: |
| 193 |
return bool(client.delete(normalized_key)) |
| 194 |
return False |
| 195 |
|
| 196 |
def delete_many(self, *keys: str) -> list[_t.Any]: |
| 197 |
new_keys = [] |
| 198 |
normalized_keys = [] |
| 199 |
for key in keys: |
| 200 |
normalized = self._normalize_key(key) |
| 201 |
if _test_memcached_key(normalized): |
| 202 |
new_keys.append(key) |
| 203 |
normalized_keys.append(normalized) |
| 204 |
with self._client_context() as client: |
| 205 |
client.delete_multi(normalized_keys) |
| 206 |
deleted_keys = [k for k in new_keys if not self.has(k)] |
| 207 |
if not self.ignore_delete_many_errors and len(deleted_keys) != len(new_keys): |
| 208 |
failed_keys = [k for k in new_keys if k not in deleted_keys] |
| 209 |
if failed_keys: |
| 210 |
raise RuntimeError(f"Failed to delete keys: {failed_keys}") |
| 211 |
return deleted_keys |
| 212 |
|
| 213 |
def has(self, key: str) -> bool: |
| 214 |
normalized_key = self._normalize_key(key) |
| 215 |
if _test_memcached_key(normalized_key): |
| 216 |
with self._client_context() as client: |
| 217 |
return bool(client.append(normalized_key, "")) |
| 218 |
return False |
| 219 |
|
| 220 |
def clear(self) -> bool: |
| 221 |
with self._client_context() as client: |
| 222 |
# python-memcached's flush_all returns None on success |
| 223 |
result = client.flush_all() |
| 224 |
return True if result is None else bool(result) |
| 225 |
|
| 226 |
def inc(self, key: str, delta: int = 1) -> int | None: |
| 227 |
normalized_key = self._normalize_key(key) |
| 228 |
with self._client_context() as client: |
| 229 |
value = (client.get(normalized_key) or 0) + delta |
| 230 |
return value if self.set(key, value) else None |
| 231 |
|
| 232 |
def dec(self, key: str, delta: int = 1) -> int | None: |
| 233 |
normalized_key = self._normalize_key(key) |
| 234 |
with self._client_context() as client: |
| 235 |
value = (client.get(normalized_key) or 0) - delta |
| 236 |
return value if self.set(key, value) else None |
| 237 |
|
| 238 |
def _create_pylibmc( |
| 239 |
self, servers: _t.Any, pool_size: int, pool_blocking: bool = True |
| 240 |
) -> tuple[_t.Any, _t.Callable[[], _t.ContextManager[_t.Any]]]: |
| 241 |
import pylibmc # type: ignore |
| 242 |
|
| 243 |
client = pylibmc.Client(servers) |
| 244 |
if self.check_connection: |
| 245 |
try: |
| 246 |
client.get_stats() |
| 247 |
except pylibmc.Error as err: |
| 248 |
raise RuntimeError( |
| 249 |
f"could not connect to memcached server(s): {err}" |
| 250 |
) from err |
| 251 |
pool = pylibmc.ClientPool(client, pool_size) |
| 252 |
reserve = partial(pool.reserve, block=pool_blocking) |
| 253 |
return pool, reserve |
| 254 |
|
| 255 |
def _create_google( |
| 256 |
self, servers: _t.Any, pool_size: int, pool_blocking: bool = True |
| 257 |
) -> tuple[_t.Any, _t.Callable[[], _t.ContextManager[_t.Any]]]: |
| 258 |
from google.appengine.api import memcache # type: ignore |
| 259 |
|
| 260 |
client = memcache.Client() |
| 261 |
return client, partial(nullcontext, client) |
| 262 |
|
| 263 |
def _create_memcache( |
| 264 |
self, servers: _t.Any, pool_size: int, pool_blocking: bool = True |
| 265 |
) -> tuple[_t.Any, _t.Callable[[], _t.ContextManager[_t.Any]]]: |
| 266 |
import memcache # type: ignore |
| 267 |
|
| 268 |
client = memcache.Client(servers) |
| 269 |
return client, partial(nullcontext, client) |
| 270 |
|
| 271 |
def _create_libmc( |
| 272 |
self, servers: _t.Any, pool_size: int, pool_blocking: bool = True |
| 273 |
) -> tuple[_t.Any, _t.Callable[[], _t.ContextManager[_t.Any]]]: |
| 274 |
import libmc # type: ignore |
| 275 |
|
| 276 |
# libmc.ClientPool doesn't take pool_size as a positional arg, |
| 277 |
# and its .client() always blocks/auto-grows, no non-blocking mode. |
| 278 |
pool = libmc.ClientPool(servers) |
| 279 |
pool.config(libmc.MC_INITIAL_CLIENTS, pool_size) |
| 280 |
pool.config(libmc.MC_MAX_CLIENTS, pool_size) |
| 281 |
|
| 282 |
@contextmanager |
| 283 |
def get_client() -> _t.Generator[_t.Any, None, None]: |
| 284 |
# flush_all is disabled by default in libmc; enable per connection. |
| 285 |
with pool.client() as client: |
| 286 |
client.toggle_flush_all_feature(True) |
| 287 |
yield client |
| 288 |
|
| 289 |
return pool, get_client |
| 290 |
|
| 291 |
def import_preferred_memcache_lib( |
| 292 |
self, |
| 293 |
servers: _t.Any, |
| 294 |
pool_size: int, |
| 295 |
pool_blocking: bool = True, |
| 296 |
memcache_client_lib: _MemcacheClientLib | None = None, |
| 297 |
) -> tuple[_t.Any, _t.Callable[[], _t.ContextManager[_t.Any]]]: |
| 298 |
"""Returns an initialized memcache client. Used by the constructor.""" |
| 299 |
factories = { |
| 300 |
"pylibmc": self._create_pylibmc, |
| 301 |
"google": self._create_google, |
| 302 |
"memcache": self._create_memcache, |
| 303 |
"libmc": self._create_libmc, |
| 304 |
} |
| 305 |
if memcache_client_lib is not None: |
| 306 |
factory = factories.get(memcache_client_lib) |
| 307 |
if factory is None: |
| 308 |
raise ValueError(f"Invalid memcache_client_lib: {memcache_client_lib}") |
| 309 |
return factory(servers, pool_size, pool_blocking) |
| 310 |
for factory in factories.values(): |
| 311 |
try: |
| 312 |
return factory(servers, pool_size, pool_blocking) |
| 313 |
except ImportError: |
| 314 |
continue |
| 315 |
raise RuntimeError("no memcache module found") |