Skip to content

redis_service

redis_service

codex_platform.redis_service

Async Redis service with mixin architecture.

Requires redis.asyncio.Redis client. All methods are async-only.

Quick start::

from codex_platform.redis_service import RedisService

service = RedisService(client=redis_client)
await service.set_hash_json("my_key", "field", {"a": 1})

Custom composition::

from codex_platform.redis_service import BaseRedisService, HashMixin, StreamMixin

class MyRedisService(BaseRedisService, HashMixin, StreamMixin):
    pass

Key Registry::

from codex_platform.redis_service import UserKey

await service.get_hash_json(UserKey(), "profile", user_id=42)

Classes

BaseRedisService

Base class that holds a Redis connection.

Inherit from this class when building a service that wraps a Redis client but does not need the full :class:~codex_platform.redis_service.service.RedisService composition.

Source code in src/codex_platform/redis_service/base.py
class BaseRedisService:
    """Base class that holds a Redis connection.

    Inherit from this class when building a service that wraps a Redis client
    but does not need the full :class:`~codex_platform.redis_service.service.RedisService`
    composition.
    """

    def __init__(self, client: Redis) -> None:
        """Initialize the service with an existing async Redis client.

        Args:
            client: An already-constructed ``redis.asyncio.Redis`` instance.
        """
        self.redis_client = client
Functions
__init__(client)

Initialize the service with an existing async Redis client.

Parameters:

Name Type Description Default
client Redis

An already-constructed redis.asyncio.Redis instance.

required
Source code in src/codex_platform/redis_service/base.py
def __init__(self, client: Redis) -> None:
    """Initialize the service with an existing async Redis client.

    Args:
        client: An already-constructed ``redis.asyncio.Redis`` instance.
    """
    self.redis_client = client

BaseRedisKey

Bases: ABC

Abstract base for all Redis key definitions.

Subclass and define template with {placeholder} syntax. Call .build(**kwargs) to construct the final key string.

Source code in src/codex_platform/redis_service/keys.py
class BaseRedisKey(ABC):
    """
    Abstract base for all Redis key definitions.

    Subclass and define `template` with ``{placeholder}`` syntax.
    Call ``.build(**kwargs)`` to construct the final key string.
    """

    @property
    @abstractmethod
    def template(self) -> str:
        """Key template string with ``{placeholder}`` syntax."""

    def build(self, **kwargs: Any) -> str:
        """Build the final key string by formatting the template with keyword arguments.

        Args:
            **kwargs: Values for each placeholder defined in ``template``.

        Returns:
            Fully resolved Redis key string.

        Raises:
            ValueError: If a required placeholder argument is missing.
        """
        try:
            return self.template.format(**kwargs)
        except KeyError as e:
            raise ValueError(f"Missing key argument: {e} for template '{self.template}'") from e

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}(template={self.template!r})"
Attributes
template abstractmethod property

Key template string with {placeholder} syntax.

Functions
build(**kwargs)

Build the final key string by formatting the template with keyword arguments.

Parameters:

Name Type Description Default
**kwargs Any

Values for each placeholder defined in template.

{}

Returns:

Type Description
str

Fully resolved Redis key string.

Raises:

Type Description
ValueError

If a required placeholder argument is missing.

Source code in src/codex_platform/redis_service/keys.py
def build(self, **kwargs: Any) -> str:
    """Build the final key string by formatting the template with keyword arguments.

    Args:
        **kwargs: Values for each placeholder defined in ``template``.

    Returns:
        Fully resolved Redis key string.

    Raises:
        ValueError: If a required placeholder argument is missing.
    """
    try:
        return self.template.format(**kwargs)
    except KeyError as e:
        raise ValueError(f"Missing key argument: {e} for template '{self.template}'") from e

SessionKey

Bases: BaseRedisKey

Session data. Args: token.

Source code in src/codex_platform/redis_service/keys.py
class SessionKey(BaseRedisKey):
    """Session data. Args: token."""

    template = "sess:{token}"

UserKey

Bases: BaseRedisKey

User data hash. Args: user_id.

Source code in src/codex_platform/redis_service/keys.py
class UserKey(BaseRedisKey):
    """User data hash. Args: user_id."""

    template = "u:{user_id}"

BaseRedisManager

Base manager that initialises common Redis operation helpers.

Subclass and add only the operation attributes your manager actually needs.

Example::

class SiteSettingsManager(BaseRedisManager):
    async def get_settings(self) -> dict:
        return await self.hash.get_all("site:settings") or {}
Source code in src/codex_platform/redis_service/managers/base_manager.py
class BaseRedisManager:
    """Base manager that initialises common Redis operation helpers.

    Subclass and add only the operation attributes your manager actually needs.

    Example::

        class SiteSettingsManager(BaseRedisManager):
            async def get_settings(self) -> dict:
                return await self.hash.get_all("site:settings") or {}
    """

    def __init__(self, redis_client: Redis) -> None:
        """Initialize the manager with an existing async Redis client.

        Args:
            redis_client: An already-constructed ``redis.asyncio.Redis`` instance.
        """
        self.hash = HashOperations(redis_client)
        self.string = StringOperations(redis_client)
Functions
__init__(redis_client)

Initialize the manager with an existing async Redis client.

Parameters:

Name Type Description Default
redis_client Redis

An already-constructed redis.asyncio.Redis instance.

required
Source code in src/codex_platform/redis_service/managers/base_manager.py
def __init__(self, redis_client: Redis) -> None:
    """Initialize the manager with an existing async Redis client.

    Args:
        redis_client: An already-constructed ``redis.asyncio.Redis`` instance.
    """
    self.hash = HashOperations(redis_client)
    self.string = StringOperations(redis_client)

SiteSettingsManager

Bases: BaseRedisManager

Async interface to the shared site_settings Redis hash.

Provides a fixed CACHE_KEY so that all services in the Codex ecosystem read and write the same Redis key without coupling to Django models.

Example::

manager = SiteSettingsManager(redis_client)
await manager.aset_fields({"maintenance": "false", "version": "1.2"})
value = await manager.aget_field("maintenance")
all_settings = await manager.aget_all()
Source code in src/codex_platform/redis_service/managers/site_settings.py
class SiteSettingsManager(BaseRedisManager):
    """Async interface to the shared ``site_settings`` Redis hash.

    Provides a fixed CACHE_KEY so that all services in the Codex ecosystem
    read and write the same Redis key without coupling to Django models.

    Example::

        manager = SiteSettingsManager(redis_client)
        await manager.aset_fields({"maintenance": "false", "version": "1.2"})
        value = await manager.aget_field("maintenance")
        all_settings = await manager.aget_all()
    """

    CACHE_KEY = "site_settings"

    async def aget_all(self) -> dict[str, str]:
        """Return all settings as a flat dict (HGETALL).

        Returns:
            Dict of ``{field: value}``. Empty dict if no settings are cached.
        """
        result = await self.hash.get_all(self.CACHE_KEY)
        return result or {}

    async def aget_field(self, field: str) -> str | None:
        """Return a single setting value (HGET).

        Args:
            field: Setting name.

        Returns:
            String value, or ``None`` if the field does not exist.
        """
        return cast("str | None", await self.hash.get_field(self.CACHE_KEY, field))

    async def aset_field(self, field: str, value: str) -> None:
        """Write a single setting atomically (HSET).

        Args:
            field: Setting name.
            value: String value to store.
        """
        await self.hash.set_field(self.CACHE_KEY, field, value)

    async def aset_fields(self, data: dict[str, str]) -> None:
        """Write multiple settings in a single call (HSET mapping).

        Args:
            data: Mapping of ``{field: value}`` pairs.
        """
        await self.hash.set_fields(self.CACHE_KEY, data)

    async def aexists(self) -> bool:
        """Check whether any settings are present in the cache (HLEN > 0).

        Returns:
            ``True`` if the hash key exists and has at least one field.
        """
        return cast(int, await self.hash.length(self.CACHE_KEY)) > 0
Functions
aget_all() async

Return all settings as a flat dict (HGETALL).

Returns:

Type Description
dict[str, str]

Dict of {field: value}. Empty dict if no settings are cached.

Source code in src/codex_platform/redis_service/managers/site_settings.py
async def aget_all(self) -> dict[str, str]:
    """Return all settings as a flat dict (HGETALL).

    Returns:
        Dict of ``{field: value}``. Empty dict if no settings are cached.
    """
    result = await self.hash.get_all(self.CACHE_KEY)
    return result or {}
aget_field(field) async

Return a single setting value (HGET).

Parameters:

Name Type Description Default
field str

Setting name.

required

Returns:

Type Description
str | None

String value, or None if the field does not exist.

Source code in src/codex_platform/redis_service/managers/site_settings.py
async def aget_field(self, field: str) -> str | None:
    """Return a single setting value (HGET).

    Args:
        field: Setting name.

    Returns:
        String value, or ``None`` if the field does not exist.
    """
    return cast("str | None", await self.hash.get_field(self.CACHE_KEY, field))
aset_field(field, value) async

Write a single setting atomically (HSET).

Parameters:

Name Type Description Default
field str

Setting name.

required
value str

String value to store.

required
Source code in src/codex_platform/redis_service/managers/site_settings.py
async def aset_field(self, field: str, value: str) -> None:
    """Write a single setting atomically (HSET).

    Args:
        field: Setting name.
        value: String value to store.
    """
    await self.hash.set_field(self.CACHE_KEY, field, value)
aset_fields(data) async

Write multiple settings in a single call (HSET mapping).

Parameters:

Name Type Description Default
data dict[str, str]

Mapping of {field: value} pairs.

required
Source code in src/codex_platform/redis_service/managers/site_settings.py
async def aset_fields(self, data: dict[str, str]) -> None:
    """Write multiple settings in a single call (HSET mapping).

    Args:
        data: Mapping of ``{field: value}`` pairs.
    """
    await self.hash.set_fields(self.CACHE_KEY, data)
aexists() async

Check whether any settings are present in the cache (HLEN > 0).

Returns:

Type Description
bool

True if the hash key exists and has at least one field.

Source code in src/codex_platform/redis_service/managers/site_settings.py
async def aexists(self) -> bool:
    """Check whether any settings are present in the cache (HLEN > 0).

    Returns:
        ``True`` if the hash key exists and has at least one field.
    """
    return cast(int, await self.hash.length(self.CACHE_KEY)) > 0

HashOperations

Redis Hash operations (HSET / HGET / HGETALL / HDEL and more).

Accepts an already-constructed redis.asyncio.Redis client. All methods wrap Redis errors in typed exceptions.

Example::

ops = HashOperations(client)
await ops.set_json("user:42", "profile", {"name": "Alice"})
profile = await ops.get_json("user:42", "profile")
Source code in src/codex_platform/redis_service/operations/hash.py
class HashOperations:
    """Redis Hash operations (HSET / HGET / HGETALL / HDEL and more).

    Accepts an already-constructed ``redis.asyncio.Redis`` client.
    All methods wrap Redis errors in typed exceptions.

    Example::

        ops = HashOperations(client)
        await ops.set_json("user:42", "profile", {"name": "Alice"})
        profile = await ops.get_json("user:42", "profile")
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    @catch_redis_errors
    async def set_json(self, key: "str | BaseRedisKey", field: str, data: dict[str, Any], **kwargs: Any) -> None:
        """Serialize a dict to JSON and store it in a hash field (HSET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            field: Hash field name.
            data: Dictionary to serialize as JSON.
            **kwargs: Extra parameters forwarded to ``resolve_key`` (e.g. ``user_id=42``).

        Raises:
            RedisDataError: If ``data`` cannot be serialized to JSON.
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        try:
            data_json = json.dumps(data)
        except TypeError as e:
            raise RedisDataError(f"JSON serialization error for key='{real_key}': {e}") from e
        await self.client.hset(real_key, field, data_json)

    @catch_redis_errors
    async def get_json(self, key: "str | BaseRedisKey", field: str, **kwargs: Any) -> dict[str, Any] | None:
        """Retrieve a hash field and deserialize it from JSON (HGET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            field: Hash field name.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Deserialized dictionary, or ``None`` if the field does not exist.

        Raises:
            RedisDataError: If the field value is not valid JSON.
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        raw = await self.client.hget(real_key, field)
        if raw is None:
            return None
        try:
            return json.loads(raw)
        except json.JSONDecodeError as e:
            raise RedisDataError(f"Invalid JSON in key='{real_key}' field='{field}': {e}") from e

    @catch_redis_errors
    async def set_field(self, key: "str | BaseRedisKey", field: str, value: str, **kwargs: Any) -> None:
        """Set a single string field in a hash (HSET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            field: Hash field name.
            value: String value to store.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        await self.client.hset(real_key, field, value)

    @catch_redis_errors
    async def set_fields(
        self,
        key: "str | BaseRedisKey",
        data: dict[str, Any],
        *,
        encoder: Callable[[Any], Any] | None = None,
        **kwargs: Any,
    ) -> None:
        """Set multiple hash fields in a single call (HSET mapping).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            data: Mapping of ``{field: value}`` pairs to write.
            encoder: Optional callable to transform values before setting.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        if encoder:
            data = {k: encoder(v) for k, v in data.items()}
        await self.client.hset(real_key, mapping=data)

    @catch_redis_errors
    async def get_field(self, key: "str | BaseRedisKey", field: str, **kwargs: Any) -> str | None:
        """Retrieve a single hash field as a string (HGET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            field: Hash field name.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            String value of the field, or ``None`` if it does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        value = await self.client.hget(real_key, field)
        return str(value) if value is not None else None

    @catch_redis_errors
    async def get_fields(self, key: "str | BaseRedisKey", *fields: str, **kwargs: Any) -> list[str | None]:
        """Retrieve multiple hash fields in a single request (HMGET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            *fields: Field names to retrieve.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List of values in the same order as ``fields``.
            ``None`` for fields that do not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        values = await self.client.hmget(real_key, list(fields))
        return [str(v) if v is not None else None for v in values]

    @catch_redis_errors
    async def get_all(self, key: "str | BaseRedisKey", **kwargs: Any) -> dict[str, str] | None:
        """Retrieve all fields and values from a hash (HGETALL).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Dict of ``{field: value}``, or ``None`` if the hash does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        data = await self.client.hgetall(real_key)
        return data if data else None

    @catch_redis_errors
    async def delete_field(self, key: "str | BaseRedisKey", *fields: str, **kwargs: Any) -> int:
        """Delete one or more fields from a hash (HDEL).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            *fields: Field names to delete.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of fields actually deleted.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.hdel(real_key, *fields))

    @catch_redis_errors
    async def delete(self, key: "str | BaseRedisKey", **kwargs: Any) -> None:
        """Delete the entire hash key (DEL).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        await self.client.delete(real_key)

    @catch_redis_errors
    async def exists_field(self, key: "str | BaseRedisKey", field: str, **kwargs: Any) -> bool:
        """Check whether a field exists in a hash (HEXISTS).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            field: Hash field name to check.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            ``True`` if the field exists, ``False`` otherwise.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return bool(await self.client.hexists(real_key, field))

    @catch_redis_errors
    async def keys(self, key: "str | BaseRedisKey", **kwargs: Any) -> list[str]:
        """Return all field names of a hash (HKEYS).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List of field names. Empty list if the hash does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return await self.client.hkeys(real_key)

    @catch_redis_errors
    async def values(self, key: "str | BaseRedisKey", **kwargs: Any) -> list[str]:
        """Return all field values of a hash (HVALS).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List of field values. Empty list if the hash does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return await self.client.hvals(real_key)

    @catch_redis_errors
    async def length(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
        """Return the number of fields in a hash (HLEN).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of fields. ``0`` if the hash does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.hlen(real_key))

    @catch_redis_errors
    async def increment(self, key: "str | BaseRedisKey", field: str, amount: int = 1, **kwargs: Any) -> int:
        """Increment a numeric hash field by the given amount (HINCRBY).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            field: Numeric field name.
            amount: Increment step. Defaults to ``1``.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            New value of the field after incrementing.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.hincrby(real_key, field, amount))
Functions
set_json(key, field, data, **kwargs) async

Serialize a dict to JSON and store it in a hash field (HSET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
field str

Hash field name.

required
data dict[str, Any]

Dictionary to serialize as JSON.

required
**kwargs Any

Extra parameters forwarded to resolve_key (e.g. user_id=42).

{}

Raises:

Type Description
RedisDataError

If data cannot be serialized to JSON.

RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def set_json(self, key: "str | BaseRedisKey", field: str, data: dict[str, Any], **kwargs: Any) -> None:
    """Serialize a dict to JSON and store it in a hash field (HSET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        field: Hash field name.
        data: Dictionary to serialize as JSON.
        **kwargs: Extra parameters forwarded to ``resolve_key`` (e.g. ``user_id=42``).

    Raises:
        RedisDataError: If ``data`` cannot be serialized to JSON.
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    try:
        data_json = json.dumps(data)
    except TypeError as e:
        raise RedisDataError(f"JSON serialization error for key='{real_key}': {e}") from e
    await self.client.hset(real_key, field, data_json)
get_json(key, field, **kwargs) async

Retrieve a hash field and deserialize it from JSON (HGET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
field str

Hash field name.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
dict[str, Any] | None

Deserialized dictionary, or None if the field does not exist.

Raises:

Type Description
RedisDataError

If the field value is not valid JSON.

RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def get_json(self, key: "str | BaseRedisKey", field: str, **kwargs: Any) -> dict[str, Any] | None:
    """Retrieve a hash field and deserialize it from JSON (HGET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        field: Hash field name.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Deserialized dictionary, or ``None`` if the field does not exist.

    Raises:
        RedisDataError: If the field value is not valid JSON.
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    raw = await self.client.hget(real_key, field)
    if raw is None:
        return None
    try:
        return json.loads(raw)
    except json.JSONDecodeError as e:
        raise RedisDataError(f"Invalid JSON in key='{real_key}' field='{field}': {e}") from e
set_field(key, field, value, **kwargs) async

Set a single string field in a hash (HSET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
field str

Hash field name.

required
value str

String value to store.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def set_field(self, key: "str | BaseRedisKey", field: str, value: str, **kwargs: Any) -> None:
    """Set a single string field in a hash (HSET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        field: Hash field name.
        value: String value to store.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    await self.client.hset(real_key, field, value)
set_fields(key, data, *, encoder=None, **kwargs) async

Set multiple hash fields in a single call (HSET mapping).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
data dict[str, Any]

Mapping of {field: value} pairs to write.

required
encoder Callable[[Any], Any] | None

Optional callable to transform values before setting.

None
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def set_fields(
    self,
    key: "str | BaseRedisKey",
    data: dict[str, Any],
    *,
    encoder: Callable[[Any], Any] | None = None,
    **kwargs: Any,
) -> None:
    """Set multiple hash fields in a single call (HSET mapping).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        data: Mapping of ``{field: value}`` pairs to write.
        encoder: Optional callable to transform values before setting.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    if encoder:
        data = {k: encoder(v) for k, v in data.items()}
    await self.client.hset(real_key, mapping=data)
get_field(key, field, **kwargs) async

Retrieve a single hash field as a string (HGET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
field str

Hash field name.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
str | None

String value of the field, or None if it does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def get_field(self, key: "str | BaseRedisKey", field: str, **kwargs: Any) -> str | None:
    """Retrieve a single hash field as a string (HGET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        field: Hash field name.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        String value of the field, or ``None`` if it does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    value = await self.client.hget(real_key, field)
    return str(value) if value is not None else None
get_fields(key, *fields, **kwargs) async

Retrieve multiple hash fields in a single request (HMGET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
*fields str

Field names to retrieve.

()
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
list[str | None]

List of values in the same order as fields.

list[str | None]

None for fields that do not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def get_fields(self, key: "str | BaseRedisKey", *fields: str, **kwargs: Any) -> list[str | None]:
    """Retrieve multiple hash fields in a single request (HMGET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        *fields: Field names to retrieve.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List of values in the same order as ``fields``.
        ``None`` for fields that do not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    values = await self.client.hmget(real_key, list(fields))
    return [str(v) if v is not None else None for v in values]
get_all(key, **kwargs) async

Retrieve all fields and values from a hash (HGETALL).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
dict[str, str] | None

Dict of {field: value}, or None if the hash does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def get_all(self, key: "str | BaseRedisKey", **kwargs: Any) -> dict[str, str] | None:
    """Retrieve all fields and values from a hash (HGETALL).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Dict of ``{field: value}``, or ``None`` if the hash does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    data = await self.client.hgetall(real_key)
    return data if data else None
delete_field(key, *fields, **kwargs) async

Delete one or more fields from a hash (HDEL).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
*fields str

Field names to delete.

()
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of fields actually deleted.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def delete_field(self, key: "str | BaseRedisKey", *fields: str, **kwargs: Any) -> int:
    """Delete one or more fields from a hash (HDEL).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        *fields: Field names to delete.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of fields actually deleted.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.hdel(real_key, *fields))
delete(key, **kwargs) async

Delete the entire hash key (DEL).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def delete(self, key: "str | BaseRedisKey", **kwargs: Any) -> None:
    """Delete the entire hash key (DEL).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    await self.client.delete(real_key)
exists_field(key, field, **kwargs) async

Check whether a field exists in a hash (HEXISTS).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
field str

Hash field name to check.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
bool

True if the field exists, False otherwise.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def exists_field(self, key: "str | BaseRedisKey", field: str, **kwargs: Any) -> bool:
    """Check whether a field exists in a hash (HEXISTS).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        field: Hash field name to check.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        ``True`` if the field exists, ``False`` otherwise.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return bool(await self.client.hexists(real_key, field))
keys(key, **kwargs) async

Return all field names of a hash (HKEYS).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
list[str]

List of field names. Empty list if the hash does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def keys(self, key: "str | BaseRedisKey", **kwargs: Any) -> list[str]:
    """Return all field names of a hash (HKEYS).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List of field names. Empty list if the hash does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return await self.client.hkeys(real_key)
values(key, **kwargs) async

Return all field values of a hash (HVALS).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
list[str]

List of field values. Empty list if the hash does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def values(self, key: "str | BaseRedisKey", **kwargs: Any) -> list[str]:
    """Return all field values of a hash (HVALS).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List of field values. Empty list if the hash does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return await self.client.hvals(real_key)
length(key, **kwargs) async

Return the number of fields in a hash (HLEN).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of fields. 0 if the hash does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def length(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
    """Return the number of fields in a hash (HLEN).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of fields. ``0`` if the hash does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.hlen(real_key))
increment(key, field, amount=1, **kwargs) async

Increment a numeric hash field by the given amount (HINCRBY).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
field str

Numeric field name.

required
amount int

Increment step. Defaults to 1.

1
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

New value of the field after incrementing.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/hash.py
@catch_redis_errors
async def increment(self, key: "str | BaseRedisKey", field: str, amount: int = 1, **kwargs: Any) -> int:
    """Increment a numeric hash field by the given amount (HINCRBY).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        field: Numeric field name.
        amount: Increment step. Defaults to ``1``.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        New value of the field after incrementing.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.hincrby(real_key, field, amount))

JsonModuleOperations

Redis JSON operations using the server-side RedisJSON module (JSON.* commands).

Requires the RedisJSON module on the server and redis-py with JSON support. Supports path-based access, atomic updates, array append, and more.

Example::

svc = JsonModuleOperations(client)
await svc.set("user:42", "$", {"name": "Alice", "age": 30})
name = await svc.get("user:42", "$.name")  # [["Alice"]]
Source code in src/codex_platform/redis_service/operations/json_module.py
class JsonModuleOperations:
    """Redis JSON operations using the server-side RedisJSON module (JSON.* commands).

    Requires the RedisJSON module on the server and redis-py with JSON support.
    Supports path-based access, atomic updates, array append, and more.

    Example::

        svc = JsonModuleOperations(client)
        await svc.set("user:42", "$", {"name": "Alice", "age": 30})
        name = await svc.get("user:42", "$.name")  # [["Alice"]]
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    def _require_json(self) -> None:
        if not _JSON_AVAILABLE:
            raise RuntimeError("RedisJSON module not available in redis-py. Install: pip install redis[hiredis]")

    @catch_redis_errors
    async def set(self, key: str, path: str, obj: Any, nx: bool = False, xx: bool = False) -> bool:
        """Set a JSON value at the given path (JSON.SET).

        Args:
            key: Redis key string.
            path: JSONPath expression, e.g. ``$`` or ``$.field``.
            obj: Any JSON-serializable object.
            nx: Set only if the key does not exist.
            xx: Set only if the key already exists.

        Returns:
            ``True`` if the value was successfully set.

        Raises:
            RuntimeError: If the RedisJSON module is not available.
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        self._require_json()
        result = await self.client.json().set(key, path, obj, nx=nx, xx=xx)  # type: ignore[no-untyped-call]
        log.debug("JsonModuleOps | set key='%s' path='%s'", key, path)
        return bool(result)

    @catch_redis_errors
    async def get(self, key: str, path: str = "$") -> Any:
        """Retrieve a JSON value at the given path (JSON.GET).

        Args:
            key: Redis key string.
            path: JSONPath expression. Defaults to ``$`` (the whole document).

        Returns:
            Parsed value, or ``None`` if the key does not exist.

        Raises:
            RuntimeError: If the RedisJSON module is not available.
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        self._require_json()
        return await self.client.json().get(key, path)  # type: ignore[no-untyped-call]

    @catch_redis_errors
    async def arrappend(self, key: str, path: str, *args: Any) -> int:
        """Append elements to a JSON array at the given path (JSON.ARRAPPEND).

        Args:
            key: Redis key string.
            path: JSONPath expression pointing to an array.
            *args: Values to append to the array.

        Returns:
            New length of the array after appending.

        Raises:
            RuntimeError: If the RedisJSON module is not available.
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        self._require_json()
        count = await self.client.json().arrappend(key, path, *args)  # type: ignore[no-untyped-call]
        return int(count) if count else 0

    @catch_redis_errors
    async def delete(self, key: str, path: str = "$") -> int:
        """Delete a JSON value at the given path (JSON.DEL).

        Args:
            key: Redis key string.
            path: JSONPath expression. Defaults to ``$`` (the whole document).

        Returns:
            Number of elements deleted.

        Raises:
            RuntimeError: If the RedisJSON module is not available.
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        self._require_json()
        result = await self.client.json().delete(key, path)  # type: ignore[no-untyped-call]
        return int(result) if result else 0
Functions
set(key, path, obj, nx=False, xx=False) async

Set a JSON value at the given path (JSON.SET).

Parameters:

Name Type Description Default
key str

Redis key string.

required
path str

JSONPath expression, e.g. $ or $.field.

required
obj Any

Any JSON-serializable object.

required
nx bool

Set only if the key does not exist.

False
xx bool

Set only if the key already exists.

False

Returns:

Type Description
bool

True if the value was successfully set.

Raises:

Type Description
RuntimeError

If the RedisJSON module is not available.

RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_module.py
@catch_redis_errors
async def set(self, key: str, path: str, obj: Any, nx: bool = False, xx: bool = False) -> bool:
    """Set a JSON value at the given path (JSON.SET).

    Args:
        key: Redis key string.
        path: JSONPath expression, e.g. ``$`` or ``$.field``.
        obj: Any JSON-serializable object.
        nx: Set only if the key does not exist.
        xx: Set only if the key already exists.

    Returns:
        ``True`` if the value was successfully set.

    Raises:
        RuntimeError: If the RedisJSON module is not available.
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    self._require_json()
    result = await self.client.json().set(key, path, obj, nx=nx, xx=xx)  # type: ignore[no-untyped-call]
    log.debug("JsonModuleOps | set key='%s' path='%s'", key, path)
    return bool(result)
get(key, path='$') async

Retrieve a JSON value at the given path (JSON.GET).

Parameters:

Name Type Description Default
key str

Redis key string.

required
path str

JSONPath expression. Defaults to $ (the whole document).

'$'

Returns:

Type Description
Any

Parsed value, or None if the key does not exist.

Raises:

Type Description
RuntimeError

If the RedisJSON module is not available.

RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_module.py
@catch_redis_errors
async def get(self, key: str, path: str = "$") -> Any:
    """Retrieve a JSON value at the given path (JSON.GET).

    Args:
        key: Redis key string.
        path: JSONPath expression. Defaults to ``$`` (the whole document).

    Returns:
        Parsed value, or ``None`` if the key does not exist.

    Raises:
        RuntimeError: If the RedisJSON module is not available.
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    self._require_json()
    return await self.client.json().get(key, path)  # type: ignore[no-untyped-call]
arrappend(key, path, *args) async

Append elements to a JSON array at the given path (JSON.ARRAPPEND).

Parameters:

Name Type Description Default
key str

Redis key string.

required
path str

JSONPath expression pointing to an array.

required
*args Any

Values to append to the array.

()

Returns:

Type Description
int

New length of the array after appending.

Raises:

Type Description
RuntimeError

If the RedisJSON module is not available.

RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_module.py
@catch_redis_errors
async def arrappend(self, key: str, path: str, *args: Any) -> int:
    """Append elements to a JSON array at the given path (JSON.ARRAPPEND).

    Args:
        key: Redis key string.
        path: JSONPath expression pointing to an array.
        *args: Values to append to the array.

    Returns:
        New length of the array after appending.

    Raises:
        RuntimeError: If the RedisJSON module is not available.
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    self._require_json()
    count = await self.client.json().arrappend(key, path, *args)  # type: ignore[no-untyped-call]
    return int(count) if count else 0
delete(key, path='$') async

Delete a JSON value at the given path (JSON.DEL).

Parameters:

Name Type Description Default
key str

Redis key string.

required
path str

JSONPath expression. Defaults to $ (the whole document).

'$'

Returns:

Type Description
int

Number of elements deleted.

Raises:

Type Description
RuntimeError

If the RedisJSON module is not available.

RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_module.py
@catch_redis_errors
async def delete(self, key: str, path: str = "$") -> int:
    """Delete a JSON value at the given path (JSON.DEL).

    Args:
        key: Redis key string.
        path: JSONPath expression. Defaults to ``$`` (the whole document).

    Returns:
        Number of elements deleted.

    Raises:
        RuntimeError: If the RedisJSON module is not available.
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    self._require_json()
    result = await self.client.json().delete(key, path)  # type: ignore[no-untyped-call]
    return int(result) if result else 0

JsonStringOperations

Store JSON objects as Redis strings using SET/GET with json.dumps/loads.

Works with any standard Redis instance — no server modules required. Does not support path-based access; for that use :class:~codex_platform.redis_service.operations.json_module.JsonModuleOperations.

Example::

svc = JsonStringOperations(client)
await svc.set("user:42", {"name": "Alice", "age": 30}, ttl=3600)
user = await svc.get("user:42")  # {"name": "Alice", "age": 30}
Source code in src/codex_platform/redis_service/operations/json_string.py
class JsonStringOperations:
    """Store JSON objects as Redis strings using SET/GET with json.dumps/loads.

    Works with any standard Redis instance — no server modules required.
    Does not support path-based access; for that use
    :class:`~codex_platform.redis_service.operations.json_module.JsonModuleOperations`.

    Example::

        svc = JsonStringOperations(client)
        await svc.set("user:42", {"name": "Alice", "age": 30}, ttl=3600)
        user = await svc.get("user:42")  # {"name": "Alice", "age": 30}
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    @catch_redis_errors
    async def set(self, key: str, obj: Any, ttl: int | None = None) -> None:
        """Serialize an object to JSON and store it in Redis (SET).

        Args:
            key: Redis key string.
            obj: Any JSON-serializable object (dict, list, str, int, …).
            ttl: Expiry in seconds. ``None`` means no expiry.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        value = json.dumps(obj, ensure_ascii=False)
        await self.client.set(key, value, ex=ttl)
        log.debug("JsonStringOps | set key='%s' ttl=%s", key, ttl)

    @catch_redis_errors
    async def get(self, key: str) -> Any:
        """Read a Redis string and deserialize it from JSON (GET).

        Args:
            key: Redis key string.

        Returns:
            Deserialized object, or ``None`` if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        raw = await self.client.get(key)
        if raw is None:
            return None
        return json.loads(raw)

    @catch_redis_errors
    async def set_nx(self, key: str, obj: Any, ttl: int | None = None) -> bool:
        """Set a JSON value only if the key does not exist (SET NX).

        Args:
            key: Redis key string.
            obj: Any JSON-serializable object.
            ttl: Expiry in seconds. ``None`` means no expiry.

        Returns:
            ``True`` if the value was set, ``False`` if the key already existed.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        value = json.dumps(obj, ensure_ascii=False)
        result = await self.client.set(key, value, ex=ttl, nx=True)
        log.debug("JsonStringOps | set_nx key='%s' result=%s", key, bool(result))
        return bool(result)

    @catch_redis_errors
    async def mget(self, *keys: str) -> list[Any]:
        """Retrieve multiple JSON values in a single request (MGET).

        Args:
            *keys: Redis key strings.

        Returns:
            List of deserialized objects in the same order as ``keys``.
            ``None`` for keys that do not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        if not keys:
            return []
        raws = await self.client.mget(*keys)
        return [json.loads(r) if r is not None else None for r in raws]
Functions
set(key, obj, ttl=None) async

Serialize an object to JSON and store it in Redis (SET).

Parameters:

Name Type Description Default
key str

Redis key string.

required
obj Any

Any JSON-serializable object (dict, list, str, int, …).

required
ttl int | None

Expiry in seconds. None means no expiry.

None

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_string.py
@catch_redis_errors
async def set(self, key: str, obj: Any, ttl: int | None = None) -> None:
    """Serialize an object to JSON and store it in Redis (SET).

    Args:
        key: Redis key string.
        obj: Any JSON-serializable object (dict, list, str, int, …).
        ttl: Expiry in seconds. ``None`` means no expiry.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    value = json.dumps(obj, ensure_ascii=False)
    await self.client.set(key, value, ex=ttl)
    log.debug("JsonStringOps | set key='%s' ttl=%s", key, ttl)
get(key) async

Read a Redis string and deserialize it from JSON (GET).

Parameters:

Name Type Description Default
key str

Redis key string.

required

Returns:

Type Description
Any

Deserialized object, or None if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_string.py
@catch_redis_errors
async def get(self, key: str) -> Any:
    """Read a Redis string and deserialize it from JSON (GET).

    Args:
        key: Redis key string.

    Returns:
        Deserialized object, or ``None`` if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    raw = await self.client.get(key)
    if raw is None:
        return None
    return json.loads(raw)
set_nx(key, obj, ttl=None) async

Set a JSON value only if the key does not exist (SET NX).

Parameters:

Name Type Description Default
key str

Redis key string.

required
obj Any

Any JSON-serializable object.

required
ttl int | None

Expiry in seconds. None means no expiry.

None

Returns:

Type Description
bool

True if the value was set, False if the key already existed.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_string.py
@catch_redis_errors
async def set_nx(self, key: str, obj: Any, ttl: int | None = None) -> bool:
    """Set a JSON value only if the key does not exist (SET NX).

    Args:
        key: Redis key string.
        obj: Any JSON-serializable object.
        ttl: Expiry in seconds. ``None`` means no expiry.

    Returns:
        ``True`` if the value was set, ``False`` if the key already existed.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    value = json.dumps(obj, ensure_ascii=False)
    result = await self.client.set(key, value, ex=ttl, nx=True)
    log.debug("JsonStringOps | set_nx key='%s' result=%s", key, bool(result))
    return bool(result)
mget(*keys) async

Retrieve multiple JSON values in a single request (MGET).

Parameters:

Name Type Description Default
*keys str

Redis key strings.

()

Returns:

Type Description
list[Any]

List of deserialized objects in the same order as keys.

list[Any]

None for keys that do not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/json_string.py
@catch_redis_errors
async def mget(self, *keys: str) -> list[Any]:
    """Retrieve multiple JSON values in a single request (MGET).

    Args:
        *keys: Redis key strings.

    Returns:
        List of deserialized objects in the same order as ``keys``.
        ``None`` for keys that do not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    if not keys:
        return []
    raws = await self.client.mget(*keys)
    return [json.loads(r) if r is not None else None for r in raws]

ListOperations

Redis List operations (RPUSH / LPUSH / LPOP / LRANGE and more).

Accepts an already-constructed redis.asyncio.Redis client. All methods wrap Redis errors in typed exceptions.

Example::

ops = ListOperations(client)
await ops.push("queue:jobs", "job-1", "job-2")
job = await ops.pop("queue:jobs")
Source code in src/codex_platform/redis_service/operations/list_.py
class ListOperations:
    """Redis List operations (RPUSH / LPUSH / LPOP / LRANGE and more).

    Accepts an already-constructed ``redis.asyncio.Redis`` client.
    All methods wrap Redis errors in typed exceptions.

    Example::

        ops = ListOperations(client)
        await ops.push("queue:jobs", "job-1", "job-2")
        job = await ops.pop("queue:jobs")
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    @catch_redis_errors
    async def push(self, key: "str | BaseRedisKey", *values: str, **kwargs: Any) -> int:
        """Append one or more values to the end of a list (RPUSH).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            *values: String values to append.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            New length of the list after the operation.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.rpush(real_key, *values))

    @catch_redis_errors
    async def lpush(self, key: "str | BaseRedisKey", *values: str, **kwargs: Any) -> int:
        """Prepend one or more values to the beginning of a list (LPUSH).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            *values: String values to prepend.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            New length of the list after the operation.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.lpush(real_key, *values))

    @catch_redis_errors
    async def pop(self, key: "str | BaseRedisKey", **kwargs: Any) -> str | None:
        """Remove and return the first element of a list (LPOP).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            The first element, or ``None`` if the list is empty or does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        value = await self.client.lpop(real_key)
        return str(value) if value is not None else None

    @catch_redis_errors
    async def rpop(self, key: "str | BaseRedisKey", **kwargs: Any) -> str | None:
        """Remove and return the last element of a list (RPOP).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            The last element, or ``None`` if the list is empty or does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        value = await self.client.rpop(real_key)
        return str(value) if value is not None else None

    @catch_redis_errors
    async def brpop(self, *keys: str, timeout: int = 0) -> tuple[str, str] | None:
        """Blocking pop of the last element from the first non-empty list (BRPOP).

        Args:
            *keys: One or more Redis key strings to check in order.
            timeout: Maximum seconds to block. ``0`` blocks indefinitely.

        Returns:
            ``(key, value)`` tuple when an element is available,
            or ``None`` if the timeout expires.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        result = await self.client.brpop(list(keys), timeout=timeout)
        if result:
            return str(result[0]), str(result[1])
        return None

    @catch_redis_errors
    async def range(self, key: "str | BaseRedisKey", start: int = 0, end: int = -1, **kwargs: Any) -> list[str]:
        """Return a slice of list elements by index range (LRANGE).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            start: Start index (0-based). Negative values count from the end.
            end: End index inclusive. ``-1`` means the last element.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List of elements in the requested range.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return await self.client.lrange(real_key, start, end)

    @catch_redis_errors
    async def length(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
        """Return the number of elements in a list (LLEN).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List length. ``0`` if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.llen(real_key))

    @catch_redis_errors
    async def set_index(self, key: "str | BaseRedisKey", index: int, value: str, **kwargs: Any) -> None:
        """Set the element at a specific list index (LSET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            index: Zero-based index. Negative values count from the end.
            value: New value to set at the given index.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        await self.client.lset(real_key, index, value)

    @catch_redis_errors
    async def trim(self, key: "str | BaseRedisKey", start: int, end: int, **kwargs: Any) -> None:
        """Trim a list to the specified index range, discarding all other elements (LTRIM).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            start: Start index (inclusive).
            end: End index (inclusive).
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        await self.client.ltrim(real_key, start, end)

    @catch_redis_errors
    async def move(self, src: str, dst: str) -> str | None:
        """Atomically move the last element of ``src`` to the head of ``dst`` (RPOPLPUSH).

        Args:
            src: Source list key.
            dst: Destination list key.

        Returns:
            The moved element, or ``None`` if ``src`` is empty.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        value = await self.client.rpoplpush(src, dst)
        return str(value) if value is not None else None
Functions
push(key, *values, **kwargs) async

Append one or more values to the end of a list (RPUSH).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
*values str

String values to append.

()
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

New length of the list after the operation.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def push(self, key: "str | BaseRedisKey", *values: str, **kwargs: Any) -> int:
    """Append one or more values to the end of a list (RPUSH).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        *values: String values to append.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        New length of the list after the operation.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.rpush(real_key, *values))
lpush(key, *values, **kwargs) async

Prepend one or more values to the beginning of a list (LPUSH).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
*values str

String values to prepend.

()
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

New length of the list after the operation.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def lpush(self, key: "str | BaseRedisKey", *values: str, **kwargs: Any) -> int:
    """Prepend one or more values to the beginning of a list (LPUSH).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        *values: String values to prepend.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        New length of the list after the operation.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.lpush(real_key, *values))
pop(key, **kwargs) async

Remove and return the first element of a list (LPOP).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
str | None

The first element, or None if the list is empty or does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def pop(self, key: "str | BaseRedisKey", **kwargs: Any) -> str | None:
    """Remove and return the first element of a list (LPOP).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        The first element, or ``None`` if the list is empty or does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    value = await self.client.lpop(real_key)
    return str(value) if value is not None else None
rpop(key, **kwargs) async

Remove and return the last element of a list (RPOP).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
str | None

The last element, or None if the list is empty or does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def rpop(self, key: "str | BaseRedisKey", **kwargs: Any) -> str | None:
    """Remove and return the last element of a list (RPOP).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        The last element, or ``None`` if the list is empty or does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    value = await self.client.rpop(real_key)
    return str(value) if value is not None else None
brpop(*keys, timeout=0) async

Blocking pop of the last element from the first non-empty list (BRPOP).

Parameters:

Name Type Description Default
*keys str

One or more Redis key strings to check in order.

()
timeout int

Maximum seconds to block. 0 blocks indefinitely.

0

Returns:

Type Description
tuple[str, str] | None

(key, value) tuple when an element is available,

tuple[str, str] | None

or None if the timeout expires.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def brpop(self, *keys: str, timeout: int = 0) -> tuple[str, str] | None:
    """Blocking pop of the last element from the first non-empty list (BRPOP).

    Args:
        *keys: One or more Redis key strings to check in order.
        timeout: Maximum seconds to block. ``0`` blocks indefinitely.

    Returns:
        ``(key, value)`` tuple when an element is available,
        or ``None`` if the timeout expires.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    result = await self.client.brpop(list(keys), timeout=timeout)
    if result:
        return str(result[0]), str(result[1])
    return None
range(key, start=0, end=-1, **kwargs) async

Return a slice of list elements by index range (LRANGE).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
start int

Start index (0-based). Negative values count from the end.

0
end int

End index inclusive. -1 means the last element.

-1
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
list[str]

List of elements in the requested range.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def range(self, key: "str | BaseRedisKey", start: int = 0, end: int = -1, **kwargs: Any) -> list[str]:
    """Return a slice of list elements by index range (LRANGE).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        start: Start index (0-based). Negative values count from the end.
        end: End index inclusive. ``-1`` means the last element.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List of elements in the requested range.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return await self.client.lrange(real_key, start, end)
length(key, **kwargs) async

Return the number of elements in a list (LLEN).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

List length. 0 if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def length(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
    """Return the number of elements in a list (LLEN).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List length. ``0`` if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.llen(real_key))
set_index(key, index, value, **kwargs) async

Set the element at a specific list index (LSET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
index int

Zero-based index. Negative values count from the end.

required
value str

New value to set at the given index.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def set_index(self, key: "str | BaseRedisKey", index: int, value: str, **kwargs: Any) -> None:
    """Set the element at a specific list index (LSET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        index: Zero-based index. Negative values count from the end.
        value: New value to set at the given index.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    await self.client.lset(real_key, index, value)
trim(key, start, end, **kwargs) async

Trim a list to the specified index range, discarding all other elements (LTRIM).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
start int

Start index (inclusive).

required
end int

End index (inclusive).

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def trim(self, key: "str | BaseRedisKey", start: int, end: int, **kwargs: Any) -> None:
    """Trim a list to the specified index range, discarding all other elements (LTRIM).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        start: Start index (inclusive).
        end: End index (inclusive).
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    await self.client.ltrim(real_key, start, end)
move(src, dst) async

Atomically move the last element of src to the head of dst (RPOPLPUSH).

Parameters:

Name Type Description Default
src str

Source list key.

required
dst str

Destination list key.

required

Returns:

Type Description
str | None

The moved element, or None if src is empty.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/list_.py
@catch_redis_errors
async def move(self, src: str, dst: str) -> str | None:
    """Atomically move the last element of ``src`` to the head of ``dst`` (RPOPLPUSH).

    Args:
        src: Source list key.
        dst: Destination list key.

    Returns:
        The moved element, or ``None`` if ``src`` is empty.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    value = await self.client.rpoplpush(src, dst)
    return str(value) if value is not None else None

PipelineOperations

Redis pipeline and atomic transaction operations.

Provides three execution modes:

  • Batching (execute) — commands are sent in one round-trip, not atomic.
  • Transaction (transact) — commands are wrapped in MULTI/EXEC, atomic.
  • Context manager (atomic) — atomic block with automatic EXEC on exit.

Also exposes Lua script execution via eval_script.

Source code in src/codex_platform/redis_service/operations/pipeline.py
class PipelineOperations:
    """Redis pipeline and atomic transaction operations.

    Provides three execution modes:

    - **Batching** (``execute``) — commands are sent in one round-trip, not atomic.
    - **Transaction** (``transact``) — commands are wrapped in MULTI/EXEC, atomic.
    - **Context manager** (``atomic``) — atomic block with automatic EXEC on exit.

    Also exposes Lua script execution via ``eval_script``.
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    @catch_redis_errors
    async def execute(self, builder_func: Callable[[Pipeline], Awaitable[None]]) -> list[Any]:
        """Execute a sequence of commands in a pipeline without MULTI/EXEC (batching).

        Commands are sent in a single round-trip but are **not** atomic.
        Use ``transact`` or ``atomic`` when atomicity is required.

        Args:
            builder_func: Async function that receives a ``Pipeline`` and queues commands.

        Returns:
            List of results for each queued command, in order.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.

        Example::

            async def build(pipe):
                await pipe.set("k1", "v1")
                await pipe.set("k2", "v2")

            results = await ops.execute(build)
        """
        async with self.client.pipeline(transaction=False) as pipe:
            await builder_func(pipe)
            results = await pipe.execute()
        log.debug("PipelineOps | execute commands=%d", len(results))
        return results

    @catch_redis_errors
    async def transact(self, builder_func: Callable[[Pipeline], Awaitable[None]]) -> list[Any]:
        """Execute commands in an atomic transaction (MULTI/EXEC).

        All commands inside ``builder_func`` are executed atomically.
        If the server crashes before EXEC, none of the commands are applied.

        Args:
            builder_func: Async function that receives a ``Pipeline`` and queues commands.

        Returns:
            List of results for each queued command, in order.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.

        Example::

            async def transfer(pipe):
                await pipe.decrby("wallet:from", 100)
                await pipe.incrby("wallet:to", 100)

            results = await ops.transact(transfer)
        """
        async with self.client.pipeline(transaction=True) as pipe:
            await builder_func(pipe)
            results = await pipe.execute()
        log.debug("PipelineOps | transact commands=%d", len(results))
        return results

    @asynccontextmanager
    async def atomic(self) -> AsyncIterator[Pipeline]:
        """Async context manager for an atomic block (MULTI/EXEC).

        Opens a Pipeline in transaction mode. EXEC is called automatically on exit.

        Yields:
            ``Pipeline`` instance in MULTI/EXEC mode.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.

        Example::

            async with service.pipeline.atomic() as pipe:
                await pipe.set("session:abc", "token")
                await pipe.expire("session:abc", 3600)
            # EXEC is called automatically on context exit
        """
        from redis.exceptions import ConnectionError, RedisError, TimeoutError

        pipe: Pipeline = self.client.pipeline(transaction=True)
        try:
            async with pipe as p:
                yield p
                await p.execute()
                log.debug("PipelineOps | atomic block committed")
        except (ConnectionError, TimeoutError) as e:
            raise RedisConnectionError(f"Atomic block connection failed: {e}") from e
        except RedisError as e:
            raise RedisServiceError(f"Atomic block error: {e}") from e

    @catch_redis_errors
    async def eval_script(
        self,
        script: str,
        keys: list[str] | None = None,
        args: list[Any] | None = None,
    ) -> Any:
        """Execute a Lua script (EVAL). Lua scripts are always atomic in Redis.

        Use for complex read-modify-write operations that must not be interrupted.

        Args:
            script: Lua script source code.
            keys: List of Redis keys accessible as ``KEYS[1]``, ``KEYS[2]``, etc.
            args: Script arguments accessible as ``ARGV[1]``, ``ARGV[2]``, etc.

        Returns:
            Value returned by the Lua script.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.

        Example::

            result = await ops.eval_script(
                \"\"\"
                local val = redis.call('GET', KEYS[1])
                if val == ARGV[1] then
                    redis.call('SET', KEYS[1], ARGV[2])
                    return 1
                end
                return 0
                \"\"\",
                keys=["mykey"],
                args=["expected", "new_value"],
            )
        """
        result = await self.client.eval(script, len(keys or []), *(keys or []), *(args or []))
        log.debug("PipelineOps | eval_script keys=%d args=%d", len(keys or []), len(args or []))
        return result
Functions
execute(builder_func) async

Execute a sequence of commands in a pipeline without MULTI/EXEC (batching).

Commands are sent in a single round-trip but are not atomic. Use transact or atomic when atomicity is required.

Parameters:

Name Type Description Default
builder_func Callable[[Pipeline], Awaitable[None]]

Async function that receives a Pipeline and queues commands.

required

Returns:

Type Description
list[Any]

List of results for each queued command, in order.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Example::

async def build(pipe):
    await pipe.set("k1", "v1")
    await pipe.set("k2", "v2")

results = await ops.execute(build)
Source code in src/codex_platform/redis_service/operations/pipeline.py
@catch_redis_errors
async def execute(self, builder_func: Callable[[Pipeline], Awaitable[None]]) -> list[Any]:
    """Execute a sequence of commands in a pipeline without MULTI/EXEC (batching).

    Commands are sent in a single round-trip but are **not** atomic.
    Use ``transact`` or ``atomic`` when atomicity is required.

    Args:
        builder_func: Async function that receives a ``Pipeline`` and queues commands.

    Returns:
        List of results for each queued command, in order.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.

    Example::

        async def build(pipe):
            await pipe.set("k1", "v1")
            await pipe.set("k2", "v2")

        results = await ops.execute(build)
    """
    async with self.client.pipeline(transaction=False) as pipe:
        await builder_func(pipe)
        results = await pipe.execute()
    log.debug("PipelineOps | execute commands=%d", len(results))
    return results
transact(builder_func) async

Execute commands in an atomic transaction (MULTI/EXEC).

All commands inside builder_func are executed atomically. If the server crashes before EXEC, none of the commands are applied.

Parameters:

Name Type Description Default
builder_func Callable[[Pipeline], Awaitable[None]]

Async function that receives a Pipeline and queues commands.

required

Returns:

Type Description
list[Any]

List of results for each queued command, in order.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Example::

async def transfer(pipe):
    await pipe.decrby("wallet:from", 100)
    await pipe.incrby("wallet:to", 100)

results = await ops.transact(transfer)
Source code in src/codex_platform/redis_service/operations/pipeline.py
@catch_redis_errors
async def transact(self, builder_func: Callable[[Pipeline], Awaitable[None]]) -> list[Any]:
    """Execute commands in an atomic transaction (MULTI/EXEC).

    All commands inside ``builder_func`` are executed atomically.
    If the server crashes before EXEC, none of the commands are applied.

    Args:
        builder_func: Async function that receives a ``Pipeline`` and queues commands.

    Returns:
        List of results for each queued command, in order.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.

    Example::

        async def transfer(pipe):
            await pipe.decrby("wallet:from", 100)
            await pipe.incrby("wallet:to", 100)

        results = await ops.transact(transfer)
    """
    async with self.client.pipeline(transaction=True) as pipe:
        await builder_func(pipe)
        results = await pipe.execute()
    log.debug("PipelineOps | transact commands=%d", len(results))
    return results
atomic() async

Async context manager for an atomic block (MULTI/EXEC).

Opens a Pipeline in transaction mode. EXEC is called automatically on exit.

Yields:

Type Description
AsyncIterator[Pipeline]

Pipeline instance in MULTI/EXEC mode.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Example::

async with service.pipeline.atomic() as pipe:
    await pipe.set("session:abc", "token")
    await pipe.expire("session:abc", 3600)
# EXEC is called automatically on context exit
Source code in src/codex_platform/redis_service/operations/pipeline.py
@asynccontextmanager
async def atomic(self) -> AsyncIterator[Pipeline]:
    """Async context manager for an atomic block (MULTI/EXEC).

    Opens a Pipeline in transaction mode. EXEC is called automatically on exit.

    Yields:
        ``Pipeline`` instance in MULTI/EXEC mode.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.

    Example::

        async with service.pipeline.atomic() as pipe:
            await pipe.set("session:abc", "token")
            await pipe.expire("session:abc", 3600)
        # EXEC is called automatically on context exit
    """
    from redis.exceptions import ConnectionError, RedisError, TimeoutError

    pipe: Pipeline = self.client.pipeline(transaction=True)
    try:
        async with pipe as p:
            yield p
            await p.execute()
            log.debug("PipelineOps | atomic block committed")
    except (ConnectionError, TimeoutError) as e:
        raise RedisConnectionError(f"Atomic block connection failed: {e}") from e
    except RedisError as e:
        raise RedisServiceError(f"Atomic block error: {e}") from e
eval_script(script, keys=None, args=None) async

Execute a Lua script (EVAL). Lua scripts are always atomic in Redis.

Use for complex read-modify-write operations that must not be interrupted.

Parameters:

Name Type Description Default
script str

Lua script source code.

required
keys list[str] | None

List of Redis keys accessible as KEYS[1], KEYS[2], etc.

None
args list[Any] | None

Script arguments accessible as ARGV[1], ARGV[2], etc.

None

Returns:

Type Description
Any

Value returned by the Lua script.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Example::

result = await ops.eval_script(
    """
    local val = redis.call('GET', KEYS[1])
    if val == ARGV[1] then
        redis.call('SET', KEYS[1], ARGV[2])
        return 1
    end
    return 0
    """,
    keys=["mykey"],
    args=["expected", "new_value"],
)
Source code in src/codex_platform/redis_service/operations/pipeline.py
@catch_redis_errors
async def eval_script(
    self,
    script: str,
    keys: list[str] | None = None,
    args: list[Any] | None = None,
) -> Any:
    """Execute a Lua script (EVAL). Lua scripts are always atomic in Redis.

    Use for complex read-modify-write operations that must not be interrupted.

    Args:
        script: Lua script source code.
        keys: List of Redis keys accessible as ``KEYS[1]``, ``KEYS[2]``, etc.
        args: Script arguments accessible as ``ARGV[1]``, ``ARGV[2]``, etc.

    Returns:
        Value returned by the Lua script.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.

    Example::

        result = await ops.eval_script(
            \"\"\"
            local val = redis.call('GET', KEYS[1])
            if val == ARGV[1] then
                redis.call('SET', KEYS[1], ARGV[2])
                return 1
            end
            return 0
            \"\"\",
            keys=["mykey"],
            args=["expected", "new_value"],
        )
    """
    result = await self.client.eval(script, len(keys or []), *(keys or []), *(args or []))
    log.debug("PipelineOps | eval_script keys=%d args=%d", len(keys or []), len(args or []))
    return result

SetOperations

Redis Set operations (SADD / SREM / SMEMBERS / SISMEMBER and more).

Accepts an already-constructed redis.asyncio.Redis client. All methods wrap Redis errors in typed exceptions.

Example::

ops = SetOperations(client)
await ops.add("tags:post:42", "python", "redis")
has_tag = await ops.is_member("tags:post:42", "python")
Source code in src/codex_platform/redis_service/operations/set_.py
class SetOperations:
    """Redis Set operations (SADD / SREM / SMEMBERS / SISMEMBER and more).

    Accepts an already-constructed ``redis.asyncio.Redis`` client.
    All methods wrap Redis errors in typed exceptions.

    Example::

        ops = SetOperations(client)
        await ops.add("tags:post:42", "python", "redis")
        has_tag = await ops.is_member("tags:post:42", "python")
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    @catch_redis_errors
    async def add(self, key: "str | BaseRedisKey", *values: str | int, **kwargs: Any) -> int:
        """Add one or more members to a set (SADD).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            *values: Values to add. Integers are coerced to strings.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of members actually added (already-existing members are not counted).

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.sadd(real_key, *[str(v) for v in values]))

    @catch_redis_errors
    async def remove(self, key: "str | BaseRedisKey", *values: str | int, **kwargs: Any) -> int:
        """Remove one or more members from a set (SREM).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            *values: Values to remove. Integers are coerced to strings.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of members actually removed.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.srem(real_key, *[str(v) for v in values]))

    @catch_redis_errors
    async def members(self, key: "str | BaseRedisKey", **kwargs: Any) -> set[str]:
        """Return all members of a set (SMEMBERS).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Set of all member strings. Empty set if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return await self.client.smembers(real_key)

    @catch_redis_errors
    async def is_member(self, key: "str | BaseRedisKey", value: str | int, **kwargs: Any) -> bool:
        """Check whether a value is a member of a set (SISMEMBER).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            value: Value to check. Integers are coerced to strings.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            ``True`` if the value is in the set, ``False`` otherwise.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return bool(await self.client.sismember(real_key, str(value)))

    @catch_redis_errors
    async def card(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
        """Return the number of members in a set (SCARD).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Set cardinality. ``0`` if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.scard(real_key))

    @catch_redis_errors
    async def pop(self, key: "str | BaseRedisKey", count: int = 1, **kwargs: Any) -> set[str]:
        """Remove and return random members from a set (SPOP).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            count: Number of members to pop. Defaults to ``1``.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Set of popped members. Empty set if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        result = await self.client.spop(real_key, count)
        return set(result) if result else set()

    @catch_redis_errors
    async def random(self, key: "str | BaseRedisKey", count: int = 1, **kwargs: Any) -> list[str]:
        """Return random members without removing them (SRANDMEMBER).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            count: Number of random members to return.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List of random members (may contain duplicates if ``count > cardinality``).

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return await self.client.srandmember(real_key, count)

    @catch_redis_errors
    async def union(self, *keys: str) -> set[str]:
        """Return the union of multiple sets (SUNION).

        Args:
            *keys: Redis key strings.

        Returns:
            Set containing all members from all given sets.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        return await self.client.sunion(list(keys))

    @catch_redis_errors
    async def inter(self, *keys: str) -> set[str]:
        """Return the intersection of multiple sets (SINTER).

        Args:
            *keys: Redis key strings.

        Returns:
            Set containing only members present in all given sets.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        return await self.client.sinter(list(keys))

    @catch_redis_errors
    async def diff(self, *keys: str) -> set[str]:
        """Return the difference between the first set and all subsequent sets (SDIFF).

        Args:
            *keys: Redis key strings. The first key is the base set.

        Returns:
            Set of members present in the first set but not in any of the others.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        return await self.client.sdiff(list(keys))
Functions
add(key, *values, **kwargs) async

Add one or more members to a set (SADD).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
*values str | int

Values to add. Integers are coerced to strings.

()
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of members actually added (already-existing members are not counted).

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def add(self, key: "str | BaseRedisKey", *values: str | int, **kwargs: Any) -> int:
    """Add one or more members to a set (SADD).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        *values: Values to add. Integers are coerced to strings.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of members actually added (already-existing members are not counted).

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.sadd(real_key, *[str(v) for v in values]))
remove(key, *values, **kwargs) async

Remove one or more members from a set (SREM).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
*values str | int

Values to remove. Integers are coerced to strings.

()
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of members actually removed.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def remove(self, key: "str | BaseRedisKey", *values: str | int, **kwargs: Any) -> int:
    """Remove one or more members from a set (SREM).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        *values: Values to remove. Integers are coerced to strings.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of members actually removed.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.srem(real_key, *[str(v) for v in values]))
members(key, **kwargs) async

Return all members of a set (SMEMBERS).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
set[str]

Set of all member strings. Empty set if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def members(self, key: "str | BaseRedisKey", **kwargs: Any) -> set[str]:
    """Return all members of a set (SMEMBERS).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Set of all member strings. Empty set if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return await self.client.smembers(real_key)
is_member(key, value, **kwargs) async

Check whether a value is a member of a set (SISMEMBER).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
value str | int

Value to check. Integers are coerced to strings.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
bool

True if the value is in the set, False otherwise.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def is_member(self, key: "str | BaseRedisKey", value: str | int, **kwargs: Any) -> bool:
    """Check whether a value is a member of a set (SISMEMBER).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        value: Value to check. Integers are coerced to strings.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        ``True`` if the value is in the set, ``False`` otherwise.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return bool(await self.client.sismember(real_key, str(value)))
card(key, **kwargs) async

Return the number of members in a set (SCARD).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Set cardinality. 0 if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def card(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
    """Return the number of members in a set (SCARD).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Set cardinality. ``0`` if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.scard(real_key))
pop(key, count=1, **kwargs) async

Remove and return random members from a set (SPOP).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
count int

Number of members to pop. Defaults to 1.

1
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
set[str]

Set of popped members. Empty set if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def pop(self, key: "str | BaseRedisKey", count: int = 1, **kwargs: Any) -> set[str]:
    """Remove and return random members from a set (SPOP).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        count: Number of members to pop. Defaults to ``1``.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Set of popped members. Empty set if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    result = await self.client.spop(real_key, count)
    return set(result) if result else set()
random(key, count=1, **kwargs) async

Return random members without removing them (SRANDMEMBER).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
count int

Number of random members to return.

1
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
list[str]

List of random members (may contain duplicates if count > cardinality).

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def random(self, key: "str | BaseRedisKey", count: int = 1, **kwargs: Any) -> list[str]:
    """Return random members without removing them (SRANDMEMBER).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        count: Number of random members to return.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List of random members (may contain duplicates if ``count > cardinality``).

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return await self.client.srandmember(real_key, count)
union(*keys) async

Return the union of multiple sets (SUNION).

Parameters:

Name Type Description Default
*keys str

Redis key strings.

()

Returns:

Type Description
set[str]

Set containing all members from all given sets.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def union(self, *keys: str) -> set[str]:
    """Return the union of multiple sets (SUNION).

    Args:
        *keys: Redis key strings.

    Returns:
        Set containing all members from all given sets.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    return await self.client.sunion(list(keys))
inter(*keys) async

Return the intersection of multiple sets (SINTER).

Parameters:

Name Type Description Default
*keys str

Redis key strings.

()

Returns:

Type Description
set[str]

Set containing only members present in all given sets.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def inter(self, *keys: str) -> set[str]:
    """Return the intersection of multiple sets (SINTER).

    Args:
        *keys: Redis key strings.

    Returns:
        Set containing only members present in all given sets.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    return await self.client.sinter(list(keys))
diff(*keys) async

Return the difference between the first set and all subsequent sets (SDIFF).

Parameters:

Name Type Description Default
*keys str

Redis key strings. The first key is the base set.

()

Returns:

Type Description
set[str]

Set of members present in the first set but not in any of the others.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/set_.py
@catch_redis_errors
async def diff(self, *keys: str) -> set[str]:
    """Return the difference between the first set and all subsequent sets (SDIFF).

    Args:
        *keys: Redis key strings. The first key is the base set.

    Returns:
        Set of members present in the first set but not in any of the others.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    return await self.client.sdiff(list(keys))

StringOperations

Redis String and key-level operations (SET / GET / EXPIRE / TTL and more).

Accepts an already-constructed redis.asyncio.Redis client. All methods wrap Redis errors in typed exceptions.

Example::

ops = StringOperations(client)
await ops.set("session:abc", "token-value", ttl=3600)
token = await ops.get("session:abc")
Source code in src/codex_platform/redis_service/operations/string.py
class StringOperations:
    """Redis String and key-level operations (SET / GET / EXPIRE / TTL and more).

    Accepts an already-constructed ``redis.asyncio.Redis`` client.
    All methods wrap Redis errors in typed exceptions.

    Example::

        ops = StringOperations(client)
        await ops.set("session:abc", "token-value", ttl=3600)
        token = await ops.get("session:abc")
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    @catch_redis_errors
    async def set(self, key: "str | BaseRedisKey", value: str, ttl: int | None = None, **kwargs: Any) -> None:
        """Set a string value (SET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            value: String value to store.
            ttl: Expiry in seconds. ``None`` means no expiry.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        await self.client.set(real_key, value, ex=ttl)

    @catch_redis_errors
    async def setnx(self, key: "str | BaseRedisKey", value: str, ttl: int | None = None, **kwargs: Any) -> bool:
        """Set a value only if the key does not exist (SET NX).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            value: String value to store.
            ttl: Expiry in seconds. ``None`` means no expiry.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            ``True`` if the value was set, ``False`` if the key already existed.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return bool(await self.client.set(real_key, value, ex=ttl, nx=True))

    @catch_redis_errors
    async def get(self, key: "str | BaseRedisKey", **kwargs: Any) -> str | None:
        """Retrieve a string value (GET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            String value, or ``None`` if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        val = await self.client.get(real_key)
        return str(val) if val is not None else None

    @catch_redis_errors
    async def getset(self, key: "str | BaseRedisKey", value: str, **kwargs: Any) -> str | None:
        """Atomically set a new value and return the previous one (GETSET).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            value: New value to store.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Previous value, or ``None`` if the key did not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        val = await self.client.getset(real_key, value)
        return str(val) if val is not None else None

    @catch_redis_errors
    async def mget(self, *keys: str) -> list[str | None]:
        """Retrieve values for multiple keys in a single request (MGET).

        Args:
            *keys: Redis key strings.

        Returns:
            List of values in the same order as ``keys``.
            ``None`` for keys that do not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        values = await self.client.mget(list(keys))
        return [str(v) if v is not None else None for v in values]

    @catch_redis_errors
    async def mset(self, mapping: dict[str, str]) -> None:
        """Set values for multiple keys in a single call (MSET).

        Args:
            mapping: Dict of ``{key: value}`` pairs to write.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        await self.client.mset(mapping)

    @catch_redis_errors
    async def incr(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
        """Increment a numeric value by 1 (INCR).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            New value after incrementing.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.incr(real_key))

    @catch_redis_errors
    async def incrby(self, key: "str | BaseRedisKey", amount: int, **kwargs: Any) -> int:
        """Increment a numeric value by a given amount (INCRBY).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            amount: Increment step.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            New value after incrementing.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.incrby(real_key, amount))

    @catch_redis_errors
    async def append(self, key: "str | BaseRedisKey", value: str, **kwargs: Any) -> int:
        """Append a string to an existing value (APPEND).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            value: String to append.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            New total length of the value after appending.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.append(real_key, value))

    @catch_redis_errors
    async def delete(self, key: "str | BaseRedisKey", **kwargs: Any) -> None:
        """Delete a key (DEL).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        await self.client.delete(real_key)

    @catch_redis_errors
    async def delete_by_pattern(self, pattern: str) -> int:
        """Delete all keys matching a glob pattern (SCAN + DEL).

        Args:
            pattern: Glob pattern, e.g. ``"session:*"``.

        Returns:
            Number of keys deleted.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        keys = [k async for k in self.client.scan_iter(match=pattern)]
        if not keys:
            return 0
        return int(await self.client.delete(*keys))

    @catch_redis_errors
    async def expire(self, key: "str | BaseRedisKey", ttl: int, **kwargs: Any) -> bool:
        """Set a TTL (expiry) on a key in seconds (EXPIRE).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            ttl: Time-to-live in seconds.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            ``True`` if the TTL was set, ``False`` if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return bool(await self.client.expire(real_key, ttl))

    @catch_redis_errors
    async def ttl(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
        """Return the remaining TTL of a key in seconds (TTL).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Remaining TTL in seconds. ``-1`` if no TTL is set, ``-2`` if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.ttl(real_key))

    @catch_redis_errors
    async def exists(self, key: "str | BaseRedisKey", **kwargs: Any) -> bool:
        """Check whether a key exists (EXISTS).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            ``True`` if the key exists, ``False`` otherwise.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return bool(await self.client.exists(real_key))

    @catch_redis_errors
    async def rename(self, key: "str | BaseRedisKey", new_key: str, **kwargs: Any) -> None:
        """Rename a key (RENAME).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            new_key: Target key name.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        await self.client.rename(real_key, new_key)

    @catch_redis_errors
    async def key_type(self, key: "str | BaseRedisKey", **kwargs: Any) -> str:
        """Return the data type stored at a key (TYPE).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            One of: ``"string"``, ``"list"``, ``"set"``, ``"zset"``, ``"hash"``, ``"stream"``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return await self.client.type(real_key)
Functions
set(key, value, ttl=None, **kwargs) async

Set a string value (SET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
value str

String value to store.

required
ttl int | None

Expiry in seconds. None means no expiry.

None
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def set(self, key: "str | BaseRedisKey", value: str, ttl: int | None = None, **kwargs: Any) -> None:
    """Set a string value (SET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        value: String value to store.
        ttl: Expiry in seconds. ``None`` means no expiry.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    await self.client.set(real_key, value, ex=ttl)
setnx(key, value, ttl=None, **kwargs) async

Set a value only if the key does not exist (SET NX).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
value str

String value to store.

required
ttl int | None

Expiry in seconds. None means no expiry.

None
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
bool

True if the value was set, False if the key already existed.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def setnx(self, key: "str | BaseRedisKey", value: str, ttl: int | None = None, **kwargs: Any) -> bool:
    """Set a value only if the key does not exist (SET NX).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        value: String value to store.
        ttl: Expiry in seconds. ``None`` means no expiry.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        ``True`` if the value was set, ``False`` if the key already existed.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return bool(await self.client.set(real_key, value, ex=ttl, nx=True))
get(key, **kwargs) async

Retrieve a string value (GET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
str | None

String value, or None if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def get(self, key: "str | BaseRedisKey", **kwargs: Any) -> str | None:
    """Retrieve a string value (GET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        String value, or ``None`` if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    val = await self.client.get(real_key)
    return str(val) if val is not None else None
getset(key, value, **kwargs) async

Atomically set a new value and return the previous one (GETSET).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
value str

New value to store.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
str | None

Previous value, or None if the key did not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def getset(self, key: "str | BaseRedisKey", value: str, **kwargs: Any) -> str | None:
    """Atomically set a new value and return the previous one (GETSET).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        value: New value to store.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Previous value, or ``None`` if the key did not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    val = await self.client.getset(real_key, value)
    return str(val) if val is not None else None
mget(*keys) async

Retrieve values for multiple keys in a single request (MGET).

Parameters:

Name Type Description Default
*keys str

Redis key strings.

()

Returns:

Type Description
list[str | None]

List of values in the same order as keys.

list[str | None]

None for keys that do not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def mget(self, *keys: str) -> list[str | None]:
    """Retrieve values for multiple keys in a single request (MGET).

    Args:
        *keys: Redis key strings.

    Returns:
        List of values in the same order as ``keys``.
        ``None`` for keys that do not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    values = await self.client.mget(list(keys))
    return [str(v) if v is not None else None for v in values]
mset(mapping) async

Set values for multiple keys in a single call (MSET).

Parameters:

Name Type Description Default
mapping dict[str, str]

Dict of {key: value} pairs to write.

required

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def mset(self, mapping: dict[str, str]) -> None:
    """Set values for multiple keys in a single call (MSET).

    Args:
        mapping: Dict of ``{key: value}`` pairs to write.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    await self.client.mset(mapping)
incr(key, **kwargs) async

Increment a numeric value by 1 (INCR).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

New value after incrementing.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def incr(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
    """Increment a numeric value by 1 (INCR).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        New value after incrementing.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.incr(real_key))
incrby(key, amount, **kwargs) async

Increment a numeric value by a given amount (INCRBY).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
amount int

Increment step.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

New value after incrementing.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def incrby(self, key: "str | BaseRedisKey", amount: int, **kwargs: Any) -> int:
    """Increment a numeric value by a given amount (INCRBY).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        amount: Increment step.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        New value after incrementing.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.incrby(real_key, amount))
append(key, value, **kwargs) async

Append a string to an existing value (APPEND).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
value str

String to append.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

New total length of the value after appending.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def append(self, key: "str | BaseRedisKey", value: str, **kwargs: Any) -> int:
    """Append a string to an existing value (APPEND).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        value: String to append.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        New total length of the value after appending.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.append(real_key, value))
delete(key, **kwargs) async

Delete a key (DEL).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def delete(self, key: "str | BaseRedisKey", **kwargs: Any) -> None:
    """Delete a key (DEL).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    await self.client.delete(real_key)
delete_by_pattern(pattern) async

Delete all keys matching a glob pattern (SCAN + DEL).

Parameters:

Name Type Description Default
pattern str

Glob pattern, e.g. "session:*".

required

Returns:

Type Description
int

Number of keys deleted.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def delete_by_pattern(self, pattern: str) -> int:
    """Delete all keys matching a glob pattern (SCAN + DEL).

    Args:
        pattern: Glob pattern, e.g. ``"session:*"``.

    Returns:
        Number of keys deleted.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    keys = [k async for k in self.client.scan_iter(match=pattern)]
    if not keys:
        return 0
    return int(await self.client.delete(*keys))
expire(key, ttl, **kwargs) async

Set a TTL (expiry) on a key in seconds (EXPIRE).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
ttl int

Time-to-live in seconds.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
bool

True if the TTL was set, False if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def expire(self, key: "str | BaseRedisKey", ttl: int, **kwargs: Any) -> bool:
    """Set a TTL (expiry) on a key in seconds (EXPIRE).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        ttl: Time-to-live in seconds.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        ``True`` if the TTL was set, ``False`` if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return bool(await self.client.expire(real_key, ttl))
ttl(key, **kwargs) async

Return the remaining TTL of a key in seconds (TTL).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Remaining TTL in seconds. -1 if no TTL is set, -2 if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def ttl(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
    """Return the remaining TTL of a key in seconds (TTL).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Remaining TTL in seconds. ``-1`` if no TTL is set, ``-2`` if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.ttl(real_key))
exists(key, **kwargs) async

Check whether a key exists (EXISTS).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
bool

True if the key exists, False otherwise.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def exists(self, key: "str | BaseRedisKey", **kwargs: Any) -> bool:
    """Check whether a key exists (EXISTS).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        ``True`` if the key exists, ``False`` otherwise.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return bool(await self.client.exists(real_key))
rename(key, new_key, **kwargs) async

Rename a key (RENAME).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
new_key str

Target key name.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def rename(self, key: "str | BaseRedisKey", new_key: str, **kwargs: Any) -> None:
    """Rename a key (RENAME).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        new_key: Target key name.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    await self.client.rename(real_key, new_key)
key_type(key, **kwargs) async

Return the data type stored at a key (TYPE).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
str

One of: "string", "list", "set", "zset", "hash", "stream".

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/string.py
@catch_redis_errors
async def key_type(self, key: "str | BaseRedisKey", **kwargs: Any) -> str:
    """Return the data type stored at a key (TYPE).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        One of: ``"string"``, ``"list"``, ``"set"``, ``"zset"``, ``"hash"``, ``"stream"``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return await self.client.type(real_key)

ZSetOperations

Redis Sorted Set operations (ZADD / ZRANGE / ZRANGEBYSCORE / ZREM and more).

Accepts an already-constructed redis.asyncio.Redis client. All methods wrap Redis errors in typed exceptions.

Example::

ops = ZSetOperations(client)
await ops.add("leaderboard", {"alice": 1500.0, "bob": 1200.0})
top = await ops.range("leaderboard", 0, 9, reverse=True, with_scores=True)
Source code in src/codex_platform/redis_service/operations/zset.py
class ZSetOperations:
    """Redis Sorted Set operations (ZADD / ZRANGE / ZRANGEBYSCORE / ZREM and more).

    Accepts an already-constructed ``redis.asyncio.Redis`` client.
    All methods wrap Redis errors in typed exceptions.

    Example::

        ops = ZSetOperations(client)
        await ops.add("leaderboard", {"alice": 1500.0, "bob": 1200.0})
        top = await ops.range("leaderboard", 0, 9, reverse=True, with_scores=True)
    """

    def __init__(self, client: Redis) -> None:
        self.client = client

    @catch_redis_errors
    async def add(self, key: "str | BaseRedisKey", mapping: dict[str, float], **kwargs: Any) -> int:
        """Add members with scores to a sorted set (ZADD).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            mapping: Dict of ``{member: score}`` pairs.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of new members added (existing members with updated scores are not counted).

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.zadd(real_key, mapping))

    @catch_redis_errors
    async def score(self, key: "str | BaseRedisKey", member: str, **kwargs: Any) -> float | None:
        """Return the score of a member in a sorted set (ZSCORE).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            member: Member name.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Float score of the member, or ``None`` if the member does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        val = await self.client.zscore(real_key, member)
        return float(val) if val is not None else None

    @catch_redis_errors
    async def rank(self, key: "str | BaseRedisKey", member: str, reverse: bool = False, **kwargs: Any) -> int | None:
        """Return the rank (position) of a member in a sorted set (ZRANK / ZREVRANK).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            member: Member name.
            reverse: If ``True``, use ZREVRANK (rank by descending score). Defaults to ``False``.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Zero-based rank of the member, or ``None`` if the member does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        fn = self.client.zrevrank if reverse else self.client.zrank
        result = await fn(real_key, member)
        return int(result) if result is not None else None

    @catch_redis_errors
    async def range(
        self,
        key: "str | BaseRedisKey",
        start: int = 0,
        end: int = -1,
        reverse: bool = False,
        with_scores: bool = False,
        **kwargs: Any,
    ) -> list[str] | list[tuple[str, float]]:
        """Return a range of members by rank (ZRANGE / ZREVRANGE).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            start: Start rank (0-based).
            end: End rank inclusive. ``-1`` means the last member.
            reverse: If ``True``, return members in descending score order (ZREVRANGE).
            with_scores: If ``True``, return ``[(member, score), ...]`` tuples.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List of member strings, or list of ``(member, score)`` tuples if ``with_scores=True``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        if reverse:
            result = await self.client.zrevrange(real_key, start, end, withscores=with_scores)
        else:
            result = await self.client.zrange(real_key, start, end, withscores=with_scores)
        return result

    @catch_redis_errors
    async def range_by_score(
        self,
        key: "str | BaseRedisKey",
        min_score: float,
        max_score: float,
        with_scores: bool = False,
        **kwargs: Any,
    ) -> list[str] | list[tuple[str, float]]:
        """Return members within a score range (ZRANGEBYSCORE).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            min_score: Minimum score (inclusive).
            max_score: Maximum score (inclusive).
            with_scores: If ``True``, return ``[(member, score), ...]`` tuples.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            List of member strings, or list of ``(member, score)`` tuples if ``with_scores=True``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return await self.client.zrangebyscore(real_key, min_score, max_score, withscores=with_scores)

    @catch_redis_errors
    async def remove(self, key: "str | BaseRedisKey", *members: str, **kwargs: Any) -> int:
        """Remove one or more members from a sorted set (ZREM).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            *members: Member names to remove.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of members actually removed.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.zrem(real_key, *members))

    @catch_redis_errors
    async def card(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
        """Return the number of members in a sorted set (ZCARD).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of members. ``0`` if the key does not exist.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.zcard(real_key))

    @catch_redis_errors
    async def increment(self, key: "str | BaseRedisKey", member: str, amount: float = 1.0, **kwargs: Any) -> float:
        """Increment the score of a member by the given amount (ZINCRBY).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            member: Member name.
            amount: Increment value. Defaults to ``1.0``.
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            New score of the member after incrementing.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return float(await self.client.zincrby(real_key, amount, member))

    @catch_redis_errors
    async def count(self, key: "str | BaseRedisKey", min_score: float, max_score: float, **kwargs: Any) -> int:
        """Count members within a score range (ZCOUNT).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            min_score: Minimum score (inclusive).
            max_score: Maximum score (inclusive).
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of members with score in ``[min_score, max_score]``.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.zcount(real_key, min_score, max_score))

    @catch_redis_errors
    async def remove_by_rank(self, key: "str | BaseRedisKey", start: int, end: int, **kwargs: Any) -> int:
        """Remove members by rank range (ZREMRANGEBYRANK).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            start: Start rank (inclusive, 0-based).
            end: End rank (inclusive).
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of members removed.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.zremrangebyrank(real_key, start, end))

    @catch_redis_errors
    async def remove_by_score(
        self, key: "str | BaseRedisKey", min_score: float, max_score: float, **kwargs: Any
    ) -> int:
        """Remove members within a score range (ZREMRANGEBYSCORE).

        Args:
            key: Redis key or a ``BaseRedisKey`` instance.
            min_score: Minimum score (inclusive).
            max_score: Maximum score (inclusive).
            **kwargs: Extra parameters forwarded to ``resolve_key``.

        Returns:
            Number of members removed.

        Raises:
            RedisConnectionError: Redis connection failure.
            RedisServiceError: Redis operation failure.
        """
        real_key = resolve_key(key, **kwargs)
        return int(await self.client.zremrangebyscore(real_key, min_score, max_score))
Functions
add(key, mapping, **kwargs) async

Add members with scores to a sorted set (ZADD).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
mapping dict[str, float]

Dict of {member: score} pairs.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of new members added (existing members with updated scores are not counted).

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def add(self, key: "str | BaseRedisKey", mapping: dict[str, float], **kwargs: Any) -> int:
    """Add members with scores to a sorted set (ZADD).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        mapping: Dict of ``{member: score}`` pairs.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of new members added (existing members with updated scores are not counted).

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.zadd(real_key, mapping))
score(key, member, **kwargs) async

Return the score of a member in a sorted set (ZSCORE).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
member str

Member name.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
float | None

Float score of the member, or None if the member does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def score(self, key: "str | BaseRedisKey", member: str, **kwargs: Any) -> float | None:
    """Return the score of a member in a sorted set (ZSCORE).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        member: Member name.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Float score of the member, or ``None`` if the member does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    val = await self.client.zscore(real_key, member)
    return float(val) if val is not None else None
rank(key, member, reverse=False, **kwargs) async

Return the rank (position) of a member in a sorted set (ZRANK / ZREVRANK).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
member str

Member name.

required
reverse bool

If True, use ZREVRANK (rank by descending score). Defaults to False.

False
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int | None

Zero-based rank of the member, or None if the member does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def rank(self, key: "str | BaseRedisKey", member: str, reverse: bool = False, **kwargs: Any) -> int | None:
    """Return the rank (position) of a member in a sorted set (ZRANK / ZREVRANK).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        member: Member name.
        reverse: If ``True``, use ZREVRANK (rank by descending score). Defaults to ``False``.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Zero-based rank of the member, or ``None`` if the member does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    fn = self.client.zrevrank if reverse else self.client.zrank
    result = await fn(real_key, member)
    return int(result) if result is not None else None
range(key, start=0, end=-1, reverse=False, with_scores=False, **kwargs) async

Return a range of members by rank (ZRANGE / ZREVRANGE).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
start int

Start rank (0-based).

0
end int

End rank inclusive. -1 means the last member.

-1
reverse bool

If True, return members in descending score order (ZREVRANGE).

False
with_scores bool

If True, return [(member, score), ...] tuples.

False
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
list[str] | list[tuple[str, float]]

List of member strings, or list of (member, score) tuples if with_scores=True.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def range(
    self,
    key: "str | BaseRedisKey",
    start: int = 0,
    end: int = -1,
    reverse: bool = False,
    with_scores: bool = False,
    **kwargs: Any,
) -> list[str] | list[tuple[str, float]]:
    """Return a range of members by rank (ZRANGE / ZREVRANGE).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        start: Start rank (0-based).
        end: End rank inclusive. ``-1`` means the last member.
        reverse: If ``True``, return members in descending score order (ZREVRANGE).
        with_scores: If ``True``, return ``[(member, score), ...]`` tuples.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List of member strings, or list of ``(member, score)`` tuples if ``with_scores=True``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    if reverse:
        result = await self.client.zrevrange(real_key, start, end, withscores=with_scores)
    else:
        result = await self.client.zrange(real_key, start, end, withscores=with_scores)
    return result
range_by_score(key, min_score, max_score, with_scores=False, **kwargs) async

Return members within a score range (ZRANGEBYSCORE).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
min_score float

Minimum score (inclusive).

required
max_score float

Maximum score (inclusive).

required
with_scores bool

If True, return [(member, score), ...] tuples.

False
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
list[str] | list[tuple[str, float]]

List of member strings, or list of (member, score) tuples if with_scores=True.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def range_by_score(
    self,
    key: "str | BaseRedisKey",
    min_score: float,
    max_score: float,
    with_scores: bool = False,
    **kwargs: Any,
) -> list[str] | list[tuple[str, float]]:
    """Return members within a score range (ZRANGEBYSCORE).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        min_score: Minimum score (inclusive).
        max_score: Maximum score (inclusive).
        with_scores: If ``True``, return ``[(member, score), ...]`` tuples.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        List of member strings, or list of ``(member, score)`` tuples if ``with_scores=True``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return await self.client.zrangebyscore(real_key, min_score, max_score, withscores=with_scores)
remove(key, *members, **kwargs) async

Remove one or more members from a sorted set (ZREM).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
*members str

Member names to remove.

()
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of members actually removed.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def remove(self, key: "str | BaseRedisKey", *members: str, **kwargs: Any) -> int:
    """Remove one or more members from a sorted set (ZREM).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        *members: Member names to remove.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of members actually removed.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.zrem(real_key, *members))
card(key, **kwargs) async

Return the number of members in a sorted set (ZCARD).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of members. 0 if the key does not exist.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def card(self, key: "str | BaseRedisKey", **kwargs: Any) -> int:
    """Return the number of members in a sorted set (ZCARD).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of members. ``0`` if the key does not exist.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.zcard(real_key))
increment(key, member, amount=1.0, **kwargs) async

Increment the score of a member by the given amount (ZINCRBY).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
member str

Member name.

required
amount float

Increment value. Defaults to 1.0.

1.0
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
float

New score of the member after incrementing.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def increment(self, key: "str | BaseRedisKey", member: str, amount: float = 1.0, **kwargs: Any) -> float:
    """Increment the score of a member by the given amount (ZINCRBY).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        member: Member name.
        amount: Increment value. Defaults to ``1.0``.
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        New score of the member after incrementing.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return float(await self.client.zincrby(real_key, amount, member))
count(key, min_score, max_score, **kwargs) async

Count members within a score range (ZCOUNT).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
min_score float

Minimum score (inclusive).

required
max_score float

Maximum score (inclusive).

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of members with score in [min_score, max_score].

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def count(self, key: "str | BaseRedisKey", min_score: float, max_score: float, **kwargs: Any) -> int:
    """Count members within a score range (ZCOUNT).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        min_score: Minimum score (inclusive).
        max_score: Maximum score (inclusive).
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of members with score in ``[min_score, max_score]``.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.zcount(real_key, min_score, max_score))
remove_by_rank(key, start, end, **kwargs) async

Remove members by rank range (ZREMRANGEBYRANK).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
start int

Start rank (inclusive, 0-based).

required
end int

End rank (inclusive).

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of members removed.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def remove_by_rank(self, key: "str | BaseRedisKey", start: int, end: int, **kwargs: Any) -> int:
    """Remove members by rank range (ZREMRANGEBYRANK).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        start: Start rank (inclusive, 0-based).
        end: End rank (inclusive).
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of members removed.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.zremrangebyrank(real_key, start, end))
remove_by_score(key, min_score, max_score, **kwargs) async

Remove members within a score range (ZREMRANGEBYSCORE).

Parameters:

Name Type Description Default
key str | BaseRedisKey

Redis key or a BaseRedisKey instance.

required
min_score float

Minimum score (inclusive).

required
max_score float

Maximum score (inclusive).

required
**kwargs Any

Extra parameters forwarded to resolve_key.

{}

Returns:

Type Description
int

Number of members removed.

Raises:

Type Description
RedisConnectionError

Redis connection failure.

RedisServiceError

Redis operation failure.

Source code in src/codex_platform/redis_service/operations/zset.py
@catch_redis_errors
async def remove_by_score(
    self, key: "str | BaseRedisKey", min_score: float, max_score: float, **kwargs: Any
) -> int:
    """Remove members within a score range (ZREMRANGEBYSCORE).

    Args:
        key: Redis key or a ``BaseRedisKey`` instance.
        min_score: Minimum score (inclusive).
        max_score: Maximum score (inclusive).
        **kwargs: Extra parameters forwarded to ``resolve_key``.

    Returns:
        Number of members removed.

    Raises:
        RedisConnectionError: Redis connection failure.
        RedisServiceError: Redis operation failure.
    """
    real_key = resolve_key(key, **kwargs)
    return int(await self.client.zremrangebyscore(real_key, min_score, max_score))

RedisService

Unified Redis service — all data-type operations in one place.

Suitable for projects that need access to multiple Redis data types through a single entry point. For selective composition, instantiate individual Operations classes directly.

Attributes:

Name Type Description
hash

Hash operations (HSET / HGET / HGETALL …).

string

String and key-level operations (SET / GET / EXPIRE …).

list

List operations (RPUSH / LPOP / LRANGE …).

set

Set operations (SADD / SREM / SMEMBERS …).

zset

Sorted-set operations (ZADD / ZRANGE / ZRANK …).

json

JSON stored as Redis strings — works with any Redis instance.

json_module

JSON via the server-side RedisJSON module (requires RedisJSON).

pipeline

Pipeline / transaction helpers.

Source code in src/codex_platform/redis_service/service.py
class RedisService:
    """Unified Redis service — all data-type operations in one place.

    Suitable for projects that need access to multiple Redis data types through
    a single entry point.  For selective composition, instantiate individual
    ``Operations`` classes directly.

    Attributes:
        hash: Hash operations (HSET / HGET / HGETALL …).
        string: String and key-level operations (SET / GET / EXPIRE …).
        list: List operations (RPUSH / LPOP / LRANGE …).
        set: Set operations (SADD / SREM / SMEMBERS …).
        zset: Sorted-set operations (ZADD / ZRANGE / ZRANK …).
        json: JSON stored as Redis strings — works with any Redis instance.
        json_module: JSON via the server-side RedisJSON module (requires RedisJSON).
        pipeline: Pipeline / transaction helpers.
    """

    def __init__(self, client: Redis) -> None:
        """Initialize the service with an existing async Redis client.

        Args:
            client: An already-constructed ``redis.asyncio.Redis`` instance.
        """
        self.hash = HashOperations(client)
        self.string = StringOperations(client)
        self.list = ListOperations(client)
        self.set = SetOperations(client)
        self.zset = ZSetOperations(client)
        self.json = JsonStringOperations(client)
        self.json_module = JsonModuleOperations(client)
        self.pipeline = PipelineOperations(client)
Functions
__init__(client)

Initialize the service with an existing async Redis client.

Parameters:

Name Type Description Default
client Redis

An already-constructed redis.asyncio.Redis instance.

required
Source code in src/codex_platform/redis_service/service.py
def __init__(self, client: Redis) -> None:
    """Initialize the service with an existing async Redis client.

    Args:
        client: An already-constructed ``redis.asyncio.Redis`` instance.
    """
    self.hash = HashOperations(client)
    self.string = StringOperations(client)
    self.list = ListOperations(client)
    self.set = SetOperations(client)
    self.zset = ZSetOperations(client)
    self.json = JsonStringOperations(client)
    self.json_module = JsonModuleOperations(client)
    self.pipeline = PipelineOperations(client)