File: valkey.py

package info (click to toggle)
python-dogpile.cache 1.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 836 kB
  • sloc: python: 6,620; makefile: 159; sh: 104
file content (612 lines) | stat: -rw-r--r-- 21,777 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
"""
Valkey Backends
------------------

Provides backends for talking to `Valkey <http://valkey.io>`__.

"""

import re
import typing
import warnings

from ..api import BytesBackend
from ..api import NO_VALUE

if typing.TYPE_CHECKING:
    import valkey
else:
    # delayed import
    valkey = None  # noqa F811

__all__ = ("ValkeyBackend", "ValkeySentinelBackend", "ValkeyClusterBackend")


RE_VALID_PREFIX = re.compile(r"^[\w\-\.\:]{2,10}$")


class ValkeyBackend(BytesBackend):
    r"""A `Valkey <http://valkey.io/>`__ backend, using the
    `valkey-py <http://pypi.python.org/pypi/valkey/>`__ driver.

    .. versionadded:: 1.3.4

    Example configuration::

        from dogpile.cache import make_region

        region = make_region().configure(
            'dogpile.cache.valkey',
            arguments = {
                'host': 'localhost',
                'port': 6379,
                'db': 0,
                'valkey_expiration_time': 60*60*2,   # 2 hours
                'distributed_lock': True,
                'thread_local_lock': False
                }
        )


    Arguments accepted in the arguments dictionary:

    :param url: string. If provided, will override separate
     host/username/password/port/db params.  The format is that accepted by
     ``StrictValkey.from_url()``.

    :param host: string, default is ``localhost``.

    :param username: string, default is no username.

    :param password: string, default is no password.

    :param port: integer, default is ``6379``.

    :param db: integer, default is ``0``.

    :param valkey_expiration_time: integer, number of seconds after setting a
     value that Valkey should expire it.  This should be larger than dogpile's
     cache expiration.  By default no expiration is set.

    :param distributed_lock: boolean, when True, will use a
     valkey-lock as the dogpile lock. Use this when multiple processes will be
     talking to the same valkey instance. When left at False, dogpile will
     coordinate on a regular threading mutex.

    :param lock_timeout: integer, number of seconds after acquiring a lock that
     Valkey should expire it.  This argument is only valid when
     ``distributed_lock`` is ``True``.

    :param lock_sleep: integer, number of seconds to sleep when failed to
     acquire a lock.  This argument is only valid when
     ``distributed_lock`` is ``True``.

    :param lock_blocking: bool, default ``True``. Passed to the Valkey client's
     lock constructor when ``distributed_lock`` is ``True``.

     .. versionadded:: 1.4.1

    :param lock_blocking_timeout: int or float, default ``None``.  Passed to
     the Valkey client's lock constructor, when ``distributed_lock`` is
     ``True``.

     .. versionadded:: 1.4.1

    :param lock_prefix: string. This prefix is used for generating the name of
     locks. If customized, the prefix must be between 2 and 10 characters long,
     and may contain any alphanumeric character and the symbols "_-.:".

     .. versionadded:: 1.5.0

    :param socket_timeout: float, seconds for socket timeout.
     Default is None (no timeout).

    :param socket_connect_timeout: float, seconds for socket connection
     timeout. Default is None (no timeout).

    :param socket_keepalive: boolean, when True, socket keepalive is enabled.
     Default is False.

    :param socket_keepalive_options: dict, socket keepalive options.
     Default is None (no options).

    :param connection_pool: ``valkey.ConnectionPool`` object.  If provided,
     this object supersedes other connection arguments passed to the
     ``valkey.StrictValkey`` instance, including url and/or host as well as
     socket_timeout, and will be passed to ``valkey.StrictValkey`` as the
     source of connectivity.

    :param thread_local_lock: bool, whether a thread-local Valkey lock object
     should be used. This is the default, but is not compatible with
     asynchronous runners, as they run in a different thread than the one
     used to create the lock.

    :param ssl: boolean, default ``None``. If set, this is passed to the
      ``valkey.StrictValkey`` constructor as ``ssl``. All additional ``ssl_``
      prefixed args should be submitted via the
      :paramref:`.ValkeyBackend.connection_kwargs` dict.

      .. versionadded:: 1.4.1

    :param connection_kwargs: dict, additional keyword arguments are passed
     along to the
     ``StrictValkey.from_url()`` method or ``StrictValkey()`` constructor
     directly, including parameters like ``ssl``, ``ssl_certfile``,
     ``charset``, etc.
    """

    lock_template: str = "_lock{0}"

    def __init__(self, arguments):
        arguments = arguments.copy()
        self._imports()
        self.url = arguments.pop("url", None)
        self.host = arguments.pop("host", "localhost")
        self.username = arguments.pop("username", None)
        self.password = arguments.pop("password", None)
        self.port = arguments.pop("port", 6379)
        self.db = arguments.pop("db", 0)
        self.socket_timeout = arguments.pop("socket_timeout", None)
        self.socket_connect_timeout = arguments.pop(
            "socket_connect_timeout", None
        )
        self.socket_keepalive = arguments.pop("socket_keepalive", False)
        self.socket_keepalive_options = arguments.pop(
            "socket_keepalive_options", None
        )

        # additional ssl params should be submitted in `connection_kwargs`
        self.ssl = arguments.pop("ssl", None)

        # used by `get_mutex`
        self.distributed_lock = arguments.pop("distributed_lock", False)
        self.lock_timeout = arguments.pop("lock_timeout", None)
        self.lock_sleep = arguments.pop("lock_sleep", 0.1)
        self.lock_blocking = arguments.pop("lock_blocking", True)
        self.lock_blocking_timeout = arguments.pop(
            "lock_blocking_timeout", None
        )

        self.thread_local_lock = arguments.pop("thread_local_lock", True)
        self.connection_kwargs = arguments.pop("connection_kwargs", {})

        if self.distributed_lock and self.thread_local_lock:
            warnings.warn(
                "The Valkey backend thread_local_lock parameter should be "
                "set to False when distributed_lock is True"
            )

        self.valkey_expiration_time = arguments.pop(
            "valkey_expiration_time", 0
        )
        self.connection_pool = arguments.pop("connection_pool", None)

        lock_prefix = arguments.pop("lock_prefix", None)
        if lock_prefix:
            if (not isinstance(lock_prefix, str)) or (
                not RE_VALID_PREFIX.match(lock_prefix)
            ):
                raise ValueError("Invalid `lock_prefix` submitted.")
            self.lock_template = "%s{0}" % lock_prefix

        self._create_client()

    def _imports(self):
        # defer imports until backend is used
        global valkey
        import valkey  # noqa

    def _create_client(self):
        if self.connection_pool is not None:
            # the connection pool already has all other connection
            # options present within, so here we disregard socket_timeout
            # and others.
            self.writer_client = valkey.StrictValkey(
                connection_pool=self.connection_pool
            )
            self.reader_client = self.writer_client
        else:
            args = {}
            args.update(self.connection_kwargs)
            if self.socket_timeout is not None:
                args["socket_timeout"] = self.socket_timeout
            if self.socket_connect_timeout is not None:
                args["socket_connect_timeout"] = self.socket_connect_timeout
            if self.socket_keepalive:
                args["socket_keepalive"] = True
                if self.socket_keepalive_options is not None:
                    args["socket_keepalive_options"] = (
                        self.socket_keepalive_options
                    )
            if self.ssl is not None:
                args["ssl"] = self.ssl

            if self.url is not None:
                args.update(url=self.url)
                self.writer_client = valkey.StrictValkey.from_url(**args)
                self.reader_client = self.writer_client
            else:
                args.update(
                    host=self.host,
                    username=self.username,
                    password=self.password,
                    port=self.port,
                    db=self.db,
                )
                self.writer_client = valkey.StrictValkey(**args)
                self.reader_client = self.writer_client

    def get_mutex(self, key):
        if self.distributed_lock:
            return _ValkeyLockWrapper(
                self.writer_client.lock(
                    self.lock_template.format(key),
                    timeout=self.lock_timeout,
                    sleep=self.lock_sleep,
                    thread_local=self.thread_local_lock,
                    blocking=self.lock_blocking,
                    blocking_timeout=self.lock_blocking_timeout,
                )
            )
        else:
            return None

    def get_serialized(self, key):
        value = self.reader_client.get(key)
        if value is None:
            return NO_VALUE
        return value

    def get_serialized_multi(self, keys):
        if not keys:
            return []
        values = self.reader_client.mget(keys)
        return [v if v is not None else NO_VALUE for v in values]  # type: ignore   # noqa: E501

    def set_serialized(self, key, value):
        if self.valkey_expiration_time:
            self.writer_client.setex(key, self.valkey_expiration_time, value)
        else:
            self.writer_client.set(key, value)

    def set_serialized_multi(self, mapping):
        if not self.valkey_expiration_time:
            self.writer_client.mset(mapping)
        else:
            pipe = self.writer_client.pipeline()
            for key, value in mapping.items():
                pipe.setex(key, self.valkey_expiration_time, value)
            pipe.execute()

    def delete(self, key):
        self.writer_client.delete(key)

    def delete_multi(self, keys):
        self.writer_client.delete(*keys)


class _ValkeyLockWrapper:
    __slots__ = ("mutex", "__weakref__")

    def __init__(self, mutex: typing.Any):
        self.mutex = mutex

    def acquire(self, wait: bool = True) -> typing.Any:
        return self.mutex.acquire(blocking=wait)

    def release(self) -> typing.Any:
        return self.mutex.release()

    def locked(self) -> bool:
        return self.mutex.locked()  # type: ignore


class ValkeySentinelBackend(ValkeyBackend):
    """A `Valkey <http://valkey.io/>`__ backend, using the
    `valkey-py <http://pypi.python.org/pypi/valkey/>`__ driver.
    This backend is to be used when using
    `Valkey Sentinel <https://valkey.io/docs/management/sentinel/>`__.

    .. versionadded:: 1.0.0

    Example configuration::

        from dogpile.cache import make_region

        region = make_region().configure(
            'dogpile.cache.valkey_sentinel',
            arguments = {
                'sentinels': [
                    ['valkey_sentinel_1', 26379],
                    ['valkey_sentinel_2', 26379]
                ],
                'db': 0,
                'valkey_expiration_time': 60*60*2,   # 2 hours
                'distributed_lock': True,
                'thread_local_lock': False
            }
        )


    Arguments accepted in the arguments dictionary:

    :param username: string, default is no username.

     .. versionadded:: 1.3.1

    :param password: string, default is no password.

    :param db: integer, default is ``0``.

    :param valkey_expiration_time: integer, number of seconds after setting a
     value that Valkey should expire it.  This should be larger than dogpile's
     cache expiration.  By default no expiration is set.

    :param distributed_lock: boolean, when True, will use a
     valkey-lock as the dogpile lock. Use this when multiple processes will be
     talking to the same valkey instance. When False, dogpile will
     coordinate on a regular threading mutex, Default is True.

    :param lock_timeout: integer, number of seconds after acquiring a lock that
     Valkey should expire it.  This argument is only valid when
     ``distributed_lock`` is ``True``.

    :param socket_timeout: float, seconds for socket timeout.
     Default is None (no timeout).

     .. versionadded:: 1.3.2

    :param socket_connect_timeout: float, seconds for socket connection
     timeout.  Default is None (no timeout).

     .. versionadded:: 1.3.2

    :param socket_keepalive: boolean, when True, socket keepalive is enabled
     Default is False.

     .. versionadded:: 1.3.2

    :param socket_keepalive_options: dict, socket keepalive options.
     Default is {} (no options).

    :param sentinels: is a list of sentinel nodes. Each node is represented by
     a pair (hostname, port).
     Default is None (not in sentinel mode).

    :param service_name: str, the service name.
     Default is 'mymaster'.

    :param sentinel_kwargs: is a dictionary of connection arguments used when
     connecting to sentinel instances. Any argument that can be passed to
     a normal Valkey connection can be specified here.
     Default is {}.

    :param connection_kwargs: dict, additional keyword arguments are passed
     along to the
     ``StrictValkey.from_url()`` method or ``StrictValkey()`` constructor
     directly, including parameters like ``ssl``, ``ssl_certfile``,
     ``charset``, etc.

    :param lock_sleep: integer, number of seconds to sleep when failed to
     acquire a lock.  This argument is only valid when
     ``distributed_lock`` is ``True``.

    :param thread_local_lock: bool, whether a thread-local Valkey lock object
     should be used. This is the default, but is not compatible with
     asynchronous runners, as they run in a different thread than the one
     used to create the lock.


    """

    def __init__(self, arguments):
        arguments = arguments.copy()

        self.sentinels = arguments.pop("sentinels", None)
        self.service_name = arguments.pop("service_name", "mymaster")
        self.sentinel_kwargs = arguments.pop("sentinel_kwargs", {})

        super().__init__(
            arguments={
                "distributed_lock": True,
                "thread_local_lock": False,
                **arguments,
            }
        )

    def _imports(self):
        # defer imports until backend is used
        global valkey
        import valkey.sentinel  # noqa

    def _create_client(self):
        sentinel_kwargs = {}
        sentinel_kwargs.update(self.sentinel_kwargs)
        sentinel_kwargs.setdefault("username", self.username)
        sentinel_kwargs.setdefault("password", self.password)

        connection_kwargs = {}
        connection_kwargs.update(self.connection_kwargs)
        connection_kwargs.setdefault("username", self.username)
        connection_kwargs.setdefault("password", self.password)

        if self.db is not None:
            connection_kwargs.setdefault("db", self.db)
            sentinel_kwargs.setdefault("db", self.db)
        if self.socket_timeout is not None:
            connection_kwargs.setdefault("socket_timeout", self.socket_timeout)
        if self.socket_connect_timeout is not None:
            connection_kwargs.setdefault(
                "socket_connect_timeout", self.socket_connect_timeout
            )
        if self.socket_keepalive:
            connection_kwargs.setdefault("socket_keepalive", True)
            if self.socket_keepalive_options is not None:
                connection_kwargs.setdefault(
                    "socket_keepalive_options", self.socket_keepalive_options
                )

        sentinel = valkey.sentinel.Sentinel(
            self.sentinels,
            sentinel_kwargs=sentinel_kwargs,
            **connection_kwargs,
        )
        self.writer_client = sentinel.master_for(self.service_name)
        self.reader_client = sentinel.slave_for(self.service_name)


class ValkeyClusterBackend(ValkeyBackend):
    r"""A `Valkey <http://valkey.io/>`__ backend, using the
    `valkey-py <http://pypi.python.org/pypi/valkey/>`__ driver.
    This backend is to be used when connecting to a
    `Valkey Cluster <https://valkey.io/docs/management/scaling/>`__ which
    will use the
    `ValkeyCluster Client
    <https://valkey.readthedocs.io/en/stable/connections.html#cluster-client>`__.

    .. seealso::

        `Clustering <https://valkey.readthedocs.io/en/stable/clustering.html>`__
        in the valkey-py documentation.

    Requires valkey-py version >=4.1.0.

    .. versionadded:: 1.3.2

    Connecting to the cluster requires one of:

    * Passing a list of startup nodes
    * Passing only one node of the cluster, Valkey will use automatic discovery
      to find the other nodes.

    Example configuration, using startup nodes::

        from dogpile.cache import make_region
        from valkey.cluster import ClusterNode

        region = make_region().configure(
            'dogpile.cache.valkey_cluster',
            arguments = {
                "startup_nodes": [
                    ClusterNode('localhost', 6379),
                    ClusterNode('localhost', 6378)
                ]
            }
        )

    It is recommended to use startup nodes, so that connections will be
    successful as at least one node will always be present.  Connection
    arguments such as password, username or
    CA certificate may be passed using ``connection_kwargs``::

        from dogpile.cache import make_region
        from valkey.cluster import ClusterNode

        connection_kwargs = {
            "username": "admin",
            "password": "averystrongpassword",
            "ssl": True,
            "ssl_ca_certs": "valkey.pem",
        }

        nodes = [
            ClusterNode("localhost", 6379),
            ClusterNode("localhost", 6380),
            ClusterNode("localhost", 6381),
        ]

        region = make_region().configure(
            "dogpile.cache.valkey_cluster",
            arguments={
                "startup_nodes": nodes,
                "connection_kwargs": connection_kwargs,
            },
        )

    Passing a URL to one node only will allow the driver to discover the whole
    cluster automatically::

        from dogpile.cache import make_region

        region = make_region().configure(
            'dogpile.cache.valkey_cluster',
            arguments = {
                "url": "localhost:6379/0"
            }
        )

    A caveat of the above approach is that if the single node targeting
    is not available, this would prevent the connection from being successful.

    Parameters accepted include:

    :param startup_nodes: List of ClusterNode. The list of nodes in
     the cluster that the client will try to connect to.

    :param url: string. If provided, will override separate
     host/password/port/db params.  The format is that accepted by
     ``ValkeyCluster.from_url()``.

    :param db: integer, default is ``0``.

    :param valkey_expiration_time: integer, number of seconds after setting
     a value that Valkey should expire it.  This should be larger than dogpile's
     cache expiration.  By default no expiration is set.

    :param distributed_lock: boolean, when True, will use a
     valkey-lock as the dogpile lock. Use this when multiple processes will be
     talking to the same valkey instance. When left at False, dogpile will
     coordinate on a regular threading mutex.

    :param lock_timeout: integer, number of seconds after acquiring a lock that
     Valkey should expire it.  This argument is only valid when
     ``distributed_lock`` is ``True``.

    :param socket_timeout: float, seconds for socket timeout.
     Default is None (no timeout).

    :param socket_connect_timeout: float, seconds for socket connection
     timeout.  Default is None (no timeout).

    :param socket_keepalive: boolean, when True, socket keepalive is enabled
     Default is False.

    :param lock_sleep: integer, number of seconds to sleep when failed to
     acquire a lock.  This argument is only valid when
     ``distributed_lock`` is ``True``.

    :param thread_local_lock: bool, whether a thread-local Valkey lock object
     should be used. This is the default, but is not compatible with
     asynchronous runners, as they run in a different thread than the one
     used to create the lock.

    :param connection_kwargs: dict, additional keyword arguments are passed
     along to the
     ``ValkeyCluster.from_url()`` method or ``ValkeyCluster()`` constructor
     directly, including parameters like ``ssl``, ``ssl_certfile``,
     ``charset``, etc.

    """  # noqa: E501

    def __init__(self, arguments):
        arguments = arguments.copy()
        self.startup_nodes = arguments.pop("startup_nodes", None)
        super().__init__(arguments)

    def _imports(self):
        global valkey
        import valkey.cluster

    def _create_client(self):
        valkey_cluster: valkey.cluster.ValkeyCluster[typing.Any]  # type: ignore   # noqa: E501
        if self.url is not None:
            valkey_cluster = valkey.cluster.ValkeyCluster.from_url(
                self.url, **self.connection_kwargs
            )
        else:
            valkey_cluster = valkey.cluster.ValkeyCluster(  # type: ignore   # noqa: E501
                startup_nodes=self.startup_nodes,
                **self.connection_kwargs,
            )
        self.writer_client = typing.cast(valkey.Valkey[bytes], valkey_cluster)  # type: ignore   # noqa: E501
        self.reader_client = self.writer_client