diff --git a/redisvl/redis/connection.py b/redisvl/redis/connection.py index 2b635210..f5dfd051 100644 --- a/redisvl/redis/connection.py +++ b/redisvl/redis/connection.py @@ -2,7 +2,7 @@ import os from collections.abc import Mapping from typing import Any, TypeVar, overload -from urllib.parse import parse_qs, unquote, urlencode, urlparse, urlunparse +from urllib.parse import unquote, unquote_plus, urlparse from warnings import warn from redis import Redis, RedisCluster @@ -116,8 +116,11 @@ def _strip_cluster_from_url_and_kwargs( ) -> tuple[str, dict[str, Any]]: """Remove 'cluster' parameter from URL query string and kwargs. - AsyncRedisCluster doesn't accept 'cluster' parameter, but it might be - present in the URL or kwargs for compatibility with other Redis clients. + Only RedisVL reads 'cluster', to choose a cluster client; redis-py's + Redis, AsyncRedis and AsyncRedisCluster reject it. The rest of the URL, + including any fragment, is kept as written: rebuilding it with urlunparse + would turn ``unix:///path`` into ``unix:/path``, which the sync client + rejects. Args: url: Redis URL that might contain cluster parameter @@ -126,29 +129,17 @@ def _strip_cluster_from_url_and_kwargs( Returns: Tuple of (cleaned_url, cleaned_kwargs) """ - # Parse the URL - parsed = urlparse(url) - - # Parse query parameters - query_params = parse_qs(parsed.query) - - # Remove 'cluster' parameter if present - query_params.pop("cluster", None) - - # Reconstruct the query string - new_query = urlencode(query_params, doseq=True) - - # Reconstruct the URL - cleaned_url = urlunparse( - ( - parsed.scheme, - parsed.netloc, - parsed.path, - parsed.params, - new_query, - parsed.fragment, - ) - ) + cleaned_url = url + # The fragment comes off first, so that nothing in it is read as a + # query parameter. + rest, has_fragment, fragment = url.partition("#") + base, has_query, query = rest.partition("?") + params = query.split("&") if has_query else [] + # Decode each key as parse_qs does, so redis-py sees the same parameters. + kept = [p for p in params if unquote_plus(p.split("=", 1)[0]) != "cluster"] + if len(kept) != len(params): + cleaned_url = f"{base}?{'&'.join(kept)}" if kept else base + cleaned_url += has_fragment + fragment # Remove 'cluster' from kwargs if present cleaned_kwargs = kwargs.copy() @@ -865,7 +856,11 @@ def get_redis_connection( elif is_cluster_url(url, **kwargs): client = RedisCluster.from_url(url, **kwargs) else: - client = Redis.from_url(url, **kwargs) + # Strip 'cluster' parameter as Redis doesn't accept it + cleaned_url, cleaned_kwargs = _strip_cluster_from_url_and_kwargs( + url, **kwargs + ) + client = Redis.from_url(cleaned_url, **cleaned_kwargs) _identify_client(client, kwargs.get("lib_name")) return client diff --git a/tests/unit/test_async_cluster_fix.py b/tests/unit/test_async_cluster_fix.py index 2cd41ddf..c96a38ad 100644 --- a/tests/unit/test_async_cluster_fix.py +++ b/tests/unit/test_async_cluster_fix.py @@ -1,8 +1,14 @@ -"""Unit tests for AsyncRedisCluster cluster parameter stripping fix (issue #346).""" +"""Unit tests for stripping the cluster parameter before redis-py sees it (issue #346).""" + +from unittest.mock import MagicMock, patch import pytest +from redis import Redis -from redisvl.redis.connection import _strip_cluster_from_url_and_kwargs +from redisvl.redis.connection import ( + RedisConnectionFactory, + _strip_cluster_from_url_and_kwargs, +) class TestAsyncClusterParameterStripping: @@ -81,3 +87,40 @@ def test_cluster_false_also_stripped(self): assert cleaned_url == "redis://localhost:7001" assert cleaned_kwargs == {} + + @pytest.mark.parametrize( + "url, expected, db", + [ + ("unix:///tmp/redis.sock", "unix:///tmp/redis.sock", 0), + ( + "unix:///tmp/redis.sock?cluster=false&db=1", + "unix:///tmp/redis.sock?db=1", + 1, + ), + ( + "redis://localhost:6379/0?cluster=false#local&db=1", + "redis://localhost:6379/0#local&db=1", + 0, + ), + ], + ) + def test_only_the_cluster_parameter_is_removed(self, url, expected, db): + """The unix:/// scheme and the fragment survive, and so does the database.""" + cleaned_url, _ = _strip_cluster_from_url_and_kwargs(url) + + assert cleaned_url == expected + # The sync client rejects unix:/path, and selects the db it parses here. + pool = Redis.from_url(cleaned_url).connection_pool + assert pool.connection_kwargs.get("db", 0) == db + + +def test_sync_connection_strips_cluster_parameter(): + """Redis rejects 'cluster', so cluster=False must not reach it.""" + with patch( + "redisvl.redis.connection.Redis.from_url", return_value=MagicMock() + ) as from_url: + RedisConnectionFactory.get_redis_connection( + "redis://localhost:6379?cluster=false", cluster=False + ) + + from_url.assert_called_once_with("redis://localhost:6379", protocol=2)