API refactor
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2025-10-07 16:25:52 +09:00
parent 76d0d86211
commit 91c7e04474
1171 changed files with 81940 additions and 44117 deletions

View File

@@ -5,8 +5,12 @@ from typing import Optional
from redis.client import Redis
from redis.commands import SentinelCommands
from redis.connection import Connection, ConnectionPool, SSLConnection
from redis.exceptions import ConnectionError, ReadOnlyError, ResponseError, TimeoutError
from redis.utils import str_if_bytes
from redis.exceptions import (
ConnectionError,
ReadOnlyError,
ResponseError,
TimeoutError,
)
class MasterNotFoundError(ConnectionError):
@@ -24,7 +28,10 @@ class SentinelManagedConnection(Connection):
def __repr__(self):
pool = self.connection_pool
s = f"{type(self).__name__}<service={pool.service_name}%s>"
s = (
f"<{type(self).__module__}.{type(self).__name__}"
f"(service={pool.service_name}%s)>"
)
if self.host:
host_info = f",host={self.host},port={self.port}"
s = s % host_info
@@ -32,11 +39,11 @@ class SentinelManagedConnection(Connection):
def connect_to(self, address):
self.host, self.port = address
super().connect()
if self.connection_pool.check_connection:
self.send_command("PING")
if str_if_bytes(self.read_response()) != "PONG":
raise ConnectionError("PING failed")
self.connect_check_health(
check_health=self.connection_pool.check_connection,
retry_socket_connect=False,
)
def _connect_retry(self):
if self._sock:
@@ -142,9 +149,11 @@ class SentinelConnectionPool(ConnectionPool):
def __init__(self, service_name, sentinel_manager, **kwargs):
kwargs["connection_class"] = kwargs.get(
"connection_class",
SentinelManagedSSLConnection
if kwargs.pop("ssl", False)
else SentinelManagedConnection,
(
SentinelManagedSSLConnection
if kwargs.pop("ssl", False)
else SentinelManagedConnection
),
)
self.is_master = kwargs.pop("is_master", True)
self.check_connection = kwargs.pop("check_connection", False)
@@ -162,7 +171,10 @@ class SentinelConnectionPool(ConnectionPool):
def __repr__(self):
role = "master" if self.is_master else "slave"
return f"{type(self).__name__}<service={self.service_name}({role})"
return (
f"<{type(self).__module__}.{type(self).__name__}"
f"(service={self.service_name}({role}))>"
)
def reset(self):
super().reset()
@@ -221,6 +233,7 @@ class Sentinel(SentinelCommands):
sentinels,
min_other_sentinels=0,
sentinel_kwargs=None,
force_master_ip=None,
**connection_kwargs,
):
# if sentinel_kwargs isn't defined, use the socket_* options from
@@ -237,6 +250,7 @@ class Sentinel(SentinelCommands):
]
self.min_other_sentinels = min_other_sentinels
self.connection_kwargs = connection_kwargs
self._force_master_ip = force_master_ip
def execute_command(self, *args, **kwargs):
"""
@@ -244,16 +258,27 @@ class Sentinel(SentinelCommands):
once - If set to True, then execute the resulting command on a single
node at random, rather than across the entire sentinel cluster.
"""
once = bool(kwargs.get("once", False))
if "once" in kwargs.keys():
kwargs.pop("once")
once = bool(kwargs.pop("once", False))
# Check if command is supposed to return the original
# responses instead of boolean value.
return_responses = bool(kwargs.pop("return_responses", False))
if once:
random.choice(self.sentinels).execute_command(*args, **kwargs)
else:
for sentinel in self.sentinels:
sentinel.execute_command(*args, **kwargs)
return True
response = random.choice(self.sentinels).execute_command(*args, **kwargs)
if return_responses:
return [response]
else:
return True if response else False
responses = []
for sentinel in self.sentinels:
responses.append(sentinel.execute_command(*args, **kwargs))
if return_responses:
return responses
return all(responses)
def __repr__(self):
sentinel_addresses = []
@@ -261,7 +286,10 @@ class Sentinel(SentinelCommands):
sentinel_addresses.append(
"{host}:{port}".format_map(sentinel.connection_pool.connection_kwargs)
)
return f'{type(self).__name__}<sentinels=[{",".join(sentinel_addresses)}]>'
return (
f"<{type(self).__module__}.{type(self).__name__}"
f"(sentinels=[{','.join(sentinel_addresses)}])>"
)
def check_master_state(self, state, service_name):
if not state["is_master"] or state["is_sdown"] or state["is_odown"]:
@@ -293,7 +321,13 @@ class Sentinel(SentinelCommands):
sentinel,
self.sentinels[0],
)
return state["ip"], state["port"]
ip = (
self._force_master_ip
if self._force_master_ip is not None
else state["ip"]
)
return ip, state["port"]
error_info = ""
if len(collected_errors) > 0:
@@ -330,6 +364,8 @@ class Sentinel(SentinelCommands):
):
"""
Returns a redis client instance for the ``service_name`` master.
Sentinel client will detect failover and reconnect Redis clients
automatically.
A :py:class:`~redis.sentinel.SentinelConnectionPool` class is
used to retrieve the master's address before establishing a new