Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/event.py: 44%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import asyncio
2import logging
3import threading
4import time
5from abc import ABC, abstractmethod
6from enum import Enum
7from typing import TYPE_CHECKING, Dict, List, Optional, Type, Union
9from redis.auth.token import TokenInterface
10from redis.credentials import CredentialProvider, StreamingCredentialProvider
11from redis.observability.recorder import (
12 init_connection_count,
13 register_pools_connection_count,
14)
15from redis.utils import check_protocol_version, deprecated_function
17if TYPE_CHECKING:
18 from redis.maint_notifications import (
19 MaintenanceNotification,
20 MaintenanceState,
21 MaintNotificationsConfig,
22 )
24logger = logging.getLogger(__name__)
26# A failed deferred AUTH is logged by every connection, on every release that
27# retries it, so it is a warning at most once per interval and debug otherwise
28_RE_AUTH_FAILURE_WARNING_INTERVAL = 60.0
29_last_re_auth_failure_warning = float("-inf")
30_suppressed_re_auth_failures = 0
33def _log_re_auth_failure(connection: object, error: Exception) -> None:
34 """Log a failed deferred AUTH without flooding the log."""
35 global _last_re_auth_failure_warning, _suppressed_re_auth_failures
36 now = time.monotonic()
37 if now - _last_re_auth_failure_warning >= _RE_AUTH_FAILURE_WARNING_INTERVAL:
38 suppressed = _suppressed_re_auth_failures
39 _last_re_auth_failure_warning = now
40 _suppressed_re_auth_failures = 0
41 logger.warning(
42 "Deferred re-authentication of %s failed: %r (%d failures since "
43 "the last warning were logged at debug level)",
44 connection,
45 error,
46 suppressed,
47 )
48 else:
49 _suppressed_re_auth_failures += 1
50 if logger.isEnabledFor(logging.DEBUG):
51 logger.debug(
52 "Deferred re-authentication of %s failed: %r", connection, error
53 )
56class EventListenerInterface(ABC):
57 """
58 Represents a listener for given event object.
59 """
61 @abstractmethod
62 def listen(self, event: object):
63 pass
66class AsyncEventListenerInterface(ABC):
67 """
68 Represents an async listener for given event object.
69 """
71 @abstractmethod
72 async def listen(self, event: object):
73 pass
76class EventDispatcherInterface(ABC):
77 """
78 Represents a dispatcher that dispatches events to listeners
79 associated with given event.
80 """
82 @abstractmethod
83 def dispatch(self, event: object):
84 pass
86 @abstractmethod
87 async def dispatch_async(self, event: object):
88 pass
90 @abstractmethod
91 def register_listeners(
92 self,
93 mappings: Dict[
94 Type[object],
95 List[Union[EventListenerInterface, AsyncEventListenerInterface]],
96 ],
97 ):
98 """Register additional listeners."""
99 pass
101 @abstractmethod
102 def unregister_listeners(
103 self,
104 mappings: Dict[
105 Type[object],
106 List[Union[EventListenerInterface, AsyncEventListenerInterface]],
107 ],
108 ):
109 """Remove previously registered listeners by identity."""
110 pass
113class EventException(Exception):
114 """
115 Exception wrapper that adds an event object into exception context.
116 """
118 def __init__(self, exception: Exception, event: object):
119 self.exception = exception
120 self.event = event
121 super().__init__(exception)
124class EventDispatcher(EventDispatcherInterface):
125 # TODO: Make dispatcher to accept external mappings.
126 def __init__(
127 self,
128 event_listeners: Optional[
129 Dict[Type[object], List[EventListenerInterface]]
130 ] = None,
131 ):
132 """
133 Dispatcher that dispatches events to listeners associated with given event.
134 """
135 self._event_listeners_mapping: Dict[
136 Type[object], List[EventListenerInterface]
137 ] = {
138 AfterConnectionReleasedEvent: [
139 ReAuthConnectionListener(),
140 ],
141 AfterPooledConnectionsInstantiationEvent: [
142 RegisterReAuthForPooledConnections(),
143 ],
144 AfterSingleConnectionInstantiationEvent: [
145 RegisterReAuthForSingleConnection()
146 ],
147 AfterPubSubConnectionInstantiationEvent: [RegisterReAuthForPubSub()],
148 AfterAsyncClusterInstantiationEvent: [RegisterReAuthForAsyncClusterNodes()],
149 AsyncAfterConnectionReleasedEvent: [
150 AsyncReAuthConnectionListener(),
151 ],
152 }
154 # Reentrant so a finalizer/listener that runs on the same thread
155 # while the lock is held (e.g. a weakref.finalize callback fired
156 # from cyclic GC during an allocation inside register_listeners /
157 # unregister_listeners) can re-enter without deadlocking.
158 self._lock = threading.RLock()
159 self._async_lock = None
161 if event_listeners:
162 self.register_listeners(event_listeners)
164 def dispatch(self, event: object):
165 # Snapshot listeners under the lock, then release it before invoking
166 # them. Holding the lock across listener execution would turn any
167 # listener that calls register_listeners / unregister_listeners /
168 # dispatch back into the dispatcher into a deadlock.
169 with self._lock:
170 listeners = list(self._event_listeners_mapping.get(type(event), []))
171 for listener in listeners:
172 listener.listen(event)
174 async def dispatch_async(self, event: object):
175 if self._async_lock is None:
176 self._async_lock = asyncio.Lock()
178 # Snapshot listeners under the lock, then release it before awaiting
179 # them. See the note in dispatch(); the same rationale applies here
180 # for dispatch_async re-entry from within a listener.
181 async with self._async_lock:
182 listeners = list(self._event_listeners_mapping.get(type(event), []))
183 for listener in listeners:
184 await listener.listen(event)
186 def register_listeners(
187 self,
188 mappings: Dict[
189 Type[object],
190 List[Union[EventListenerInterface, AsyncEventListenerInterface]],
191 ],
192 ):
193 with self._lock:
194 for event_type in mappings:
195 if event_type in self._event_listeners_mapping:
196 self._event_listeners_mapping[event_type] = list(
197 set(
198 self._event_listeners_mapping[event_type]
199 + mappings[event_type]
200 )
201 )
202 else:
203 self._event_listeners_mapping[event_type] = mappings[event_type]
205 def unregister_listeners(
206 self,
207 mappings: Dict[
208 Type[object],
209 List[Union[EventListenerInterface, AsyncEventListenerInterface]],
210 ],
211 ):
212 with self._lock:
213 for event_type, to_remove in mappings.items():
214 current = self._event_listeners_mapping.get(event_type)
215 if not current:
216 continue
217 # Remove by identity to match register semantics and to avoid
218 # reliance on listener __eq__ implementations.
219 self._event_listeners_mapping[event_type] = [
220 listener
221 for listener in current
222 if all(listener is not target for target in to_remove)
223 ]
226class AfterConnectionReleasedEvent:
227 """
228 Event that will be fired before each command execution.
229 """
231 def __init__(self, connection):
232 self._connection = connection
234 @property
235 def connection(self):
236 return self._connection
239class AsyncAfterConnectionReleasedEvent(AfterConnectionReleasedEvent):
240 pass
243class AfterSlotsCacheRefreshEvent:
244 """
245 Event fired after NodesManager's slots cache is refreshed, either via a
246 full re-initialization or a MOVED-driven slot re-mapping. Signal-only;
247 carries no payload. Listeners typically reconcile per-node bookkeeping
248 (e.g. ClusterPubSub shard subscriptions).
249 """
251 pass
254class AsyncAfterSlotsCacheRefreshEvent(AfterSlotsCacheRefreshEvent):
255 pass
258class MaintenanceEvent:
259 """
260 Base class of the events a maintenance notification pushed by the server
261 produces while it relaxes timeouts: on a connection pool for a node handoff
262 (``MaintenanceState.MOVING``), or on a single connection for a shard
263 migration or failover (``MaintenanceState.MAINTENANCE``).
265 Dispatched synchronously, by both the sync and the async client, to the
266 ``event_dispatcher`` of the ``MaintNotificationsConfig`` the handler acted
267 with; listeners implement ``EventListenerInterface``.
269 :param connection_pool: The pool whose connections are affected. ``None``
270 when the notification was handled by a connection without a pool
271 handler, such as an OSS cluster node connection.
272 :param connection: The connection that received the notification. ``None``
273 when a pool-level handler had no connection to attribute it to.
274 :param state: The ``MaintenanceState`` the notification puts its source in.
275 :param notification: The ``MaintenanceNotification`` that was handled.
276 :param config: The ``MaintNotificationsConfig`` the handler acted with.
277 """
279 def __init__(
280 self,
281 connection_pool: Optional[object],
282 connection: Optional[object],
283 state: "MaintenanceState",
284 notification: Optional["MaintenanceNotification"],
285 config: "MaintNotificationsConfig",
286 ):
287 self._connection_pool = connection_pool
288 self._connection = connection
289 self._state = state
290 self._notification = notification
291 self._config = config
293 @property
294 def connection_pool(self) -> Optional[object]:
295 return self._connection_pool
297 @property
298 def connection(self) -> Optional[object]:
299 return self._connection
301 @property
302 def state(self) -> "MaintenanceState":
303 return self._state
305 @property
306 def notification(self) -> Optional["MaintenanceNotification"]:
307 return self._notification
309 @property
310 def config(self) -> "MaintNotificationsConfig":
311 return self._config
314class MaintenanceStartedEvent(MaintenanceEvent):
315 """
316 Event fired when a maintenance notification starts relaxing the timeouts of
317 its source. Paired with a ``MaintenanceCompletedEvent`` carrying the same
318 ``state`` and source.
319 """
321 pass
324class MaintenanceCompletedEvent(MaintenanceEvent):
325 """
326 Event fired when the timeout relaxation announced by a
327 ``MaintenanceStartedEvent`` is reverted: the completion notification
328 arrived, the handoff TTL expired, or the connection was closed while
329 still under maintenance. Also fired, with ``MaintenanceState.MAINTENANCE``,
330 when a handoff takes over a connection under maintenance: the connection
331 stays relaxed, but under the handoff's ``MOVING`` pair from then on. In
332 the last two cases ``notification`` is ``None``.
334 Not fired when a newer handoff superseded the one that completed; the
335 source stays relaxed until the newer one completes.
336 """
338 pass
341class ClientType(Enum):
342 SYNC = ("sync",)
343 ASYNC = ("async",)
346class AfterPooledConnectionsInstantiationEvent:
347 """
348 Event that will be fired after pooled connection instances was created.
349 """
351 def __init__(
352 self,
353 connection_pools: List,
354 client_type: ClientType,
355 credential_provider: Optional[CredentialProvider] = None,
356 ):
357 self._connection_pools = connection_pools
358 self._client_type = client_type
359 self._credential_provider = credential_provider
361 @property
362 def connection_pools(self):
363 return self._connection_pools
365 @property
366 def client_type(self) -> ClientType:
367 return self._client_type
369 @property
370 def credential_provider(self) -> Union[CredentialProvider, None]:
371 return self._credential_provider
374class AfterSingleConnectionInstantiationEvent:
375 """
376 Event that will be fired after single connection instances was created.
378 :param connection_lock: For sync client thread-lock should be provided,
379 for async asyncio.Lock
380 """
382 def __init__(
383 self,
384 connection,
385 client_type: ClientType,
386 connection_lock: Union[threading.RLock, asyncio.Lock],
387 ):
388 self._connection = connection
389 self._client_type = client_type
390 self._connection_lock = connection_lock
392 @property
393 def connection(self):
394 return self._connection
396 @property
397 def client_type(self) -> ClientType:
398 return self._client_type
400 @property
401 def connection_lock(self) -> Union[threading.RLock, asyncio.Lock]:
402 return self._connection_lock
405class AfterPubSubConnectionInstantiationEvent:
406 def __init__(
407 self,
408 pubsub_connection,
409 connection_pool,
410 client_type: ClientType,
411 connection_lock: Union[threading.RLock, asyncio.Lock],
412 ):
413 self._pubsub_connection = pubsub_connection
414 self._connection_pool = connection_pool
415 self._client_type = client_type
416 self._connection_lock = connection_lock
418 @property
419 def pubsub_connection(self):
420 return self._pubsub_connection
422 @property
423 def connection_pool(self):
424 return self._connection_pool
426 @property
427 def client_type(self) -> ClientType:
428 return self._client_type
430 @property
431 def connection_lock(self) -> Union[threading.RLock, asyncio.Lock]:
432 return self._connection_lock
435class AfterAsyncClusterInstantiationEvent:
436 """
437 Event that will be fired after async cluster instance was created.
439 Async cluster doesn't use connection pools,
440 instead ClusterNode object manages connections.
441 """
443 def __init__(
444 self,
445 nodes: dict,
446 credential_provider: Optional[CredentialProvider] = None,
447 ):
448 self._nodes = nodes
449 self._credential_provider = credential_provider
451 @property
452 def nodes(self) -> dict:
453 return self._nodes
455 @property
456 def credential_provider(self) -> Union[CredentialProvider, None]:
457 return self._credential_provider
460class OnCommandsFailEvent:
461 """
462 Event fired whenever a command fails during the execution.
463 """
465 def __init__(
466 self,
467 commands: tuple,
468 exception: Exception,
469 ):
470 self._commands = commands
471 self._exception = exception
473 @property
474 def commands(self) -> tuple:
475 return self._commands
477 @property
478 def exception(self) -> Exception:
479 return self._exception
482class AsyncOnCommandsFailEvent(OnCommandsFailEvent):
483 pass
486class ReAuthConnectionListener(EventListenerInterface):
487 """
488 Listener that performs re-authentication of given connection.
489 """
491 def listen(self, event: AfterConnectionReleasedEvent):
492 # It runs between commands, where an error would fail a command that
493 # did not cause it, so a failure is logged instead. The token stays
494 # pending on the connection.
495 try:
496 event.connection.re_auth()
497 except Exception as e:
498 _log_re_auth_failure(event.connection, e)
501class AsyncReAuthConnectionListener(AsyncEventListenerInterface):
502 """
503 Async listener that performs re-authentication of given connection.
504 """
506 async def listen(self, event: AsyncAfterConnectionReleasedEvent):
507 # It runs between commands, where an error would fail a command that
508 # did not cause it, so a failure is logged instead. The token stays
509 # pending on the connection.
510 try:
511 await event.connection.re_auth()
512 except Exception as e:
513 _log_re_auth_failure(event.connection, e)
516class RegisterReAuthForPooledConnections(EventListenerInterface):
517 """
518 Listener that registers a re-authentication callback for pooled connections.
519 Required by :class:`StreamingCredentialProvider`.
520 """
522 def __init__(self):
523 self._event = None
525 def listen(self, event: AfterPooledConnectionsInstantiationEvent):
526 if isinstance(event.credential_provider, StreamingCredentialProvider):
527 self._event = event
529 if event.client_type == ClientType.SYNC:
530 event.credential_provider.on_next(self._re_auth)
531 event.credential_provider.on_error(self._raise_on_error)
532 else:
533 event.credential_provider.on_next(self._re_auth_async)
534 event.credential_provider.on_error(self._raise_on_error_async)
536 def _re_auth(self, token):
537 first_error = None
538 for pool in self._event.connection_pools:
539 try:
540 pool.re_auth_callback(token)
541 except Exception as e:
542 if first_error is None:
543 first_error = e
544 if first_error is not None:
545 raise first_error
547 async def _re_auth_async(self, token):
548 first_error = None
549 for pool in self._event.connection_pools:
550 try:
551 await pool.re_auth_callback(token)
552 except Exception as e:
553 if first_error is None:
554 first_error = e
555 if first_error is not None:
556 raise first_error
558 def _raise_on_error(self, error: Exception):
559 raise EventException(error, self._event)
561 async def _raise_on_error_async(self, error: Exception):
562 raise EventException(error, self._event)
565class RegisterReAuthForSingleConnection(EventListenerInterface):
566 """
567 Listener that registers a re-authentication callback for single connection.
568 Required by :class:`StreamingCredentialProvider`.
569 """
571 def __init__(self):
572 self._event = None
574 def listen(self, event: AfterSingleConnectionInstantiationEvent):
575 if isinstance(
576 event.connection.credential_provider, StreamingCredentialProvider
577 ):
578 self._event = event
580 if event.client_type == ClientType.SYNC:
581 event.connection.credential_provider.on_next(self._re_auth)
582 event.connection.credential_provider.on_error(self._raise_on_error)
583 else:
584 event.connection.credential_provider.on_next(self._re_auth_async)
585 event.connection.credential_provider.on_error(
586 self._raise_on_error_async
587 )
589 def _re_auth(self, token):
590 with self._event.connection_lock:
591 self._event.connection.send_command(
592 "AUTH", token.try_get("oid"), token.get_value()
593 )
594 self._event.connection.read_response()
596 async def _re_auth_async(self, token):
597 async with self._event.connection_lock:
598 await self._event.connection.send_command(
599 "AUTH", token.try_get("oid"), token.get_value()
600 )
601 await self._event.connection.read_response()
603 def _raise_on_error(self, error: Exception):
604 raise EventException(error, self._event)
606 async def _raise_on_error_async(self, error: Exception):
607 raise EventException(error, self._event)
610class RegisterReAuthForAsyncClusterNodes(EventListenerInterface):
611 def __init__(self):
612 self._event = None
614 def listen(self, event: AfterAsyncClusterInstantiationEvent):
615 if isinstance(event.credential_provider, StreamingCredentialProvider):
616 self._event = event
617 event.credential_provider.on_next(self._re_auth)
618 event.credential_provider.on_error(self._raise_on_error)
620 async def _re_auth(self, token: TokenInterface):
621 nodes = self._event.nodes
622 first_error = None
623 # Iterate a snapshot: a topology refresh can add and remove nodes while
624 # a node is being re-authenticated. A node that is no longer the one cached
625 # under its key is skipped: it is being closed, even if a later refresh
626 # re-added its address as a new node. Nodes added in the meantime connect
627 # with the current credentials and need no AUTH.
628 for key, node in tuple(nodes.items()):
629 if nodes.get(key) is node:
630 try:
631 await node.re_auth_callback(token)
632 except Exception as e:
633 if first_error is None:
634 first_error = e
635 if first_error is not None:
636 raise first_error
638 async def _raise_on_error(self, error: Exception):
639 raise EventException(error, self._event)
642class RegisterReAuthForPubSub(EventListenerInterface):
643 def __init__(self):
644 self._connection = None
645 self._connection_pool = None
646 self._client_type = None
647 self._connection_lock = None
648 self._event = None
650 def listen(self, event: AfterPubSubConnectionInstantiationEvent):
651 if isinstance(
652 event.pubsub_connection.credential_provider, StreamingCredentialProvider
653 ) and check_protocol_version(event.pubsub_connection.get_protocol(), 3):
654 self._event = event
655 self._connection = event.pubsub_connection
656 self._connection_pool = event.connection_pool
657 self._client_type = event.client_type
658 self._connection_lock = event.connection_lock
660 if self._client_type == ClientType.SYNC:
661 self._connection.credential_provider.on_next(self._re_auth)
662 self._connection.credential_provider.on_error(self._raise_on_error)
663 else:
664 self._connection.credential_provider.on_next(self._re_auth_async)
665 self._connection.credential_provider.on_error(
666 self._raise_on_error_async
667 )
669 def _re_auth(self, token: TokenInterface):
670 with self._connection_lock:
671 self._connection.send_command(
672 "AUTH", token.try_get("oid"), token.get_value()
673 )
674 self._connection.read_response()
676 self._connection_pool.re_auth_callback(token)
678 async def _re_auth_async(self, token: TokenInterface):
679 async with self._connection_lock:
680 await self._connection.send_command(
681 "AUTH", token.try_get("oid"), token.get_value()
682 )
683 await self._connection.read_response()
685 await self._connection_pool.re_auth_callback(token)
687 def _raise_on_error(self, error: Exception):
688 raise EventException(error, self._event)
690 async def _raise_on_error_async(self, error: Exception):
691 raise EventException(error, self._event)
694class InitializeConnectionCountObservability(EventListenerInterface):
695 """
696 Listener that initializes connection count observability.
697 """
699 @deprecated_function(
700 reason="Connection count is now tracked via record_connection_count(). "
701 "This functionality will be removed in the next major version",
702 version="7.4.0",
703 )
704 def listen(self, event: AfterPooledConnectionsInstantiationEvent):
705 # Initialize gauge only once, subsequent calls won't have an affect.
706 # Note: init_connection_count() and register_pools_connection_count()
707 # are deprecated and will emit their own warnings.
708 init_connection_count()
710 # Register pools for connection count observability.
711 register_pools_connection_count(event.connection_pools)