Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 6 additions & 14 deletions src/tools/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,21 +182,13 @@ async def scan_all_keys(
"""
try:
r = RedisConnectionManager.get_connection()
all_keys = []
cursor = 0

while True:
cursor, keys = r.scan(cursor=cursor, match=pattern, count=batch_size)

# Convert bytes to strings if needed and add to results
decoded_keys = [
key.decode("utf-8") if isinstance(key, bytes) else key for key in keys
]
all_keys.extend(decoded_keys)

# Break when scan is complete (cursor returns to 0)
if cursor == 0:
break
# scan_iter handles the cursor, including the per-node cursors in cluster mode
# Convert bytes to strings if needed
all_keys = [
key.decode("utf-8") if isinstance(key, bytes) else key
for key in r.scan_iter(match=pattern, count=batch_size)
]

return all_keys
except RedisError as e:
Expand Down
31 changes: 31 additions & 0 deletions tests/tools/test_misc.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,39 @@
from functools import partial
from unittest.mock import MagicMock, patch

import pytest
from redis.cluster import RedisCluster
from redis.exceptions import DataError

import src.tools.misc as misc


@pytest.mark.asyncio
async def test_scan_all_keys_cluster_mode():
"""RedisCluster.scan returns a cursor per node, not a single integer."""
pages = {
0: ({"node-a": 7, "node-b": 0}, [b"user:1", b"user:2"]),
7: ({"node-a": 0}, [b"user:3"]),
}

def scan(cursor=0, **kwargs):
if isinstance(cursor, dict):
raise DataError("Invalid input of type: 'dict'.")
return pages[cursor]

cluster = MagicMock(spec=RedisCluster)
cluster.scan.side_effect = scan
# Run redis-py's own cluster iteration on top of the mocked SCAN
cluster.scan_iter = partial(RedisCluster.scan_iter, cluster)

with patch.object(
misc.RedisConnectionManager, "get_connection", return_value=cluster
):
result = await misc.scan_all_keys("user:*")

assert result == ["user:1", "user:2", "user:3"]


@pytest.mark.asyncio
async def test_search_redis_documents_url_not_configured(monkeypatch):
"""Return a clear error if MCP_DOCS_SEARCH_URL is not set for search_redis_documents."""
Expand Down
Loading