1import asyncio
2import functools
3import logging
4from typing import TYPE_CHECKING, Any, Awaitable, Callable
5
6from redis.asyncio.observability.recorder import (
7 record_connection_handoff,
8 record_connection_relaxed_timeout,
9 record_maint_notification_count,
10)
11from redis.event import (
12 MaintenanceCompletedEvent,
13 MaintenanceEvent,
14 MaintenanceStartedEvent,
15)
16from redis.maint_notifications import (
17 MaintenanceNotification,
18 MaintenanceState,
19 MaintNotificationsConfig,
20 NodeMovingNotification,
21 OSSNodeMigratedNotification,
22 OSSNodeMigratingNotification,
23 _dispatch_maintenance_event,
24 _get_maintenance_notification_name,
25 _get_maintenance_notification_type,
26 _should_skip_connection_timeout_update,
27)
28from redis.observability.attributes import get_pool_name
29
30if TYPE_CHECKING:
31 from redis.asyncio.cluster import RedisCluster
32 from redis.asyncio.connection import AsyncMaintNotificationsAbstractConnection
33
34logger = logging.getLogger(__name__)
35
36_ScheduledCallback = Callable[..., Awaitable[None]]
37
38
39def _log_task_exception(message: str, task: "asyncio.Task[Any]") -> None:
40 """Task done-callback that surfaces a failed task's exception in the logs.
41
42 Without it, an unhandled exception in a fire-and-forget task is only
43 reported by asyncio as a noisy "Task exception was never retrieved"
44 warning. Retrieving the exception here suppresses that warning and logs a
45 meaningful error instead. Cancellation is expected and left unlogged.
46
47 Bind ``message`` with ``functools.partial`` before passing to
48 ``add_done_callback`` (which supplies ``task``).
49 """
50 try:
51 exc = task.exception()
52 except asyncio.CancelledError:
53 return
54 if exc:
55 logger.error(message, exc_info=exc)
56
57
58def add_debug_log_for_notification(
59 connection: object,
60 notification: str | MaintenanceNotification,
61) -> None:
62 if not logger.isEnabledFor(logging.DEBUG):
63 return
64
65 details = "no connection"
66 try:
67 extract = getattr(connection, "extract_connection_details", None)
68 if callable(extract):
69 details = extract()
70 except (AttributeError, OSError, TypeError):
71 pass
72
73 logger.debug(
74 f"Handling maintenance notification: {notification}, "
75 f"with connection: {connection}, {details}",
76 )
77
78
79class AsyncMaintNotificationsPoolHandler:
80 def __init__(
81 self,
82 pool: Any,
83 config: MaintNotificationsConfig,
84 ) -> None:
85 self.pool = pool
86 self.config = config
87 self._processed_notifications: set[MaintenanceNotification] = set()
88 self._scheduled_tasks: set[asyncio.Task[None]] = set()
89 # The handoffs whose scheduled cleanup has not finished yet
90 self._pending_handoffs: set[NodeMovingNotification] = set()
91 self._lock = asyncio.Lock()
92 self.connection: Any | None = None
93
94 def set_connection(
95 self, connection: "AsyncMaintNotificationsAbstractConnection"
96 ) -> None:
97 self.connection = connection
98
99 def get_handler_for_connection(self) -> "AsyncMaintNotificationsPoolHandler":
100 # Copy all data that should be shared between connections, while each
101 # connection gets its own handler instance and current connection state.
102 copy = AsyncMaintNotificationsPoolHandler(self.pool, self.config)
103 copy._processed_notifications = self._processed_notifications
104 copy._scheduled_tasks = self._scheduled_tasks
105 copy._pending_handoffs = self._pending_handoffs
106 copy._lock = self._lock
107 copy.connection = None
108 return copy
109
110 async def remove_expired_notifications(self) -> None:
111 async with self._lock:
112 for notification in tuple(self._processed_notifications):
113 if notification.is_expired():
114 self._processed_notifications.remove(notification)
115
116 async def handle_notification(self, notification: MaintenanceNotification) -> None:
117 await self.remove_expired_notifications()
118
119 if isinstance(notification, NodeMovingNotification):
120 await self.handle_node_moving_notification(notification)
121 else:
122 logger.error(f"Unhandled notification type: {notification}")
123
124 async def handle_node_moving_notification(
125 self, notification: NodeMovingNotification
126 ) -> None:
127 if (
128 not self.config.proactive_reconnect
129 and not self.config.is_relaxed_timeouts_enabled()
130 ):
131 return
132
133 async with self._lock:
134 if notification in self._processed_notifications:
135 # nothing to do in the connection pool handling
136 # the notification has already been handled or is expired
137 # just return
138 return
139 if logger.isEnabledFor(logging.DEBUG):
140 logger.debug(
141 f"Handling node MOVING notification: {notification}, "
142 f"with connection: {self.connection}, connected to ip "
143 f"{self.connection.get_resolved_ip() if self.connection else None}"
144 )
145 # Get the current connected address - if any
146 # This is the address that is being moved
147 # and we need to handle only connections
148 # connected to the same address
149 moving_address_src = (
150 self.connection.getpeername() if self.connection else None
151 )
152
153 # Reported before the pool is relaxed: taking over a connection
154 # under maintenance completes that connection's pair, and a
155 # listener must see the handoff's pair open by then rather than
156 # no relaxation at all.
157 self._dispatch_handoff_event(MaintenanceStartedEvent, notification)
158
159 try:
160 # The async pool owns the active/free connection collections
161 # and asyncio.Lock is not reentrant, so the whole MOVING pool
162 # mutation has to be one pool-owned atomic operation. The
163 # handler still owns the notification policy and passes the
164 # already-decided inputs.
165 await self.pool.apply_moving_notification(
166 notification=notification,
167 config=self.config,
168 moving_address_src=moving_address_src,
169 run_proactive_reconnect=(
170 self.config.proactive_reconnect
171 and notification.new_node_host is not None
172 ),
173 )
174
175 if (
176 self.config.proactive_reconnect
177 and notification.new_node_host is None
178 ):
179 self._schedule(
180 notification.ttl / 2,
181 self.run_proactive_reconnect,
182 moving_address_src,
183 )
184
185 self._schedule(
186 notification.ttl,
187 self.handle_node_moved_notification,
188 notification,
189 )
190 self._pending_handoffs.add(notification)
191 except BaseException:
192 # The relaxation reported above was not applied, or has no
193 # cleanup to end it: close its pair
194 self._dispatch_handoff_event(MaintenanceCompletedEvent, notification)
195 raise
196
197 await record_connection_handoff(
198 pool_name=get_pool_name(self.pool),
199 )
200
201 self._processed_notifications.add(notification)
202
203 def _dispatch_handoff_event(
204 self,
205 event_type: type[MaintenanceEvent],
206 notification: NodeMovingNotification,
207 ) -> None:
208 """
209 Report a handoff's relaxation. The events report relaxed timeouts; a
210 handoff handled only for the proactive reconnect relaxes nothing.
211 """
212 if self.config.is_relaxed_timeouts_enabled():
213 _dispatch_maintenance_event(
214 self.config,
215 event_type(
216 connection_pool=self.pool,
217 connection=self.connection,
218 state=MaintenanceState.MOVING,
219 notification=notification,
220 config=self.config,
221 ),
222 )
223
224 async def run_proactive_reconnect(
225 self, moving_address_src: str | None = None
226 ) -> None:
227 """
228 Run proactive reconnect for the pool.
229 Active connections are marked for reconnect after they complete the current command.
230 Inactive connections are disconnected and will be connected on next use.
231 """
232 async with self._lock:
233 # This delayed reconnect must be atomic for the same reason as the
234 # initial MOVING mutation: a connection can move between active and
235 # free lists while another task is acquiring or releasing it.
236 await self.pool.run_proactive_reconnect(
237 moving_address_src=moving_address_src,
238 )
239
240 async def handle_node_moved_notification(
241 self, notification: NodeMovingNotification
242 ) -> bool:
243 """
244 Handle the cleanup after a node moving notification expires.
245
246 Returns whether the cleanup reverted the connection kwargs; it does not
247 when a newer MOVING notification has superseded this one.
248 """
249 async with self._lock:
250 return await self._revert_node_moved_notification(notification)
251
252 async def _revert_node_moved_notification(
253 self, notification: NodeMovingNotification
254 ) -> bool:
255 # Runs under self._lock
256 notification_hash = hash(notification)
257
258 if logger.isEnabledFor(logging.DEBUG):
259 logger.debug(
260 f"Reverting temporary changes related to notification: {notification}, "
261 f"with connection: {self.connection}, connected to ip "
262 f"{self.connection.get_resolved_ip() if self.connection else None}"
263 )
264 reset_relaxed_timeout = self.config.is_relaxed_timeouts_enabled()
265 reset_host_address = self.config.proactive_reconnect
266
267 # Cleanup has to reset future connection kwargs and existing
268 # matching connections together under the pool lock. Splitting it
269 # lets an acquire/release interleave and leaves stale MOVING state.
270 reverted = await self.pool.cleanup_moving_notification(
271 notification_hash=notification_hash,
272 reset_relaxed_timeout=reset_relaxed_timeout,
273 reset_host_address=reset_host_address,
274 )
275
276 # Discarded once the cleanup is done, so one cancelled halfway is
277 # still run by cancel_scheduled_tasks(), and before the listeners run
278 self._pending_handoffs.discard(notification)
279 # A newer MOVING notification has superseded this one when the
280 # kwargs were not reverted: the pool stays relaxed until it expires.
281 if reverted:
282 self._dispatch_handoff_event(MaintenanceCompletedEvent, notification)
283 return reverted
284
285 def _schedule(
286 self,
287 delay: float,
288 callback: _ScheduledCallback,
289 *args: Any,
290 ) -> None:
291 # Record the absolute deadline now so that any lag between create_task
292 # and the task's first execution slice does not push the fire time out.
293 deadline = asyncio.get_running_loop().time() + delay
294 task = asyncio.create_task(self._run_after(deadline, callback, *args))
295 self._scheduled_tasks.add(task)
296 task.add_done_callback(self._scheduled_tasks.discard)
297 task.add_done_callback(
298 functools.partial(
299 _log_task_exception,
300 "Error handling scheduled maintenance notification",
301 )
302 )
303
304 async def _run_after(
305 self,
306 deadline: float,
307 callback: _ScheduledCallback,
308 *args: Any,
309 ) -> None:
310 remaining = deadline - asyncio.get_running_loop().time()
311 if remaining > 0:
312 await asyncio.sleep(remaining)
313 await callback(*args)
314
315 async def cancel_scheduled_tasks(self) -> None:
316 # Taken under the lock so a MOVING still being handled finishes, and
317 # schedules its cleanup, before the snapshot. The cleanups take the
318 # lock themselves, so they are awaited after it is released.
319 async with self._lock:
320 # A cancelled aclose() can leave handoffs whose tasks are already
321 # gone: a retry still has to run their cleanups
322 if not self._scheduled_tasks and not self._pending_handoffs:
323 return
324 pending_handoffs = tuple(self._pending_handoffs)
325 tasks = tuple(self._scheduled_tasks)
326 for task in tasks:
327 task.cancel()
328 await asyncio.gather(*tasks, return_exceptions=True)
329 # The pool can be reused after aclose(): run the cancelled MOVING
330 # cleanups now so the temporary host and relaxed timeouts do not stay
331 # in its connection kwargs, and forget the handoffs so the server can
332 # redeliver a still-active MOVING to the reused pool.
333 for notification in pending_handoffs:
334 async with self._lock:
335 # A concurrent aclose() may have run this cleanup already
336 if notification not in self._pending_handoffs:
337 continue
338 reverted = await self._revert_node_moved_notification(notification)
339 if not reverted:
340 # Closing ends the relaxation of a superseded handoff too
341 self._dispatch_handoff_event(MaintenanceCompletedEvent, notification)
342 self._processed_notifications.discard(notification)
343
344
345class AsyncMaintNotificationsConnectionHandler:
346 def __init__(
347 self,
348 connection: "AsyncMaintNotificationsAbstractConnection",
349 config: MaintNotificationsConfig,
350 ) -> None:
351 self.connection = connection
352 self.config = config
353
354 def _get_pool(self) -> Any | None:
355 """
356 Get the pool from the connection's pool handler, or None for
357 standalone connections without a pool.
358 """
359 pool_handler = getattr(
360 self.connection, "_maint_notifications_pool_handler", None
361 )
362 if pool_handler:
363 return getattr(pool_handler, "pool", None)
364 return None
365
366 def _get_pool_name(self) -> str:
367 """
368 Get the pool name from the connection's pool handler.
369 Falls back to connection representation if pool is not available.
370 """
371 pool = self._get_pool()
372 if pool:
373 return get_pool_name(pool)
374 # Fallback for standalone connections without a pool
375 return repr(self.connection)
376
377 async def handle_notification(self, notification: MaintenanceNotification) -> None:
378 # 1 for start, 0 for end notification type, None for unknown.
379 notification_type = _get_maintenance_notification_type(notification)
380 maint_notification = _get_maintenance_notification_name(notification)
381
382 await record_maint_notification_count(
383 server_address=self.connection.host,
384 server_port=self.connection.port,
385 network_peer_address=self.connection.host,
386 network_peer_port=self.connection.port,
387 maint_notification=maint_notification,
388 )
389
390 if notification_type is None:
391 logger.error(f"Unhandled notification type: {notification}")
392 return
393
394 if notification_type:
395 await self.handle_maintenance_start_notification(
396 MaintenanceState.MAINTENANCE, notification
397 )
398 else:
399 await self.handle_maintenance_completed_notification(
400 notification=notification
401 )
402
403 async def handle_maintenance_start_notification(
404 self,
405 maintenance_state: MaintenanceState,
406 notification: MaintenanceNotification,
407 ) -> None:
408 add_debug_log_for_notification(self.connection, notification)
409
410 if _should_skip_connection_timeout_update(
411 self.connection.maintenance_state, self.config
412 ):
413 return
414
415 self.connection.maintenance_state = maintenance_state
416 self.connection.set_tmp_settings(
417 tmp_relaxed_timeout=self.config.relaxed_timeout
418 )
419 self.connection.update_current_socket_timeout(self.config.relaxed_timeout)
420 if isinstance(notification, OSSNodeMigratingNotification):
421 # add the notification id to the set of processed start maint notifications
422 # this is used to skip the unrelaxing of the timeouts if we have received more than
423 # one start notification before the final end notification
424 self.connection.add_maint_start_notification(notification.id)
425
426 maint_notification = _get_maintenance_notification_name(notification)
427 await record_connection_relaxed_timeout(
428 connection_name=self._get_pool_name(),
429 maint_notification=maint_notification,
430 relaxed=True,
431 )
432
433 _dispatch_maintenance_event(
434 self.config,
435 MaintenanceStartedEvent(
436 connection_pool=self._get_pool(),
437 connection=self.connection,
438 state=maintenance_state,
439 notification=notification,
440 config=self.config,
441 ),
442 )
443
444 async def handle_maintenance_completed_notification(self, **kwargs: Any) -> None:
445 # Only reset timeouts if state is not MOVING and relaxed timeouts are enabled
446 if _should_skip_connection_timeout_update(
447 self.connection.maintenance_state, self.config
448 ):
449 return
450
451 # A completion can reach a connection whose start went to another one,
452 # or none at all; only a connection that was relaxed has a start event
453 # to pair the completion with
454 was_relaxed = self.connection.maintenance_state == MaintenanceState.MAINTENANCE
455
456 notification = None
457 if kwargs.get("notification"):
458 notification = kwargs["notification"]
459 add_debug_log_for_notification(
460 self.connection, notification if notification else "MAINTENANCE_COMPLETED"
461 )
462 self.connection.reset_tmp_settings(reset_relaxed_timeout=True)
463 # Maintenance completed - reset the connection
464 # timeouts by providing -1 as the relaxed timeout
465 self.connection.update_current_socket_timeout(-1)
466 self.connection.maintenance_state = MaintenanceState.NONE
467 # reset the sets that keep track of received start maint
468 # notifications and skipped end maint notifications
469 self.connection.reset_received_notifications()
470
471 if notification:
472 maint_notification = _get_maintenance_notification_name(notification)
473 await record_connection_relaxed_timeout(
474 connection_name=self._get_pool_name(),
475 maint_notification=maint_notification,
476 relaxed=False,
477 )
478
479 if was_relaxed:
480 _dispatch_maintenance_event(
481 self.config,
482 MaintenanceCompletedEvent(
483 connection_pool=self._get_pool(),
484 connection=self.connection,
485 state=MaintenanceState.MAINTENANCE,
486 notification=notification,
487 config=self.config,
488 ),
489 )
490
491
492class AsyncOSSMaintNotificationsHandler:
493 """
494 Cluster-wide handler for OSS (open-source) cluster maintenance notifications.
495
496 Reacts to SMIGRATED (slot migration completed) push notifications and
497 triggers topology re-initialization via nodes_manager.initialize().
498
499 Lock discipline: _lock is held across the whole pool mutation, including
500 await initialize(), so the topology refresh and the subsequent connection
501 marking/disconnect happen as one atomic operation — releasing the lock
502 mid-mutation would let other tasks observe partial state.
503
504 Re-entrancy is not a deadlock risk here even though asyncio.Lock is
505 non-reentrant: initialize() may dispatch commands whose responses carry new
506 push notifications, but handle_notification schedules the actual handling as
507 a separate background task rather than calling into it inline, so the
508 re-entrant arrival never tries to re-acquire the lock on this call stack.
509 The cheap _in_progress/_processed dedup that gates that scheduling runs
510 without the lock — those sets are only mutated from the single event loop.
511
512 For the same reason the sync handler's lock-ordering rule (acquire
513 NodesManager._initialization_lock before the handler's _lock) does not apply
514 here: because the handling never runs inline on the call stack that is inside
515 initialize(), no task ever holds NodesManager._initialize_lock while waiting
516 for this _lock, so the two can be acquired in this order safely. The
517 divergence from the sync handler is deliberate, not drift.
518 """
519
520 def __init__(
521 self,
522 cluster_client: "RedisCluster",
523 config: MaintNotificationsConfig,
524 ) -> None:
525 self.cluster_client = cluster_client
526 self.config = config
527 self._processed_notifications: set[MaintenanceNotification] = set()
528 self._in_progress: set[MaintenanceNotification] = set()
529 self._lock = asyncio.Lock()
530 self._background_tasks: set[asyncio.Task] = set()
531
532 async def remove_expired_notifications(self) -> None:
533 async with self._lock:
534 for n in tuple(self._processed_notifications):
535 if n.is_expired():
536 self._processed_notifications.remove(n)
537
538 async def handle_notification(self, notification: MaintenanceNotification) -> None:
539 # Synchronous pre-dedup BEFORE scheduling a task.
540 #
541 # The same SMIGRATED notification is delivered by the server on every
542 # connection, so under load this callback fires many times for the same
543 # notification. Without this guard we would schedule one background task
544 # per arrival - a flood of tasks that each acquire the lock and dedup,
545 # saturating the single event loop. Reserving the notification in
546 # _in_progress here (and skipping if already in-progress/processed) caps
547 # it at exactly ONE handling task per unique notification.
548 #
549 # These sets are only mutated from the single event loop, so this
550 # check-and-add is race-free without holding the lock.
551 if (
552 notification in self._in_progress
553 or notification in self._processed_notifications
554 ):
555 return
556 self._in_progress.add(notification)
557
558 # Schedule as a background task so the parser's read path is not blocked.
559 # This also breaks the inline call chain that would otherwise deadlock:
560 # initialize() dispatches commands whose responses may carry more push
561 # notifications; as a separate task it can run while this one awaits.
562 #
563 # If scheduling the task (or wiring its callbacks) fails, release the
564 # in-progress reservation made above. Otherwise the notification would be
565 # stuck in _in_progress forever - the dedup guard would skip it on every
566 # future arrival, and _do_handle_notification's finally (which normally
567 # clears it) never runs because the task was never started.
568 try:
569 task = asyncio.get_running_loop().create_task(
570 self._do_handle_notification(notification)
571 )
572 self._background_tasks.add(task)
573 task.add_done_callback(self._background_tasks.discard)
574 task.add_done_callback(
575 functools.partial(
576 _log_task_exception,
577 "Error handling maintenance notification background task",
578 )
579 )
580 except Exception:
581 self._in_progress.discard(notification)
582 raise
583
584 async def _do_handle_notification(
585 self, notification: MaintenanceNotification
586 ) -> None:
587 try:
588 if isinstance(notification, OSSNodeMigratedNotification):
589 await self.handle_oss_maintenance_completed_notification(notification)
590 else:
591 logger.error(f"Unhandled notification type: {notification}")
592 finally:
593 # Release the in-progress reservation. On success the notification is
594 # also in _processed_notifications (so it won't be re-handled); on
595 # failure it is not, allowing a later retry.
596 self._in_progress.discard(notification)
597
598 async def handle_oss_maintenance_completed_notification(
599 self, notification: OSSNodeMigratedNotification
600 ) -> None:
601 await self.remove_expired_notifications()
602
603 async with self._lock:
604 # handle_notification already reserved this notification in
605 # _in_progress and guaranteed uniqueness; the processed check here is
606 # defensive (e.g. across handler copies sharing the same sets).
607 if notification in self._processed_notifications:
608 return
609 if logger.isEnabledFor(logging.DEBUG):
610 logger.debug(f"Handling SMIGRATED notification: {notification}")
611
612 # Extract the information about the src and destination nodes that are
613 # affected by the maintenance. nodes_to_slots_mapping structure:
614 # {
615 # "src_host:port": [
616 # {"dest_host:port": "slot_range"},
617 # ...
618 # ],
619 # ...
620 # }
621 additional_startup_nodes_info = []
622 affected_nodes = set()
623 for (
624 src_address,
625 dest_mappings,
626 ) in notification.nodes_to_slots_mapping.items():
627 src_host, src_port = src_address.rsplit(":", 1)
628 src_node = self.cluster_client.nodes_manager.get_node(
629 host=src_host, port=int(src_port)
630 )
631 if src_node is not None:
632 affected_nodes.add(src_node)
633 for dest_mapping in dest_mappings:
634 for dest_address in dest_mapping.keys():
635 dest_host, dest_port = dest_address.rsplit(":", 1)
636 additional_startup_nodes_info.append(
637 (dest_host, int(dest_port))
638 )
639 # Updates the cluster slots cache with the new slots mapping
640 # This will also update the nodes cache with the new nodes mapping
641 await self.cluster_client.nodes_manager.initialize(
642 additional_startup_nodes_info=additional_startup_nodes_info,
643 )
644
645 all_nodes = set(affected_nodes)
646 all_nodes = all_nodes.union(
647 self.cluster_client.nodes_manager.nodes_cache.values()
648 )
649 for current_node in all_nodes:
650 handoff_recorded = False
651 if current_node in affected_nodes:
652 # mark for reconnect all in-use connections to the node — this
653 # forces them to disconnect after completing their current command
654 free_set = set(current_node._free)
655 for conn in current_node._connections:
656 if conn not in free_set:
657 add_debug_log_for_notification(
658 conn, "SMIGRATED - mark for reconnect"
659 )
660 conn.mark_for_reconnect()
661 await record_connection_handoff(
662 pool_name=f"{current_node.host}:{current_node.port}"
663 )
664 handoff_recorded = True
665 else:
666 if logger.isEnabledFor(logging.DEBUG):
667 logger.debug(
668 f"SMIGRATED: Node {current_node.name} not affected "
669 f"by maintenance, skipping mark for reconnect"
670 )
671 if (
672 current_node
673 not in self.cluster_client.nodes_manager.nodes_cache.values()
674 ):
675 task = asyncio.get_running_loop().create_task(
676 current_node.disconnect_free_connections()
677 )
678 self._background_tasks.add(task)
679 task.add_done_callback(self._background_tasks.discard)
680 task.add_done_callback(
681 functools.partial(
682 _log_task_exception,
683 "Error disconnecting free connections after "
684 "maintenance notification",
685 )
686 )
687 if not handoff_recorded:
688 await record_connection_handoff(
689 pool_name=f"{current_node.host}:{current_node.port}"
690 )
691
692 self._processed_notifications.add(notification)