Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Migrator throws Moved error when connecting to cluster #550

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 6 additions & 4 deletions aredis_om/connections.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import os
from typing import Union

from . import redis


URL = os.environ.get("REDIS_OM_URL", None)


def get_redis_connection(**kwargs) -> redis.Redis:
def get_redis_connection(**kwargs) -> Union[redis.Redis, redis.RedisCluster]:
# Decode from UTF-8 by default
if "decode_responses" not in kwargs:
kwargs["decode_responses"] = True

# If someone passed in a 'url' parameter, or specified a REDIS_OM_URL
# environment variable, we'll create the Redis client from the URL.
url = kwargs.pop("url", URL)
cluster = kwargs.get("cluster", False) or "cluster=true" in str(url).lower()
conn_obj = redis.RedisCluster if cluster else redis.Redis
if url:
return redis.Redis.from_url(url, **kwargs)
return conn_obj.from_url(url, **kwargs)

return redis.Redis(**kwargs)
return conn_obj(**kwargs)
29 changes: 23 additions & 6 deletions aredis_om/model/migrations/migrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@
import logging
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
from typing import List, Optional, Union

from ... import redis


log = logging.getLogger(__name__)


import importlib # noqa: E402
import pkgutil # noqa: E402

Expand All @@ -30,7 +28,7 @@ def import_submodules(root_module_name: str):
)

for loader, module_name, is_pkg in pkgutil.walk_packages(
root_module.__path__, root_module.__name__ + "." # type: ignore
root_module.__path__, root_module.__name__ + "." # type: ignore
):
importlib.import_module(module_name)

Expand All @@ -39,7 +37,26 @@ def schema_hash_key(index_name):
return f"{index_name}:hash"


async def create_index(conn: redis.Redis, index_name, schema, current_hash):
async def _create_index_cluster(conn: redis.RedisCluster, index_name, schema, current_hash):
"""Create a search index on a Redis Cluster.
This is a workaround for the fact that the `FT.CREATE` command is not supported in Redis Cluster.
The implementation is same is `create_index` but with the following changes:
- `command` is passed as a list instead of a string
- The `FT.CREATE` command is executed only on primary nodes
"""
try:
await conn.ft(index_name).info()
except redis.ResponseError:
command = f"ft.create {index_name} {schema}".split()

await conn.execute_command(*command, target_nodes=redis.RedisCluster.PRIMARIES)
await conn.set(schema_hash_key(index_name), current_hash) # type: ignore


async def create_index(conn: [redis.Redis, redis.RedisCluster], index_name, schema, current_hash):
if type(conn) is redis.RedisCluster:
return _create_index_cluster(conn, index_name, schema, current_hash)

db_number = conn.connection_pool.connection_kwargs.get("db")
if db_number and db_number > 0:
raise MigrationError(
Expand Down Expand Up @@ -68,7 +85,7 @@ class IndexMigration:
schema: str
hash: str
action: MigrationAction
conn: redis.Redis
conn: Union[redis.Redis, redis.RedisCluster]
previous_hash: Optional[str] = None

async def run(self):
Expand Down
Loading