diff --git a/.env.test b/.env.test index d98e332d4..3395a1cc3 100644 --- a/.env.test +++ b/.env.test @@ -10,7 +10,7 @@ MYSQL__IMAGE=mysql:8.4.13 OTEL_COLLECTOR__IMAGE=otel/opentelemetry-collector-contrib:0.165.0 POSTGRES__IMAGE=postgres:18.7-alpine PUSHGATEWAY__IMAGE=prom/pushgateway:v1.11.5 -REDIS__IMAGE=redis:8.10.3-alpine +REDIS__IMAGE=ghcr.io/redis/docker-library-redis:8.12.0-alpine SCYLLADB__IMAGE=scylladb/scylla:2026.3.6 STARROCKS__IMAGE=starrocks/allin1-ubuntu:4.1.8 TEMPORAL__IMAGE=temporalio/temporal:1.10.1 diff --git a/.github/workflows/link-check.yml b/.github/workflows/link-check.yml index 57024dd7f..2e0ae3e2e 100644 --- a/.github/workflows/link-check.yml +++ b/.github/workflows/link-check.yml @@ -22,5 +22,9 @@ jobs: - uses: lycheeverse/lychee-action@v2 with: - args: --no-progress --max-retries 2 --accept 200,429 --exclude 'localhost' --exclude '127\.0\.0\.1' 'README.md' 'docs/**/*.md' + args: >- + --no-progress --max-retries 2 --accept 200,429 + --exclude 'localhost' --exclude '127\.0\.0\.1' + --remap '^https://github\.com/SyntaxArc/ArchiPy/blob/master/ file://${{ github.workspace }}/' + 'README.md' 'docs/**/*.md' fail: true diff --git a/archipy/configs/sections/redis.py b/archipy/configs/sections/redis.py index c08de95a3..4b896595a 100644 --- a/archipy/configs/sections/redis.py +++ b/archipy/configs/sections/redis.py @@ -28,6 +28,11 @@ class RedisClusterConfig(BaseModel): NODES: list[str] = Field(default=[], description="List of cluster node addresses (host:port)") REQUIRE_FULL_COVERAGE: bool = Field(default=True, description="Require full cluster coverage") + TOPOLOGY_REFRESH_MIN_INTERVAL: float | None = Field( + default=None, + ge=0, + description="Minimum seconds between error-triggered topology refreshes; None uses the client default", + ) READ_FROM_REPLICAS: bool = Field(default=True, description="Allow reading from replica nodes") @@ -79,6 +84,7 @@ class RedisRetryConfig(BaseModel): ) BACKOFF_BASE: float = Field(default=0.008, gt=0, description="Exponential backoff base delay in seconds") BACKOFF_CAP: float = Field(default=0.512, gt=0, description="Exponential backoff maximum delay in seconds") + FAIL_FAST_MISSING_SOCKET: bool = Field(default=False, description="Skip retries when the Unix socket is missing") ON_TIMEOUT: bool = Field(default=False, description="Also retry commands that hit a socket timeout") @@ -91,12 +97,13 @@ class RedisConfig(BaseModel): MODE: RedisMode = Field(default=RedisMode.STANDALONE, description="Redis deployment mode") MASTER_HOST: str | None = Field(default="localhost", description="Redis master host (standalone/sentinel)") SLAVE_HOST: str | None = Field(default=None, description="Redis slave host (standalone)") + UNIX_SOCKET_PATH: str | None = Field(default=None, min_length=1, description="Standalone Redis Unix socket path") PORT: int = Field(default=6379, description="Default Redis server port") DATABASE: int = Field(default=0, description="Redis database number (standalone and sentinel; ignored in cluster)") USERNAME: str | None = Field(default=None, description="Redis ACL username (Redis 6+); None uses the default user") PASSWORD: SecretStr | None = Field(default=None, description="Redis password") DECODE_RESPONSES: Literal[True] = Field(default=True, description="Whether to decode responses") - PROTOCOL: Literal[2, 3] = Field(default=3, description="RESP protocol version (2 or 3)") + PROTOCOL: Literal[2, 3] | None = Field(default=3, description="RESP protocol version; None enables negotiation") HEALTH_CHECK_INTERVAL: int = Field(default=10, description="Health check interval in seconds") SOCKET_KEEPALIVE: bool | None = Field( default=None, @@ -136,11 +143,21 @@ def validate_mode_configuration(self) -> Self: for node in self.SENTINEL.NODES: self._validate_node_address(node, port_required=True) - elif self.MODE == RedisMode.STANDALONE and not self.MASTER_HOST: + elif not (self.MASTER_HOST or self.UNIX_SOCKET_PATH): raise ConfigurationError(operation="redis", reason="master_host_required") return self + @model_validator(mode="after") + def validate_unix_socket(self) -> Self: + """Validate options for a standalone Unix socket connection.""" + if self.UNIX_SOCKET_PATH and (self.MODE != RedisMode.STANDALONE or self.TLS.IS_ENABLED or self.SLAVE_HOST): + raise ConfigurationError(operation="redis", reason="unix_socket_requires_standalone_without_tls_or_replica") + if self.RETRY.FAIL_FAST_MISSING_SOCKET and self.UNIX_SOCKET_PATH is None: + raise ConfigurationError(operation="redis", reason="missing_socket_fast_fail_requires_unix_socket") + + return self + @model_validator(mode="after") def warn_insecure_tls(self) -> Self: """Warn when credentials travel without TLS or the server identity is not verified.""" diff --git a/archipy/models/dtos/redis/search/aggregation_dto.py b/archipy/models/dtos/redis/search/aggregation_dto.py index aba4643fc..e41e55cee 100644 --- a/archipy/models/dtos/redis/search/aggregation_dto.py +++ b/archipy/models/dtos/redis/search/aggregation_dto.py @@ -1,8 +1,8 @@ """DTOs for Redis Search aggregations.""" -from typing import Literal +from typing import Annotated, Literal -from pydantic import field_validator +from pydantic import Field, field_validator from archipy.models.dtos.base_dtos import BaseDTO from archipy.models.dtos.redis.search.escaping import SearchIdentifier @@ -18,12 +18,16 @@ class AggregationDTO(BaseDTO): query: str = "*" group_by: list[SearchIdentifier] | None = None reduce_field: SearchIdentifier | None = None - reduce_function: SearchIdentifier | None = None + reduce_function: Literal["COUNT", "COLLECT"] | None = None + collect_fields: list[SearchIdentifier] = Field(default_factory=list) + collect_sort_by: SearchIdentifier | None = None + collect_sort_direction: Literal["ASC", "DESC"] = "ASC" + collect_limit: tuple[Annotated[int, Field(ge=0)], Annotated[int, Field(ge=0)]] | None = None sort_by: SearchIdentifier | None = None sort_direction: Literal["ASC", "DESC"] = "ASC" limit: int | None = None - @field_validator("sort_direction", mode="before") + @field_validator("sort_direction", "collect_sort_direction", mode="before") @classmethod def _normalize_sort_direction(cls, value: object) -> object: """Accept any casing of ASC/DESC, as before.""" diff --git a/docs/tutorials/adapters/redis.md b/docs/tutorials/adapters/redis.md index dd3795ec6..59d9fa1e5 100644 --- a/docs/tutorials/adapters/redis.md +++ b/docs/tutorials/adapters/redis.md @@ -86,6 +86,16 @@ REDIS__SENTINEL__USERNAME=sentinel-user # sentinel ACL user, used with SENTINEL `SSL` or when `SSL_CHECK_HOSTNAME` is disabled. `SENTINEL_NODES` entries must be `host:port` and `CLUSTER_NODES` ports must be numeric; malformed entries raise `ConfigurationError`. +### Protocol negotiation, Unix sockets, and cluster refresh + +Set `RedisConfig(PROTOCOL=None)` to negotiate RESP3 and allow redis-py to fall back to RESP2 when a +server rejects `HELLO`. The default is explicit RESP3. + +Use `REDIS__UNIX_SOCKET_PATH` for a standalone Unix socket connection. Set +`REDIS__RETRY__FAIL_FAST_MISSING_SOCKET=true` to skip backoff for a missing socket. +Set `REDIS__CLUSTER__TOPOLOGY_REFRESH_MIN_INTERVAL` in seconds to control the minimum time between +error-triggered cluster topology refreshes. The redis-py default applies when the option is unset. + ## Basic Usage === "Sync" @@ -179,6 +189,10 @@ async def run() -> None: await redis.set("key", "value") ``` +Sentinel adapters close their data clients and Sentinel discovery pools when the adapter closes. Async standalone +and cluster clients use redis-py’s automatic RESP3 maintenance notifications on supported deployments. +The Redis Open Source test image lacks this server capability. See [Redis smart client handoffs](https://redis.io/docs/latest/develop/clients/sch/). + ### Async iteration On the async adapter, `scan_iter()` and `sscan_iter()` can be iterated directly with `async for key in @@ -186,6 +200,30 @@ redis.scan_iter(match="user:*")`. The older `async for key in await redis.scan_i ## Caching Patterns +### Server-assisted client-side caching + +The sync standalone and cluster adapters accept redis-py's `CacheConfig`. Use explicit RESP3 and +Redis 7.4 or newer. The tracking mode controls which reads Redis tracks, and a predicate can +further limit cache eligibility. + +```python +from redis.cache import CacheConfig, TrackingMode + +from archipy.adapters.redis.adapters import RedisAdapter + +with RedisAdapter( + cache_config=CacheConfig( + tracking_mode=TrackingMode.OPTIN, + cache_predicate=lambda command, keys: command == "GET" and keys[0].startswith("products:"), + ), +) as redis: + product = redis.get("products:42") +``` + +`TrackingMode.OPTOUT` also tracks eligible cached reads. `TrackingMode.PLAIN` is the default. +The sync adapter accepts a `MetadataResolver` to customize command eligibility and cluster +routing. The async cluster adapter accepts an `AsyncMetadataResolver` for routing. + ### Function Result Caching ```python @@ -266,8 +304,68 @@ logger.info(f"Second call (cached): {result2}") ## Advanced Redis Features +### List batches, set cardinality, and streams + +These operations require Redis 8.10+. They are available on both adapters. Use the same hash tag +for keys in a multi-key list, set, or stream operation on Redis Cluster. + +```python +redis_adapter.rpush("{tasks}:ready", "a", "b", "c") +redis_adapter.lmovem("{tasks}:ready", "{tasks}:running", count=2, ordering="BULK") +redis_adapter.blmovem("{tasks}:ready", "{tasks}:running", timeout_seconds=1) +redis_adapter.sunioncard(["{tasks}:pending", "{tasks}:active"], limit=100) +redis_adapter.sdiffcard(["{tasks}:pending", "{tasks}:active"]) + +redis_adapter.xread({"{events}:new": "0-0"}, max_count=100, max_size=65536) +redis_adapter.xreadgroup("workers", "worker-1", {"{events}:new": ">"}, max_count=100) +``` + +`MAXCOUNT` and `MAXSIZE` apply to the whole stream reply. `MAXSIZE` still permits one oversized entry. +Create the consumer group before calling `xreadgroup`. Stream reply shapes follow the configured RESP version. + +The stream-limit and RediSearch integration scenarios run against real Redis. + +### Member expiration, sorted set moves, and maintenance + +Both adapters expose the redis-py 8.2 command families. The Redis server must support the +command you call. The ArchiPy container suite uses Redis 8.12. + +| Capability | Adapter methods | +| --- | --- | +| Set-member expiration | `saddex`, `sexpire`, `spexpire`, `sexpireat`, `spexpireat`, `sttl`, `spttl`, `sexpiretime`, `spexpiretime`, `spersist` | +| Sorted-set moves | `zmove`, `bzmove`, `zmovemember` | +| Bitmap positions and key eviction flags | `bitrangeintarray`, `bless_get`, `bless_set`, `bless_clear`, `bless_scan` | +| Client list | `client_list_iter`, with optional type or client IDs | +| Count-Min Sketch counter widths | `cms_initbydim`, `cms_initbyprob` with `cell_size` in bytes | +| Server backup | `backup_start`, `backup_status`, `backup_list`, `backup_seal`, `backup_abort`, `backup_cleanup` | + +Use a shared cluster hash tag for the source and destination of a sorted-set move. Set-member expiration +methods return one status per requested member. An async call to `client_list_iter` is awaited once and +returns an ordinary iterator. + +Backups are managed per Redis node. Connect directly to the node you intend to back up. Start the +backup, check `backup_status` for the `incrementing` state, then seal and copy the files returned by +`backup_list` before cleanup. + +### Experimental hash fieldsets + +redis-py 8.1.0 exposes experimental `HIMPORT` fieldsets on Redis 8.10+. The upstream API can change. +Use the same adapter client to prepare the fieldset, write values in field order, and discard the fieldset. +Await these calls when using the async adapter. + +```python +client = redis_adapter.client +client.himport_prepare("profile", ["name", "region"]) +try: + client.himport_set("profile:42", "profile", ["Avery", "west"]) +finally: + client.himport_discard("profile") +``` + ### Publish/Subscribe +For shard channels in Redis Cluster, call `spublish` on the adapter and `ssubscribe` on its Pub/Sub handle. + The `publish` and `pubsub` methods are available through the port interface: ```python @@ -819,6 +917,10 @@ logger.info(f"Text hits: {text_result.total}, hybrid hits: {len(hybrid_result.hi Set `text_scorer` (for example `"BM25"` or `"TFIDF"`) on `SearchQueryDTO` or `from_hybrid()` to choose the full-text scoring function; it is sent to RediSearch as `SCORER`, and an unknown name is rejected by the server. +Use `handle.hybrid_search(query, explain_score=True)` with a redis-py `HybridQuery` when you need +the native `FT.HYBRID` score explanation. The returned `HybridResult` contains score details using +Redis's response shape for the selected protocol. The async Search handle exposes the same method. + ### Aggregations Group and count documents with `AggregationDTO`: @@ -846,6 +948,23 @@ agg = handle.aggregate( logger.info(f"Aggregation rows: {agg['rows']}") ``` +Use `COLLECT` to return field values for each group on Redis 8.10+. `collect_fields` selects which fields to collect. +Omit it to collect all fields. `collect_sort_by`, `collect_sort_direction`, and `collect_limit` select and order entries +within each group. `COLLECT` is a preview feature and can require `search-enable-unstable-features` on the server. + +```python +by_category = handle.aggregate( + AggregationDTO( + group_by=["category"], + reduce_function="COLLECT", + reduce_field="titles", + collect_fields=["title"], + collect_sort_by="title", + collect_limit=(0, 10), + ), +) +``` + ### Schema Changes, Aliases, and Index Lifecycle ```python @@ -870,6 +989,8 @@ handle.drop_index(delete_documents=True) handle.delete_alias("products-view") ``` +Call `handle.list_aliases()` to list the aliases assigned to that index on Redis 8.10+. + ### Untrusted Input and Escaping `SearchQueryDTO.query`, `filter_expr` and `AggregationDTO.query` are raw RediSearch syntax and are **not** escaped. Never @@ -885,7 +1006,7 @@ hybrid = SearchQueryDTO.from_hybrid(quote_phrase(user_text), [0.1, 0.2, 0.3]) ``` Identifier-like fields (`vector_field`, `score_field`, `return_fields`, `group_by`, `sort_by`, `reduce_field`, -`reduce_function`) are validated to letters, digits, `_`, `.`, `$` and `-` (with an optional leading `@`), and +`collect_fields`) are validated to letters, digits, `_`, `.`, `$` and `-` (with an optional leading `@`), and `sort_direction` must be `ASC` or `DESC`; anything else raises a Pydantic `ValidationError`. ### Asynchronous RediSearch diff --git a/features/redis_adapter.feature b/features/redis_adapter.feature index e587356de..f6d594111 100644 --- a/features/redis_adapter.feature +++ b/features/redis_adapter.feature @@ -1,4 +1,4 @@ -@needs-redis @needs-redis-cluster +@redis @needs-redis @needs-redis-cluster Feature: Redis Testing As a developer I want to test Redis operations with both mocks and real containers @@ -7,6 +7,7 @@ Feature: Redis Testing Background: Given test entities are defined + @redis-keys @sync Scenario Outline: Store and retrieve a simple key-value pair Given a configured When I store the key "user-id" with value "12345" in @@ -20,6 +21,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: Remove a key Given a configured When I store the key "session-token" with value "abcde" in @@ -35,6 +37,7 @@ Feature: Redis Testing | container | | cluster | + @redis-lists @sync Scenario Outline: Manage a list of items Given a configured When I add "apple, banana, orange" to the list "fruits" in @@ -48,6 +51,7 @@ Feature: Redis Testing | container | | cluster | + @redis-hashes @sync Scenario Outline: Handle a hash structure Given a configured When I assign "name" to "Alice" in the hash "profile" in @@ -61,6 +65,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sets @sync Scenario Outline: Manage a set of colors Given a configured When I add "red, blue, green" to the set "colors" in @@ -74,7 +79,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: Store and retrieve a key-value pair asynchronously Given a configured async When I store the key "order-id" with value "67890" in async @@ -88,7 +93,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: Remove a key asynchronously Given a configured async When I store the key "cache-key" with value "xyz" in async @@ -104,7 +109,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-lists @async Scenario Outline: Manage a list of tasks asynchronously Given a configured async When I add "task1, task2, task3" to the list "tasks" in async @@ -118,7 +123,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-hashes @async Scenario Outline: Handle a hash structure asynchronously Given a configured async When I assign "email" to "bob@example.com" in the hash "contact" in async @@ -132,7 +137,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-sets @async Scenario Outline: Manage a set of tags asynchronously Given a configured async When I add "tag1, tag2, tag3" to the set "tags" in async @@ -146,11 +151,13 @@ Feature: Redis Testing | container | | cluster | + @redis-cluster @sync Scenario: Cluster reports healthy state Given a configured cluster When I query cluster info from the adapter Then cluster state should be ok + @redis-cluster @sync Scenario: Cluster mock exposes cluster operations without a real cluster Given a configured cluster mock When I query cluster info from the adapter @@ -160,11 +167,13 @@ Feature: Redis Testing When I get the cluster slot for key "foo" Then the cluster slot should be 12182 + @redis-cluster @async Scenario: Async cluster mock exposes the CRC16 key slot Given a configured async cluster mock When I get the cluster slot for key "foo" from the async adapter Then the cluster slot should be 12182 + @redis-keys @redis-cluster @sync Scenario Outline: Hash-tagged keys round-trip on cluster Given a configured cluster When I store the key "" with value "" in cluster @@ -176,6 +185,7 @@ Feature: Redis Testing | {user}:1 | alice | | {order}:99 | shipped | + @redis-cluster @sync Scenario Outline: Slot lookup in valid range on cluster Given a configured cluster When I get the cluster slot for key "" @@ -186,11 +196,13 @@ Feature: Redis Testing | {user}:1 | | order:99 | + @redis-cluster @sync Scenario: Cluster topology has 3 masters and 3 replicas Given a configured cluster When I query cluster nodes from the adapter Then cluster should have 3 masters and 3 replicas + @redis-cluster @sync Scenario Outline: Hash-tagged keys share slot on cluster Given a configured cluster When I get the cluster slots for keys "" and "" @@ -201,6 +213,7 @@ Feature: Redis Testing | {user}:1 | {user}:2 | | {order}:1 | {order}:2 | + @redis-cluster @sync Scenario Outline: Slot key inspection on cluster Given a configured cluster When I store the key "" with value "" in cluster @@ -213,13 +226,13 @@ Feature: Redis Testing | {user}:1 | alice | | {order}:99 | shipped | - @async + @redis-cluster @async Scenario: Cluster reports healthy state asynchronously Given a configured async cluster When I query cluster info from the async adapter Then cluster state should be ok - @async + @redis-keys @redis-cluster @async Scenario Outline: Hash-tagged keys round-trip on cluster asynchronously Given a configured async cluster When I store the key "" with value "" in async cluster @@ -231,7 +244,7 @@ Feature: Redis Testing | {user}:1 | alice | | {order}:99 | shipped | - @async + @redis-cluster @async Scenario Outline: Slot lookup in valid range on cluster asynchronously Given a configured async cluster When I get the cluster slot for key "" from the async adapter @@ -242,13 +255,13 @@ Feature: Redis Testing | {user}:1 | | order:99 | - @async + @redis-cluster @async Scenario: Cluster topology has 3 masters and 3 replicas asynchronously Given a configured async cluster When I query cluster nodes from the async adapter Then cluster should have 3 masters and 3 replicas - @async + @redis-cluster @async Scenario Outline: Hash-tagged keys share slot on cluster asynchronously Given a configured async cluster When I get the cluster slots for keys "" and "" from the async adapter @@ -259,7 +272,7 @@ Feature: Redis Testing | {user}:1 | {user}:2 | | {order}:1 | {order}:2 | - @async + @redis-cluster @async Scenario Outline: Slot key inspection on cluster asynchronously Given a configured async cluster When I store the key "" with value "" in async cluster @@ -272,6 +285,7 @@ Feature: Redis Testing | {user}:1 | alice | | {order}:99 | shipped | + @redis-keys @sync Scenario Outline: Store key with expiry and verify TTL Given a configured When I store the key "bdd-s-ttl-key" with value "expires" and expiry 60 seconds in @@ -287,6 +301,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: GetSet returns old value Given a configured When I store the key "bdd-s-gs-key" with value "old" in @@ -301,6 +316,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: GetDel returns value and removes key Given a configured When I store the key "bdd-s-gd-key" with value "gone" in @@ -315,6 +331,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: Append extends string value Given a configured When I store the key "bdd-s-app-key" with value "hello" in @@ -329,6 +346,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: Report key type Given a configured When I create a key "bdd-s--key" in @@ -353,6 +371,7 @@ Feature: Redis Testing | cluster | set | | cluster | zset | + @redis-keys @sync Scenario Outline: Increment and decrement counter Given a configured When I increment key "bdd-s-counter" by 5 in @@ -366,6 +385,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: Mset and mget multiple keys Given a configured When I mset "{bdd-s-m}:1" to "val1" and "{bdd-s-m}:2" to "val2" in @@ -378,6 +398,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: Find keys by pattern and scan Given a configured When I mset "{bdd-s-scan}:1" to "a" and "{bdd-s-scan}:2" to "b" in @@ -392,6 +413,7 @@ Feature: Redis Testing | container | | cluster | + @redis-lists @sync Scenario Outline: Lpush and lpop preserve order Given a configured When I lpush "first, second" to list "bdd-s-mylist" in @@ -405,6 +427,7 @@ Feature: Redis Testing | container | | cluster | + @redis-lists @sync Scenario Outline: Rpop and lrem modify list Given a configured When I add "a, b, a, c" to the list "bdd-s-rlist" in @@ -422,6 +445,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sets @sync Scenario Outline: Set membership and removal Given a configured When I add "alpha, beta" to the set "bdd-s-myset" in @@ -440,6 +464,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sets @sync Scenario Outline: Set union across hash-tagged sets Given a configured When I add "a, b" to the set "{bdd-s-su}:1" in @@ -453,6 +478,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sorted-sets @sync Scenario Outline: Manage sorted set members Given a configured When I zadd members "alice=10,bob=20" to sorted set "bdd-s-leaderboard" in @@ -482,6 +508,7 @@ Feature: Redis Testing | container | | cluster | + @redis-hashes @sync Scenario Outline: Hash field operations Given a configured When I hset mapping "name=Alice,email=alice@test.com" in hash "bdd-s-user" in @@ -502,6 +529,7 @@ Feature: Redis Testing | container | | cluster | + @redis-pubsub @sync Scenario Outline: Publish message to channel Given a configured When I publish "hello" to channel "bdd-s-test-channel" in @@ -513,6 +541,7 @@ Feature: Redis Testing | container | | cluster | + @redis-pubsub @sync Scenario Outline: Subscribe and receive published message Given a configured When I subscribe to channel "bdd-s-pubsub--channel" in @@ -524,6 +553,7 @@ Feature: Redis Testing | mock | | container | + @redis-pipeline @sync Scenario Outline: Pipeline executes commands atomically Given a configured When I run pipeline setting "{}:k" to "v" and incrementing "{}:cnt" by 1 in @@ -537,7 +567,7 @@ Feature: Redis Testing | container | bdd-s-p-cont | | cluster | bdd-s-p-clust | - @async + @redis-keys @async Scenario Outline: Store key with expiry and verify TTL asynchronously Given a configured async When I store the key "bdd-a-ttl-key" with value "expires" and expiry 60 seconds in async @@ -553,7 +583,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: GetSet returns old value asynchronously Given a configured async When I store the key "bdd-a-gs-key" with value "old" in async @@ -568,7 +598,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: GetDel returns value and removes key asynchronously Given a configured async When I store the key "bdd-a-gd-key" with value "gone" in async @@ -583,7 +613,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: Append extends string value asynchronously Given a configured async When I store the key "bdd-a-app-key" with value "hello" in async @@ -598,7 +628,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: Report key type asynchronously Given a configured async When I create a key "bdd-a--key" in async @@ -623,7 +653,7 @@ Feature: Redis Testing | cluster | set | | cluster | zset | - @async + @redis-keys @async Scenario Outline: Increment and decrement counter asynchronously Given a configured async When I increment key "bdd-a-counter" by 5 in async @@ -637,7 +667,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: Mset and mget multiple keys asynchronously Given a configured async When I mset "{bdd-a-m}:1" to "val1" and "{bdd-a-m}:2" to "val2" in async @@ -650,7 +680,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: Find keys by pattern and scan asynchronously Given a configured async When I mset "{bdd-a-scan}:1" to "a" and "{bdd-a-scan}:2" to "b" in async @@ -665,6 +695,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @redis-sets @async Scenario Outline: Async scan_iter and sscan_iter work with a plain async for Given a configured async When I mset "{bdd-a-direct}:1" to "a" and "{bdd-a-direct}:2" to "b" in async @@ -678,7 +709,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-lists @async Scenario Outline: Lpush and lpop preserve order asynchronously Given a configured async When I lpush "first, second" to list "bdd-a-mylist" in async @@ -692,7 +723,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-lists @async Scenario Outline: Rpop and lrem modify list asynchronously Given a configured async When I add "a, b, a, c" to the list "bdd-a-rlist" in async @@ -710,7 +741,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-sets @async Scenario Outline: Set membership and removal asynchronously Given a configured async When I add "alpha, beta" to the set "bdd-a-myset" in async @@ -729,7 +760,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-sets @async Scenario Outline: Set union across hash-tagged sets asynchronously Given a configured async When I add "a, b" to the set "{bdd-a-su}:1" in async @@ -743,7 +774,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-sorted-sets @async Scenario Outline: Manage sorted set members asynchronously Given a configured async When I zadd members "alice=10,bob=20" to sorted set "bdd-a-leaderboard" in async @@ -773,7 +804,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-hashes @async Scenario Outline: Hash field operations asynchronously Given a configured async When I hset mapping "name=Alice,email=alice@test.com" in hash "bdd-a-user" in async @@ -794,7 +825,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-pubsub @async Scenario Outline: Publish message to channel asynchronously Given a configured async When I publish "hello" to channel "bdd-a-test-channel" in async @@ -806,7 +837,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-pubsub @async Scenario Outline: Subscribe and receive published message asynchronously Given a configured async When I subscribe to channel "bdd-a-pubsub--channel" in async @@ -818,7 +849,7 @@ Feature: Redis Testing | mock | | container | - @async + @redis-pipeline @async Scenario Outline: Pipeline executes commands asynchronously Given a configured async When I run pipeline setting "{}:k" to "v" and incrementing "{}:cnt" by 1 in async @@ -833,6 +864,7 @@ Feature: Redis Testing | cluster | bdd-a-p-clust | # Redis 8.8 — Array data structure + @redis-arrays @sync Scenario Outline: Store and retrieve array elements Given a configured When I arset index 0 to "alpha, beta, gamma" in array "bdd-s-array" in @@ -849,6 +881,7 @@ Feature: Redis Testing | container | | cluster | + @redis-arrays @sync Scenario Outline: Array ring buffer retains last N elements Given a configured When I arring size 2 with "first, second, third" into array "bdd-s-ring" in @@ -863,7 +896,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-arrays @async Scenario Outline: Store and retrieve array elements asynchronously Given a configured async When I arset index 0 to "alpha, beta, gamma" in array "bdd-a-array" in async @@ -877,7 +910,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-arrays @async Scenario Outline: Array ring buffer retains last N elements asynchronously Given a configured async When I arring size 2 with "first, second, third" into array "bdd-a-ring" in async @@ -893,6 +926,7 @@ Feature: Redis Testing | cluster | # Redis 8.8 — INCREX window counter rate limiter (requires Redis 8.8+) + @redis-keys @sync Scenario Outline: INCREX respects upper bound for rate limiting Given a configured When I increx key "bdd-s-rl" by 1 with upper bound 3 and expiry 60 seconds in @@ -911,7 +945,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-keys @async Scenario Outline: INCREX respects upper bound for rate limiting asynchronously Given a configured async When I increx key "bdd-a-rl" by 1 with upper bound 3 and expiry 60 seconds in async @@ -930,6 +964,7 @@ Feature: Redis Testing | cluster | # Redis 8.8 — ZUNION/ZINTER COUNT aggregator (requires Redis 8.8+) + @redis-sorted-sets @sync Scenario Outline: ZUNION COUNT aggregator scores by set membership Given a configured When I zadd members "a=1,b=2" to sorted set "{bdd-s-zc}:1" in @@ -943,6 +978,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sorted-sets @sync Scenario Outline: ZINTER COUNT aggregator scores by set membership Given a configured When I zadd members "a=1,b=2" to sorted set "{bdd-s-zi}:1" in @@ -955,7 +991,7 @@ Feature: Redis Testing | container | | cluster | - @async + @redis-sorted-sets @async Scenario Outline: ZUNION COUNT aggregator scores by set membership asynchronously Given a configured async When I zadd members "a=1,b=2" to sorted set "{bdd-a-zc}:1" in async @@ -969,6 +1005,7 @@ Feature: Redis Testing | cluster | # Redis 8.8 — Hash subkey notifications (requires Redis 8.8+) + @redis-hashes @redis-pubsub @redis-keyspace-notifications @sync Scenario Outline: Receive hash subkey notification on field update Given a configured When I enable hash subkey notifications in @@ -980,7 +1017,7 @@ Feature: Redis Testing | adapter_type | | container | - @async + @redis-hashes @redis-pubsub @redis-keyspace-notifications @async Scenario Outline: Receive hash subkey notification on field update asynchronously Given a configured async When I enable hash subkey notifications in async @@ -993,6 +1030,7 @@ Feature: Redis Testing | container | # RediSearch / vector operations (requires Redis 8+ with query engine — container or cluster) + @redis-search @redis-vector-search @sync Scenario Outline: Create search index with vector field synchronously Given a configured When I create search index "" with prefix ":" for documents @@ -1005,6 +1043,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-hash | {srch-h} | | cluster | JSON | cluster-products-json | {srch-j} | + @redis-search @redis-vector-search @sync Scenario Outline: Upsert and KNN search documents synchronously Given a configured And search index "" exists with prefix ":" for documents @@ -1021,6 +1060,7 @@ Feature: Redis Testing | cluster | HASH | cluster-knn | {srch} | {srch}:1 | {srch}:2 | | cluster | JSON | cluster-knn-j | {srch} | {srch}:j1 | {srch}:j2 | + @redis-search @sync Scenario Outline: Create index upsert and verify document fields synchronously Given a configured When I create search index "" with prefix ":" for documents @@ -1035,6 +1075,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-fields | {fld} | {fld}:1 | | cluster | JSON | cluster-products-fields-j | {fld} | {fld}:j1 | + @redis-search @redis-vector-search @sync Scenario Outline: Hybrid search synchronously Given a configured And search index "" exists with prefix ":" for documents @@ -1049,6 +1090,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-hybrid | {hyb} | {hyb}:1 | | cluster | JSON | cluster-products-hybrid-j | {hyb} | {hyb}:j1 | + @redis-search @redis-vector-search @sync Scenario Outline: Text scorer is applied to text and hybrid searches Given a configured container And search index "" exists with prefix ":" for HASH documents @@ -1063,6 +1105,7 @@ Feature: Redis Testing | scorer-hybrid-ok | scrhok | scrhok:1 | hybrid | TFIDF | hits | | scorer-hybrid-bad | scrhbd | scrhbd:1 | hybrid | NOSUCH | rejected | + @redis-search @redis-search-aggregation @sync Scenario Outline: Aggregate documents synchronously Given a configured And search index "" exists with prefix ":" for documents @@ -1078,6 +1121,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-agg | {agg} | {agg}:1 | {agg}:2 | | cluster | JSON | cluster-products-agg-j | {agg} | {agg}:j1 | {agg}:j2 | + @redis-search @redis-search-aggregation @async Scenario: Aggregate documents asynchronously Given a configured async container And async search index "products-agg-async" exists with prefix "aggasync:" for HASH documents @@ -1085,6 +1129,7 @@ Feature: Redis Testing And I aggregate search index "products-agg-async" asynchronously grouped by title Then the aggregation should return at least 1 row + @redis-search @sync Scenario Outline: Drop search index synchronously Given a configured And search index "" exists with prefix ":" for documents @@ -1098,7 +1143,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-drop | {drp} | | cluster | JSON | cluster-products-drop-j | {drp} | - @async + @redis-search @redis-vector-search @async Scenario Outline: Upsert and KNN search documents asynchronously Given a configured async And async search index "" exists with prefix ":" for documents @@ -1113,6 +1158,7 @@ Feature: Redis Testing | cluster | HASH | cluster-async-products-knn | {asrch} | {asrch}:1 | | cluster | JSON | cluster-async-products-knn-j | {asrch} | {asrch}:j1 | + @redis-search @sync Scenario Outline: Alter index schema and verify new field Given a configured And search index "" exists with prefix ":" for documents @@ -1126,6 +1172,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-alter | {alt} | | cluster | JSON | cluster-products-alter-j | {alt} | + @redis-search @redis-search-aliases @sync Scenario Outline: Add alias and search through it Given a configured And search index "" exists with prefix ":" for documents @@ -1144,6 +1191,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-alias | {als} | {als}:1 | cluster-products-alias-v | | cluster | JSON | cluster-products-alias-j | {als} | {als}:j1 | cluster-products-alias-jv | + @redis-search @sync Scenario Outline: Delete document from search index Given a configured And search index "" exists with prefix ":" for documents @@ -1158,6 +1206,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-delete | {del} | {del}:1 | | cluster | JSON | cluster-products-delete-j | {del} | {del}:j1 | + @redis-search @sync Scenario Outline: Upsert document via DTO helper Given a configured And search index "" exists with prefix ":" for documents @@ -1171,6 +1220,7 @@ Feature: Redis Testing | cluster | HASH | cluster-products-dto-hash | {dto} | {dto}:1 | DTO Cluster | [1.0, 0.0, 0.0] | | cluster | JSON | cluster-products-dto-json | {dto} | {dto}:j1 | DTO Cluster JSON | [0.0, 0.0, 1.0] | + @redis-search @redis-vector-search @sync Scenario Outline: Create SVS-VAMANA search index synchronously Given a configured When I create search index "" with prefix ":" and algorithm SVS-VAMANA for HASH documents @@ -1181,6 +1231,7 @@ Feature: Redis Testing | container | products-svs | svs | | cluster | cluster-products-svs | {svs} | + @redis-search @redis-vector-search @sync Scenario Outline: Vector range search synchronously Given a configured And search index "" exists with prefix ":" and algorithm FLAT for HASH documents @@ -1195,6 +1246,7 @@ Feature: Redis Testing | container | products-range | rng | rng:1 | rng:2 | 0.5 | | cluster | cluster-products-range | {rng} | {rng}:1 | {rng}:2 | 0.5 | + @redis-search @redis-vector-search @sync Scenario Outline: Vector range search intersects the filter with the radius Given a configured And search index "" exists with prefix ":" and algorithm FLAT for HASH documents @@ -1211,6 +1263,7 @@ Feature: Redis Testing | cluster | cluster-range-and | {rf} | {rf}:1 | {rf}:2 | {rf}:3 | and | 1 | | cluster | cluster-range-or | {ro} | {ro}:1 | {ro}:2 | {ro}:3 | or | 3 | + @redis-cluster @redis-search @redis-vector-search @sync Scenario Outline: KNN search with shard ratio on cluster Given a configured And search index "" exists with prefix ":" for HASH documents @@ -1222,19 +1275,19 @@ Feature: Redis Testing | adapter_type | index_name | prefix | doc_id | ratio | | cluster | cluster-shard-knn | {srch} | {srch}:1 | 0.5 | - @needs-otel-collector + @redis-observability @sync @needs-otel-collector Scenario: Redis adapter commands emit spans Given adapter spans are exported to the collector When I set and get a key through the Redis adapter Then the collector should have a span with attribute "db.system" containing "redis" - @async @needs-otel-collector + @redis-observability @async @needs-otel-collector Scenario: Async Redis adapter commands emit spans Given adapter spans are exported to the collector When I set and get a key through the async Redis adapter Then the collector should have a span with attribute "db.system" containing "redis" - @needs-otel-collector + @redis-search @redis-vector-search @redis-observability @sync @needs-otel-collector Scenario: Redis search with the instrumentor bound returns results and emits a span Given adapter spans are exported to the collector And a configured container @@ -1245,7 +1298,7 @@ Feature: Redis Testing And the top hit id should be "otelsrch:1" And the collector should have a span with attribute "redis.search.index" containing "otel-search" - @async @needs-otel-collector + @redis-search @redis-vector-search @redis-observability @async @needs-otel-collector Scenario: Async Redis search with the instrumentor bound returns results and emits a span Given adapter spans are exported to the collector And a configured async container @@ -1255,6 +1308,7 @@ Feature: Redis Testing Then the async search should return at least 1 hit And the collector should have a span with attribute "db.statement" containing "FT.SEARCH" + @redis-hashes @sync Scenario Outline: Read a whole hash and list its values Given a configured When I hset mapping "name=Alice,city=Paris" in hash "bdd-s-hot-hash" in @@ -1271,6 +1325,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sets @sync Scenario Outline: Scan and pop set members Given a configured When I add "apple, apricot, banana, cherry" to the set "bdd-s-hot-set" in @@ -1288,6 +1343,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @sync Scenario Outline: Count and delete several keys Given a configured When I mset "{bdd-s-hot-keys}:1" to "a" and "{bdd-s-hot-keys}:2" to "b" in @@ -1304,6 +1360,7 @@ Feature: Redis Testing | container | | cluster | + @redis-connection @sync Scenario Outline: Ping the server Given a configured When I ping the server in @@ -1315,6 +1372,7 @@ Feature: Redis Testing | container | | cluster | + @redis-hashes @async Scenario Outline: Read a whole hash and list its values asynchronously Given a configured async When I hset mapping "name=Alice,city=Paris" in hash "bdd-a-hot-hash" in async @@ -1331,6 +1389,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sets @async Scenario Outline: Scan and pop set members asynchronously Given a configured async When I add "apple, apricot, banana, cherry" to the set "bdd-a-hot-set" in async @@ -1348,6 +1407,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @async Scenario Outline: Count and delete several keys asynchronously Given a configured async When I mset "{bdd-a-hot-keys}:1" to "a" and "{bdd-a-hot-keys}:2" to "b" in async @@ -1364,6 +1424,7 @@ Feature: Redis Testing | container | | cluster | + @redis-connection @async Scenario Outline: Ping the server asynchronously Given a configured async When I ping the server in async @@ -1375,6 +1436,7 @@ Feature: Redis Testing | container | | cluster | + @redis-sorted-sets @redis-protocol @sync Scenario Outline: The mock follows the configured RESP protocol when shaping ZPOPMAX replies Given a Redis mock configured with RESP protocol When I pop the highest member of sorted set "mock-proto" holding "alice" with score 3.0 @@ -1385,11 +1447,13 @@ Feature: Redis Testing | 2 | pairs | | 3 | flat | + @redis-connection @redis-acl @sync Scenario: A Redis ACL user can connect with its username Given a configured container When I create the ACL user "acl-reader" with password "acl-secret" and connect as that user Then the connected Redis user should be "acl-reader" + @redis-connection @redis-tls @redis-config @sync Scenario Outline: TLS settings reach the client Given a Redis config in mode with TLS and the username "acl-tls-user" When I build the Redis adapter from that config @@ -1401,6 +1465,7 @@ Feature: Redis Testing | standalone | | sentinel | + @redis-connection @redis-config @sync Scenario Outline: Retry, keepalive and client name settings reach the client Given a Redis config in mode with 3 retries, TCP keepalive, the client name "archipy-app" and the sentinel username "sentinel-user" When I build the Redis adapter from that config @@ -1412,6 +1477,7 @@ Feature: Redis Testing | standalone | | sentinel | + @redis-connection @redis-config @sync Scenario Outline: Database and health check interval reach the client Given a Redis config in mode with database 3 and a health check interval of 7 seconds When I build the Redis adapter from that config @@ -1422,11 +1488,13 @@ Feature: Redis Testing | standalone | | sentinel | + @redis-connection @redis-config @sync Scenario: Unset retry settings keep the redis-py defaults Given a Redis config in standalone mode with default resilience settings When I build the Redis adapter from that config Then the client connection should not carry a client name or extra retry errors + @redis-tls @redis-config @validation Scenario Outline: Invalid TLS settings are rejected When I create a Redis config with Then the Redis config should be rejected @@ -1436,6 +1504,7 @@ Feature: Redis Testing | a client certificate but no key | | a CA bundle while TLS is disabled | + @redis-keys @redis-hashes @redis-sets @sync Scenario Outline: Bytes keys, fields and members are stored as plain text Given a configured When I write bytes keys, fields and members tagged "{bdd-bytes}" in @@ -1447,6 +1516,7 @@ Feature: Redis Testing | container | | cluster | + @redis-keys @redis-hashes @redis-sets @async Scenario Outline: Async bytes keys, fields and members are stored as plain text Given a configured async When I write bytes keys, fields and members tagged "{bdd-bytes-a}" in async @@ -1458,32 +1528,42 @@ Feature: Redis Testing | container | | cluster | + @redis-connection @sync Scenario: Closing the sync adapter releases its client and search client Given a configured container When I use the container adapter as a context manager and create its search client Then the client pool and the search client pool should be closed + @redis-connection @async Scenario: Closing the async adapter releases its client and search client Given a configured async container When I use the async container adapter as a context manager and create its search client Then the async client pool and the search client pool should be closed + @redis-connection @async Scenario: Closing the async adapter directly uses the same method name as the sync adapter Given a configured async container When I close the async container adapter directly Then the async client pool and the search client pool should be closed + @redis-cluster Scenario Outline: The mock cluster uses the real CRC16 key slot When I ask the mock cluster for the slot of key "" using the client Then the mock cluster slot should be - Examples: Keys - | mode | key | slot | - | sync | foo | 12182 | - | sync | {foo}bar | 12182 | - | async | bar | 5061 | - | async | {bar}baz | 5061 | + @sync + Examples: Sync + | mode | key | slot | + | sync | foo | 12182 | + | sync | {foo}bar | 12182 | + + @async + Examples: Async + | mode | key | slot | + | async | bar | 5061 | + | async | {bar}baz | 5061 | + @redis-config @validation Scenario Outline: Invalid node addresses are rejected When I create a Redis config with the node "" Then the Redis config should be rejected @@ -1495,6 +1575,7 @@ Feature: Redis Testing | cluster | host:abc | | cluster | :7000 | + @redis-tls @redis-config @validation Scenario Outline: Credentials stay out of the config repr and risky TLS settings warn When I create a Redis config with the password "s3cr3t-pw" and Then the Redis config repr should not contain the password @@ -1505,12 +1586,14 @@ Feature: Redis Testing | TLS disabled | without SSL | | TLS enabled without hostname checks | TLS.CHECK_HOSTNAME | + @redis-hashes @redis-search @sync Scenario: Upserting a hash document preserves fields outside the update Given a configured container And search index "upsert-merge" exists with prefix "upm:" for HASH documents When I upsert a hash document "upm:1" twice with different fields Then the hash document "upm:1" contains both fields + @redis-errors @sync Scenario Outline: Server errors surface as CacheError and stay redis-py errors Given a configured When I increment the non-numeric key "{bdd-s-err}:k" in @@ -1522,6 +1605,7 @@ Feature: Redis Testing | container | | cluster | + @redis-errors @async Scenario Outline: Async server errors surface as CacheError and stay redis-py errors Given a configured async When I increment the non-numeric key "{bdd-a-err}:k" in async @@ -1533,14 +1617,17 @@ Feature: Redis Testing | container | | cluster | + @redis-connection @redis-errors @sync Scenario: Connection failures surface as CacheError When I read a key from an unreachable Redis server Then the Redis failure should be a CacheError and still a redis-py ConnectionError + @redis-connection @redis-errors @async Scenario: Async connection failures surface as CacheError When I read a key from an unreachable Redis server asynchronously Then the Redis failure should be a CacheError and still a redis-py ConnectionError + @redis-search @sync Scenario Outline: Untrusted text is matched literally by escaped queries Given a configured container And search index "" exists with prefix ":" for HASH documents @@ -1554,6 +1641,7 @@ Feature: Redis Testing | inj-text-bad | injbd | injbd:1 | from_text | foo) PIPE (* | 0 | | inj-hyb-bad | injhb | injhb:1 | quote_phrase | foo) PIPE (* | 0 | + @redis-search @validation Scenario Outline: Unsafe identifiers and directions are rejected by the search DTOs When I build the search DTO "" with the value "" Then the DTO outcome should be "" @@ -1571,3 +1659,223 @@ Feature: Redis Testing | sort_direction | DESC; DROP | rejected | | reduce_function | COUNT | accepted | | reduce_function | COUNT) x | rejected | + + @redis-lists @redis-sets + Scenario Outline: Move list batches and count set combinations + Given a configured + When I move a list batch and count overlapping sets through the Redis adapter + Then the batch move and set counts match the stored values + + @sync + Examples: Sync + | adapter | + | mock | + | container | + | cluster | + + @async + Examples: Async + | adapter | + | async mock | + | async container | + | async cluster | + + @redis-streams + Scenario Outline: Limit stream reads across the entire Redis reply + Given a configured + When I read a stream and a consumer group with total count and size limits + Then each stream limit returns the first entry only + + @sync + Examples: Sync + | adapter | + | container | + | cluster | + + @async + Examples: Async + | adapter | + | async container | + | async cluster | + + @redis-search @redis-search-aggregation @redis-search-aliases + Scenario Outline: List search aliases and collect grouped fields + Given a configured + When I alias a search index and collect the top values for one group + Then Redis lists the alias and returns the top values + + @sync + Examples: Sync + | adapter | + | container | + | cluster | + + @async + Examples: Async + | adapter | + | async container | + | async cluster | + + @redis-search @redis-search-aggregation @validation + Scenario: Unsupported search reducers fail validation + When I build a search aggregation with the unsupported reducer "MEDIAN" + Then the search aggregation is rejected + + @redis-connection @redis-sentinel @sync @async + Scenario: Closing a Sentinel adapter releases its discovery connections + When I use and close sync and async adapters through a real Redis Sentinel + Then the Sentinel discovery connections are released + + @redis-cluster @redis-connection @redis-protocol @redis-maintenance @async + Scenario: An asynchronous Redis client refreshes slots on a maintenance notification + When I migrate a cluster slot while an async RESP3 adapter is connected + Then the adapter learns the new owner and can read the migrated key + + @redis-sets @redis-member-expiration + Scenario Outline: Set and remove expiration on individual set members + Given a configured + When I exercise the Redis set member expiration commands + Then Redis reports each member's expiration and preserves the persistent members + + @sync + Examples: Sync + | adapter | + | container | + | cluster | + + @async + Examples: Async + | adapter | + | async container | + | async cluster | + + @redis-sorted-sets + Scenario Outline: Move sorted set members and preserve scores + Given a configured + When I move sorted set members by rank, score and name + Then all members arrive in the destination with their original scores + + @sync + Examples: Sync + | adapter | + | container | + | cluster | + + @async + Examples: Async + | adapter | + | async container | + | async cluster | + + @redis-bitmaps @redis-key-eviction @redis-connection @redis-sketches + Scenario Outline: Inspect bit positions, key flags, client records and sketch widths + Given a configured + When I inspect bit positions, eviction flags, client records and sketch counter widths + Then Redis returns the expected positions, flags, client and counter widths + + @sync + Examples: Sync + | adapter | + | container | + + @async + Examples: Async + | adapter | + | async container | + + @redis-search @redis-search-hybrid + Scenario Outline: Explain a hybrid search score + Given a configured + When I run a hybrid Redis search with score explanations + Then the hybrid hit includes a numeric score and its explanation + + @sync + Examples: Sync + | adapter | + | container | + + @async + Examples: Async + | adapter | + | async container | + + @redis-connection @redis-protocol @redis-retry @sync @async + Scenario: Negotiate RESP2 on a server without HELLO and fail fast on a missing socket + When I connect with RESP negotiation and check a missing Redis Unix socket + Then both Redis adapters fall back to RESP2 and reject the missing socket without backoff + + @redis-client-cache @sync + Scenario: Cache selected keys in both tracking modes and invalidate writes + Given a configured container + When I cache selected Redis reads with both tracking modes + Then tracking invalidates cached values and ineligible reads still reach Redis + + @redis-cluster @redis-routing + Scenario Outline: Route multi-key commands across cluster primaries + Given a configured + When I read and delete keys spanning two Redis shards + Then both shards contribute to the Redis command replies + + @sync + Examples: Sync + | adapter | + | cluster | + + @async + Examples: Async + | adapter | + | async cluster | + + @redis-backup + Scenario Outline: Seal or abort a node backup and clean up + Given a configured + When I start, seal, abort and clean up Redis backups + Then Redis reports one sealed backup followed by an aborted backup + + @sync + Examples: Sync + | adapter | + | container | + + @async + Examples: Async + | adapter | + | async container | + + @redis-cluster @redis-routing @redis-topology + Scenario Outline: Apply custom metadata and topology refresh settings in cluster mode + Given a configured + When I use custom command metadata and refresh pacing on Redis Cluster + Then the custom metadata keeps reads on the primary and the client uses the configured refresh interval + + @sync + Examples: Sync + | adapter | + | cluster | + + @async + Examples: Async + | adapter | + | async cluster | + + @redis-cluster @redis-pubsub @redis-sharded-pubsub + Scenario Outline: Deliver a message on a Redis shard channel + Given a configured + When I subscribe and publish on a Redis shard channel + Then the shard subscriber receives the message + + @sync + Examples: Sync + | adapter | + | cluster | + + @async + Examples: Async + | adapter | + | async cluster | + + @redis-connection @redis-reconnect @async + Scenario: Replace a server-closed async connection + Given a configured async container + When Redis closes the connection held by the async adapter + Then the adapter reconnects and reads the stored value diff --git a/features/redis_adapter_apm.feature b/features/redis_adapter_apm.feature index 751339f17..90b2f0617 100644 --- a/features/redis_adapter_apm.feature +++ b/features/redis_adapter_apm.feature @@ -1,4 +1,4 @@ -@needs-redis @needs-redis-cluster @needs-apm-server @needs-apm-collector +@redis @redis-observability @redis-apm @needs-redis @needs-redis-cluster @needs-apm-server @needs-apm-collector Feature: Redis Testing with Elastic APM As a developer I want to test Redis operations with both mocks and real containers @@ -7,6 +7,7 @@ Feature: Redis Testing with Elastic APM Background: Given test entities are defined + @sync Scenario Outline: Redis adapter spans reach Elastic APM Server Given adapter spans are exported to Elastic APM Server When I set and get a key through the Redis adapter diff --git a/features/steps/redis_capability_steps.py b/features/steps/redis_capability_steps.py new file mode 100644 index 000000000..f88fcf7b2 --- /dev/null +++ b/features/steps/redis_capability_steps.py @@ -0,0 +1,660 @@ +"""Behavior of the Redis adapters' newer Redis command and connection capabilities.""" + +import asyncio +import inspect +import socket +import struct +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from time import monotonic +from uuid import uuid4 + +from behave import then, use_step_matcher, when +from pydantic import ValidationError +from redis import Redis +from redis.cache import CacheConfig, TrackingMode +from redis.commands.metadata import ( + AsyncDynamicMetadataResolver, + AsyncStaticMetadataResolver, + DynamicMetadataResolver, + StaticMetadataResolver, +) +from redis.commands.search.hybrid_query import HybridQuery, HybridSearchQuery, HybridVsimQuery, VectorSearchMethods +from redis.exceptions import ConnectionError as RedisConnectionError +from testcontainers.core.container import DockerContainer +from testcontainers.core.wait_strategies import LogMessageWaitStrategy + +from archipy.adapters.redis.adapters import AsyncRedisAdapter, RedisAdapter +from archipy.configs.base_config import BaseConfig +from archipy.configs.sections.redis import RedisConfig, RedisMode +from archipy.models.dtos.redis.search.aggregation_dto import AggregationDTO +from archipy.models.dtos.redis.search.index_schema_dto import ( + IndexSchemaDTO, + NumericFieldConfig, + TagFieldConfig, + TextFieldConfig, + VectorFieldConfig, +) +from archipy.models.errors import CacheError +from features.test_containers import ContainerManager +from features.test_helpers import get_current_scenario_context + +use_step_matcher("re") + + +async def _call(method, *args, **kwargs): + result = method(*args, **kwargs) + if inspect.isawaitable(result): + return await result + return result + + +def _run(context, exercise): + scenario = get_current_scenario_context(context) + + async def run(): + adapter = scenario.async_adapter or scenario.adapter + try: + return await exercise(adapter, uuid4().hex) + finally: + if scenario.async_adapter is not None: + await scenario.async_adapter.close() + scenario.async_adapter = None + + scenario.store("redis_capability", asyncio.run(run())) + + +def _result(context): + return get_current_scenario_context(context).get("redis_capability") + + +@when("I exercise the Redis set member expiration commands") +def exercise_member_expiration(context): + async def exercise(adapter, key): + expiration = int((datetime.now(UTC) + timedelta(minutes=5)).timestamp()) + added = await _call(adapter.saddex, key, "first", "second", ex=60) + seconds = await _call(adapter.sexpire, key, 70, "first", "missing") + milliseconds = await _call(adapter.spexpire, key, 80_000, "second", gt=True) + ttl_first, ttl_second, ttl_missing = await _call(adapter.sttl, key, "first", "second", "missing") + (pttl_second,) = await _call(adapter.spttl, key, "second") + expireat = await _call(adapter.sexpireat, key, expiration, "first", xx=True) + pexpireat = await _call(adapter.spexpireat, key, expiration * 1000 + 37, "second", xx=True) + deadlines = await _call(adapter.sexpiretime, key, "first", "second") + millisecond_deadlines = await _call(adapter.spexpiretime, key, "first", "second") + persisted = await _call(adapter.spersist, key, "first", "second", "missing") + remaining = await _call(adapter.sttl, key, "first", "second", "missing") + return ( + added, + seconds, + milliseconds, + 0 < ttl_first <= 70, + 0 < ttl_second <= 80, + ttl_missing, + 0 < pttl_second <= 80_000, + expireat, + pexpireat, + deadlines == [expiration, expiration + 1], + millisecond_deadlines == [expiration * 1000, expiration * 1000 + 37], + persisted, + remaining, + ) + + _run(context, exercise) + + +@then("Redis reports each member's expiration and preserves the persistent members") +def verify_member_expiration(context): + result = _result(context) + assert result == (1, [1, -2], [1], True, True, -2, True, [1], [1], True, True, [1, 1, -2], [-1, -1, -2]), result + + +@when("I move sorted set members by rank, score and name") +def exercise_sorted_set_moves(context): + async def exercise(adapter, token): + source, destination = f"{{{token}}}:source", f"{{{token}}}:destination" + await _call(adapter.zadd, source, {"a": 1, "b": 2, "c": 3, "d": 4}) + first = await _call(adapter.zmove, source, destination, lowest=True) + second = await _call(adapter.zmove, source, destination, byscore=(2, 2)) + third = await _call(adapter.bzmove, source, destination, 0.2, highest=True) + fourth = await _call(adapter.zmovemember, source, destination, "c", nx=True) + empty = await _call(adapter.zmove, source, destination, lowest=True) + return first, second, third, fourth, empty, await _call(adapter.zcard, destination) + + _run(context, exercise) + + +@then("all members arrive in the destination with their original scores") +def verify_sorted_set_moves(context): + result = _result(context) + assert result == ([["a", 1.0]], [["b", 2.0]], [["d", 4.0]], [["c", 3.0]], None, 4), result + + +@when("I inspect bit positions, eviction flags, client records and sketch counter widths") +def inspect_data_and_clients(context): + async def exercise(adapter, token): + key = f"{token}:key" + await _call(adapter.set, key, "A") + ones = await _call(adapter.bitrangeintarray, key, 0, 7, mode="BIT") + zeros = await _call(adapter.bitrangeintarray, key, 0, 7, mode="BIT", limit=2, zeros=True) + blessed = await _call(adapter.bless_set, key, "NO-EVICT") + flags = await _call(adapter.bless_get, key) + cursor, keys = await _call(adapter.bless_scan, 0, "NO-EVICT") + seen = key in keys + while cursor and not seen: + cursor, keys = await _call(adapter.bless_scan, cursor, "NO-EVICT") + seen = key in keys + cleared = await _call(adapter.bless_clear, key, "NO-EVICT") + client_id = await _call(adapter.client.client_id) + clients = list(await _call(adapter.client_list_iter, client_ids=[client_id])) + dim_key, prob_key = f"{token}:dim", f"{token}:prob" + assert await _call(adapter.cms_initbydim, dim_key, 12, 5, cell_size=1) + assert await _call(adapter.cms_initbyprob, prob_key, 0.01, 0.05, cell_size=2) + dim = await _call(adapter.client.cms().incrby, dim_key, ["item"], [255]) + prob = await _call(adapter.client.cms().incrby, prob_key, ["item"], [256]) + await _call(adapter.client.cms().incrby, dim_key, ["item"], [1]) + assert await _call(adapter.client.cms().query, dim_key, "item") == [255] + return ( + ones, + zeros, + blessed, + flags, + seen, + cleared, + [client["id"] for client in clients], + str(client_id), + dim, + prob, + ) + + _run(context, exercise) + + +@then("Redis returns the expected positions, flags, client and counter widths") +def verify_data_and_clients(context): + result = _result(context) + assert result[:6] == ([1, 7], [0, 2], 1, ["NO-EVICT"], True, 1), result + assert result[6] == [result[7]], result + assert result[8:] == ([255], [256]), result + + +@when("I run a hybrid Redis search with score explanations") +def explain_hybrid_search(context): + async def exercise(adapter, token): + vector = struct.pack("<2f", 1, 0) + handle = adapter.search_index(token) + schema = IndexSchemaDTO(fields=[TextFieldConfig(name="title"), VectorFieldConfig(name="vector", dim=2)]) + prefix = f"{token}:" + assert await _call(handle.create_index, schema, prefix) + try: + assert await _call(handle.upsert_hash, prefix + "doc", {"title": "Redis database", "vector": vector}) + deadline = monotonic() + 3 + while True: + index_info = await _call(handle.info) + if int(index_info["num_docs"]) == 1 and not int(index_info["indexing"]): + break + assert monotonic() < deadline, index_info + query = HybridQuery( + HybridSearchQuery("redis"), + HybridVsimQuery("@vector", "$vector", VectorSearchMethods.KNN, {"K": 1}), + ) + return await _call(handle.hybrid_search, query, params_substitution={"vector": vector}, explain_score=True) + finally: + await _call(handle.drop_index, delete_documents=True) + + _run(context, exercise) + + +@then("the hybrid hit includes a numeric score and its explanation") +def verify_hybrid_search(context): + result = _result(context) + assert result.total_results == 1, result + score, explanation = result.results[0]["score"] + assert isinstance(score, float) and explanation, result + + +@when("I cache selected Redis reads with both tracking modes") +def exercise_client_cache(context): + async def exercise(adapter, token): + config = adapter._configs + cache_key, other_key = f"{token}:cached", f"{token}:uncached" + readings = [] + with Redis(host=config.MASTER_HOST, port=config.PORT, decode_responses=True) as writer: + for mode in (TrackingMode.OPTIN, TrackingMode.OPTOUT): + + def predicate(command, keys): + return command == "GET" and keys == (cache_key,) + + with RedisAdapter( + config, cache_config=CacheConfig(tracking_mode=mode, cache_predicate=predicate), + ) as cached: + writer.mset({cache_key: "first", other_key: "other"}) + before = writer.info("commandstats").get("cmdstat_get", {}).get("calls", 0) + assert [cached.get(cache_key) for _ in range(2)] == ["first", "first"] + assert [cached.get(other_key) for _ in range(2)] == ["other", "other"] + calls = writer.info("commandstats")["cmdstat_get"]["calls"] - before + writer.set(cache_key, "second") + readings.append((calls, cached.get(cache_key))) + + return readings + + _run(context, exercise) + + +@then("tracking invalidates cached values and ineligible reads still reach Redis") +def verify_client_cache(context): + assert _result(context) == [(3, "second"), (3, "second")], _result(context) + + +@when("I read and delete keys spanning two Redis shards") +def exercise_cluster_routing(context): + async def exercise(adapter, token): + first = f"{token}:0" + await _call(adapter.ping) + first_node = adapter.client.get_node_from_key(first) + second = next( + key for i in range(1, 50) if adapter.client.get_node_from_key(key := f"{token}:{i}") != first_node + ) + await _call(adapter.set, first, "first") + await _call(adapter.set, second, "second") + pipeline = await _call(adapter.get_pipeline, transaction=False) + pipeline.touch(first) + pipeline.touch(second) + touched = await _call(pipeline.execute) + removed = await _call(adapter.delete, first, second, f"{token}:missing") + return touched, removed, await _call(adapter.exists, first, second) + + _run(context, exercise) + + +@then("both shards contribute to the Redis command replies") +def verify_cluster_routing(context): + assert _result(context) == ([1, 1], 2, 0), _result(context) + + +@when("I connect with RESP negotiation and check a missing Redis Unix socket") +def exercise_connection_resilience(context): + image = BaseConfig.global_config().REDIS__IMAGE + container = ( + DockerContainer(image) + .with_exposed_ports(6379) + .with_command(["redis-server", "--save", "", "--rename-command", "HELLO", ""]) + .waiting_for(LogMessageWaitStrategy("Ready to accept connections tcp")) + ) + scenario = get_current_scenario_context(context) + missing = RedisConfig( + UNIX_SOCKET_PATH=f"/tmp/redis-{uuid4().hex}.sock", + RETRY={"ATTEMPTS": 4, "BACKOFF_BASE": 1.0, "BACKOFF_CAP": 1.0, "FAIL_FAST_MISSING_SOCKET": True}, + ) + with container: + negotiated = RedisConfig( + MASTER_HOST=container.get_container_host_ip(), + PORT=int(container.get_exposed_port(6379)), + PROTOCOL=None, + ) + + async def check(adapter, unreachable): + assert await _call(adapter.set, "fallback", "resp2") + assert await _call(adapter.get, "fallback") == "resp2" + start = monotonic() + try: + await _call(unreachable.ping) + except (RedisConnectionError, CacheError) as error: + return "No such file" in str(error) and monotonic() - start < 1 + raise AssertionError("Missing Unix socket unexpectedly answered") + + async def check_async(): + async with AsyncRedisAdapter(negotiated) as adapter, AsyncRedisAdapter(missing) as unreachable: + return await check(adapter, unreachable) + + with RedisAdapter(negotiated) as adapter, RedisAdapter(missing) as unreachable: + sync_result = asyncio.run(check(adapter, unreachable)) + scenario.store("redis_capability", (sync_result, asyncio.run(check_async()))) + + +@then("both Redis adapters fall back to RESP2 and reject the missing socket without backoff") +def verify_connection_resilience(context): + assert _result(context) == (True, True), _result(context) + + +@when("I start, seal, abort and clean up Redis backups") +def exercise_backup(context): + async def exercise(adapter, token): + await _call(adapter.set, token, "backed up") + assert await _call(adapter.backup_start) == "OK" + deadline = monotonic() + 3 + while (await _call(adapter.backup_status))["state"] in {"pending", "snapshotting"}: + assert monotonic() < deadline, "Redis did not finish the backup snapshot" + assert await _call(adapter.backup_seal) == "OK" + status = await _call(adapter.backup_status) + artifacts = await _call(adapter.backup_list) + assert await _call(adapter.backup_cleanup) == "OK" + assert await _call(adapter.backup_start) == "OK" + assert await _call(adapter.backup_abort) == "OK" + aborted = await _call(adapter.backup_status) + assert await _call(adapter.backup_cleanup) == "OK" + return status["state"], bool(artifacts), aborted["state"], aborted["error"] + + _run(context, exercise) + + +@then("Redis reports one sealed backup followed by an aborted backup") +def verify_backup(context): + assert _result(context) == ("sealed", True, "failed", "aborted by user"), _result(context) + + +@when("I use custom command metadata and refresh pacing on Redis Cluster") +def exercise_cluster_metadata(context): + async def exercise(adapter, key): + config = adapter._configs + config = config.model_copy( + update={ + "CLUSTER": config.CLUSTER.model_copy( + update={"TOPOLOGY_REFRESH_MIN_INTERVAL": 0.25, "READ_FROM_REPLICAS": True}, + ), + }, + ) + fallback = StaticMetadataResolver() + get_metadata = fallback.resolve("GET") + assert get_metadata is not None + metadata = {"core": {"get": replace(get_metadata, is_readonly=False)}} + + async def check(configured): + await _call(configured.set, key, "primary") + replica = configured.client.get_node_from_key(key, replica=True) + assert replica is not None + with Redis(host=replica.host, port=replica.port) as reader: + before = reader.info("commandstats").get("cmdstat_get", {}).get("calls", 0) + values = [await _call(configured.get, key) for _ in range(4)] + after = reader.info("commandstats").get("cmdstat_get", {}).get("calls", 0) + return values, after - before, configured.client.nodes_manager._topology_refresh_min_interval + + if isinstance(adapter, AsyncRedisAdapter): + async with AsyncRedisAdapter( + config, metadata_resolver=AsyncDynamicMetadataResolver(metadata, AsyncStaticMetadataResolver()), + ) as configured: + return await check(configured) + with RedisAdapter(config, metadata_resolver=DynamicMetadataResolver(metadata, fallback)) as configured: + return await check(configured) + + _run(context, exercise) + + +@then("the custom metadata keeps reads on the primary and the client uses the configured refresh interval") +def verify_cluster_metadata(context): + assert _result(context) == (["primary"] * 4, 0, 0.25), _result(context) + + +@when("I subscribe and publish on a Redis shard channel") +def exercise_sharded_pubsub(context): + async def exercise(adapter, channel): + subscriber = await _call(adapter.pubsub) + try: + await _call(subscriber.ssubscribe, channel) + confirmation = await _call(subscriber.get_sharded_message, timeout=2) + assert confirmation is not None and confirmation["type"] == "ssubscribe", confirmation + receivers = await _call(adapter.spublish, channel, "message") + message = await _call(subscriber.get_sharded_message, timeout=2) + return receivers, message + finally: + await _call(subscriber.close) + + _run(context, exercise) + + +@then("the shard subscriber receives the message") +def verify_sharded_pubsub(context): + receivers, message = _result(context) + assert receivers == 1 and message is not None, (receivers, message) + assert message["type"] == "smessage" and message["data"] == "message", message + + +@when("Redis closes the connection held by the async adapter") +def exercise_server_disconnect(context): + async def exercise(adapter, key): + await adapter.set(key, "still present") + original_id = await adapter.client.client_id() + config = adapter._configs + with Redis(host=config.MASTER_HOST, port=config.PORT) as observer: + assert observer.client_kill_filter(_id=original_id) == 1 + value = await adapter.get(key) + return value, original_id != await adapter.client.client_id() + + _run(context, exercise) + + +@then("the adapter reconnects and reads the stored value") +def verify_server_disconnect(context): + assert _result(context) == ("still present", True), _result(context) + + +@when("I move a list batch and count overlapping sets through the Redis adapter") +def move_batch_and_count_sets(context): + async def exercise(adapter, token): + source, destination = f"{{{token}}}:source", f"{{{token}}}:destination" + await _call(adapter.rpush, source, "one", "two", "three") + moved = await _call(adapter.lmovem, source, destination, count=2, ordering="BULK") + blocked_move = await _call(adapter.blmovem, source, destination, timeout_seconds=0.2) + missing = await _call(adapter.blmovem, source, destination, timeout_seconds=0.01) + a, b = f"{{{token}}}:a", f"{{{token}}}:b" + await _call(adapter.sadd, a, "first", "shared") + await _call(adapter.sadd, b, "shared", "last") + diff = await _call(adapter.sdiffcard, [a, b]) + union = await _call(adapter.sunioncard, [a, b]) + limited_union = await _call(adapter.sunioncard, [a, b], limit=2) + return moved, blocked_move, missing, diff, union, limited_union + + _run(context, exercise) + + +@then("the batch move and set counts match the stored values") +def verify_batch_and_sets(context): + result = _result(context) + assert result == (["one", "two"], ["three"], None, 1, 3, 2), result + + +def _stream_ids(reply): + streams = ( + (entries[0] for entries in reply.values()) if isinstance(reply, dict) else (entries for _, entries in reply) + ) + return [entry_id for entries in streams for entry_id, _ in entries] + + +@when("I read a stream and a consumer group with total count and size limits") +def read_limited_streams(context): + async def exercise(adapter, token): + a, b = f"{{{token}}}:a", f"{{{token}}}:b" + for key, entry_id in ((a, "1-0"), (b, "2-0")): + await _call(adapter.client.xadd, key, {"value": "sample"}, id=entry_id) + await _call(adapter.client.xgroup_create, key, "count", id="0") + await _call(adapter.client.xgroup_create, key, "size", id="0") + positions = {a: "0", b: "0"} + group_positions = {a: ">", b: ">"} + replies = [ + await _call(adapter.xread, positions, max_count=1), + await _call(adapter.xread, positions, max_size=1), + await _call(adapter.xreadgroup, "count", "reader", group_positions, max_count=1), + await _call(adapter.xreadgroup, "size", "reader", group_positions, max_size=1), + ] + return [_stream_ids(reply) for reply in replies] + + _run(context, exercise) + + +@then("each stream limit returns the first entry only") +def verify_stream_limits(context): + result = _result(context) + assert result == [["1-0"]] * 4, result + + +@when("I alias a search index and collect the top values for one group") +def alias_and_collect(context): + async def exercise(adapter, token): + prefix = f"{{{token}}}:doc:" + handle = adapter.search_index(token) + schema = IndexSchemaDTO( + fields=[ + TagFieldConfig(name="kind"), + TextFieldConfig(name="value"), + NumericFieldConfig(name="rank"), + ], + ) + values = ("article", "audiobook", "video") + for rank, value in enumerate(values): + assert await _call(handle.upsert_hash, prefix + str(rank), {"kind": "book", "value": value, "rank": rank}) + assert await _call(handle.create_index, schema, prefix) + try: + deadline = monotonic() + 3 + while True: + index_info = await _call(handle.info) + if int(index_info["num_docs"]) == len(values) and not int(index_info["indexing"]): + break + assert monotonic() < deadline, index_info + alias = f"alias-{token}" + assert await _call(handle.add_alias, alias) + aliases = await _call(handle.list_aliases) + result = await _call( + handle.aggregate, + AggregationDTO( + group_by=["kind"], + reduce_field="entries", + reduce_function="COLLECT", + collect_fields=["value", "rank"], + collect_sort_by="rank", + collect_sort_direction="DESC", + collect_limit=(0, 2), + ), + ) + return alias in aliases, result + finally: + await _call(handle.drop_index, delete_documents=True) + + _run(context, exercise) + + +@then("Redis lists the alias and returns the top values") +def verify_alias_and_collection(context): + found, result = _result(context) + assert found + assert result["total"] == 1, result + (row,) = result["rows"] + attributes = row.get(b"extra_attributes", row) + entries = attributes[b"entries"] + assert [(entry[b"value"], int(entry[b"rank"])) for entry in entries] == [(b"video", 2), (b"audiobook", 1)], result + + +@when(r'I build a search aggregation with the unsupported reducer "(?P[^"]+)"') +def build_unsupported_reducer(context, reducer): + try: + AggregationDTO(group_by=["kind"], reduce_function=reducer) + except ValidationError as error: + get_current_scenario_context(context).store("redis_capability", error.errors()[0]["loc"]) + + +@then("the search aggregation is rejected") +def verify_unsupported_reducer(context): + assert _result(context) == ("reduce_function",) + + +@when("I use and close sync and async adapters through a real Redis Sentinel") +def use_and_close_sentinel(context): + # Reserve two distinct TCP ports before starting Redis and Sentinel on the host network. + with socket.socket() as primary, socket.socket() as monitor: + primary.bind(("127.0.0.1", 0)) + monitor.bind(("127.0.0.1", 0)) + primary_port = primary.getsockname()[1] + sentinel_port = monitor.getsockname()[1] + command = [ + "sh", + "-ec", + f"redis-server --bind 127.0.0.1 --port {primary_port} --daemonize yes\n" + f"printf '%s\\n' 'bind 127.0.0.1' 'port {sentinel_port}' " + f"'sentinel monitor archipy 127.0.0.1 {primary_port} 1' > /tmp/archipy-sentinel.conf\n" + "exec redis-server /tmp/archipy-sentinel.conf --sentinel", + ] + config = RedisConfig( + MODE=RedisMode.SENTINEL, + SENTINEL={"NODES": [f"127.0.0.1:{sentinel_port}"], "SERVICE_NAME": "archipy", "SOCKET_TIMEOUT": 2}, + ) + image = BaseConfig.global_config().REDIS__IMAGE + container = ( + DockerContainer(image) + .with_kwargs(network_mode="host") + .with_command(command) + .waiting_for(LogMessageWaitStrategy("\\+monitor master archipy")) + ) + with container, Redis(host="127.0.0.1", port=sentinel_port, socket_timeout=2) as observer: + initial = len(observer.client_list()) + with RedisAdapter(config) as adapter: + adapter.set("redis_capability:sentinel", "present") + assert adapter.get("redis_capability:sentinel") == "present" + sync_during = len(observer.client_list()) + sync_after = len(observer.client_list()) + + async def check_async_sentinel(): + async with AsyncRedisAdapter(config) as adapter: + assert await adapter.get("redis_capability:sentinel") == "present" + return len(observer.client_list()) + + async_during = asyncio.run(check_async_sentinel()) + async_after = len(observer.client_list()) + get_current_scenario_context(context).store( + "sentinel_clients", (initial, sync_during, sync_after, async_during, async_after), + ) + + +@then("the Sentinel discovery connections are released") +def check_sentinel_clients(context): + counts = get_current_scenario_context(context).get("sentinel_clients") + initial, sync_during, sync_after, async_during, async_after = counts + assert sync_during > initial and async_during > initial, counts + assert sync_after == async_after == initial, counts + + +async def _migrate_and_wait_for_notification(client, key, slot, source, destination): + # PING targets the pre-existing connection. A key command could refresh slots via MOVED + # and pass this check even if the client never processed the maintenance notification. + await client.execute_command("PING", target_nodes=source) + await client.execute_command("CLUSTER MIGRATION IMPORT", slot, slot, target_nodes=destination) + async with asyncio.timeout(5): + while client.get_node_from_key(key) != destination: + await client.execute_command("PING", target_nodes=source) + + +@when("I migrate a cluster slot while an async RESP3 adapter is connected") +def migrate_redis_slot(context): + cluster = ContainerManager.get_container("redis-cluster") + + async def exercise(): + config = cluster.cluster_config.model_copy(deep=True) + config.CLUSTER.READ_FROM_REPLICAS = False + async with AsyncRedisAdapter(config) as adapter: + key = f"redis_capability:migration:{uuid4().hex}" + client = adapter.client + await client.initialize() + slot = client.keyslot(key) + source = client.get_node_from_key(key) + help_text = await client.execute_command("CLIENT HELP", target_nodes=source) + if not any("MAINT_NOTIFICATIONS" in line for line in help_text): + return None + await adapter.set(key, "migrated") + destination = next(node for node in client.get_primaries() if node != source) + try: + await _migrate_and_wait_for_notification(client, key, slot, source, destination) + value = await adapter.get(key) + finally: + owner = client.get_node_from_key(key) + if owner == destination: + await _migrate_and_wait_for_notification(client, key, slot, destination, source) + await adapter.delete(key) + return value + + value = asyncio.run(exercise()) + if value is None: + context.scenario.skip("The Redis fixture does not implement CLIENT MAINT_NOTIFICATIONS") + else: + get_current_scenario_context(context).store("redis_capability", value) + + +@then("the adapter learns the new owner and can read the migrated key") +def verify_migrated_key(context): + assert _result(context) == "migrated" diff --git a/features/test_containers.py b/features/test_containers.py index 544acbb29..08f70f93a 100644 --- a/features/test_containers.py +++ b/features/test_containers.py @@ -386,7 +386,8 @@ def stop(self) -> None: def _build_redis_cluster_node(image: str, port: int) -> DockerContainer: """Build a Redis cluster node container using host networking.""" command = ( - f"redis-server --port {port} --cluster-enabled yes " + f"redis-server --bind 127.0.0.1 --port {port} --cluster-enabled yes " + "--cluster-bus-port-protected-mode no " f"--cluster-config-file nodes.conf --cluster-node-timeout 5000 " f"--cluster-announce-ip 127.0.0.1 --appendonly no" ) diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py b/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py index fd6a3b9ec..90772ee19 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py @@ -36,6 +36,7 @@ AsyncRedisSortedSetsMixin, RedisSortedSetsMixin, ) +from archipy.adapters.redis.adapter_mixins.streams import AsyncRedisStreamsMixin, RedisStreamsMixin __all__ = [ "AsyncRedisArraysMixin", @@ -47,6 +48,7 @@ "AsyncRedisPubSubMixin", "AsyncRedisSetsMixin", "AsyncRedisSortedSetsMixin", + "AsyncRedisStreamsMixin", "RedisArraysMixin", "RedisClusterMixin", "RedisConnectionMixin", @@ -56,4 +58,5 @@ "RedisPubSubMixin", "RedisSetsMixin", "RedisSortedSetsMixin", + "RedisStreamsMixin", ] diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py b/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py index 68272b14a..8957194dc 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py @@ -8,7 +8,7 @@ from redis.asyncio.retry import Retry as AsyncRetry from redis.backoff import ExponentialBackoff from redis.exceptions import TimeoutError as RedisTimeoutError -from redis.retry import Retry +from redis.retry import Retry, is_retryable_connect_error if TYPE_CHECKING: from redis import RedisCluster @@ -94,10 +94,12 @@ def _tls_acl_kwargs(configs: RedisConfig) -> dict[str, Any]: def _resilience_kwargs(configs: RedisConfig, *, is_async: bool = False) -> dict[str, Any]: """Build retry, keepalive and client-name kwargs; empty when none is configured.""" kwargs: dict[str, Any] = {} - if configs.RETRY.ATTEMPTS is not None: + if configs.RETRY.ATTEMPTS is not None or configs.RETRY.FAIL_FAST_MISSING_SOCKET: backoff = ExponentialBackoff(cap=configs.RETRY.BACKOFF_CAP, base=configs.RETRY.BACKOFF_BASE) retry_class = AsyncRetry if is_async else Retry - kwargs["retry"] = retry_class(backoff, configs.RETRY.ATTEMPTS) + attempts = configs.RETRY.ATTEMPTS if configs.RETRY.ATTEMPTS is not None else 3 + checker = is_retryable_connect_error if configs.RETRY.FAIL_FAST_MISSING_SOCKET else None + kwargs["retry"] = retry_class(backoff, attempts, is_retryable=checker) if configs.RETRY.ON_TIMEOUT: kwargs["retry_on_error"] = [RedisTimeoutError] if configs.SOCKET_KEEPALIVE is not None: diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py b/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py index c432a2dd4..0f5b5cecd 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py @@ -4,7 +4,7 @@ __lazy_modules__ = ["archipy.configs.base_config"] -from collections.abc import Awaitable, Iterable +from collections.abc import Awaitable, Iterable, Iterator, Sequence from typing import TYPE_CHECKING, Any, Self from redis import RedisCluster, Sentinel @@ -17,6 +17,7 @@ ) from redis.client import Pipeline, Redis from redis.cluster import ClusterNode, LoadBalancingStrategy +from redis.utils import check_protocol_version from archipy.adapters.redis.adapter_mixins._shared import ( AsyncRedisMixinBase, @@ -42,6 +43,10 @@ ) if TYPE_CHECKING: + from redis.cache import CacheConfig + from redis.commands.metadata import AsyncMetadataResolver, MetadataResolver + from redis.typing import EncodableT, KeyT + from archipy.adapters.redis.search_ports import ( AsyncRedisSearchHandlePort, RedisSearchHandlePort, @@ -51,15 +56,69 @@ class RedisConnectionMixin(SyncRedisMixinBase): """Sync Redis mixin for connection operations.""" - def __init__(self, redis_config: RedisConfig | None = None) -> None: + def client_list_iter( + self, client_type: str | None = None, *, client_ids: Sequence[EncodableT] = () + ) -> Iterator[dict[str, str]]: + """Iterate over parsed records from the server's client list.""" + return self.client.client_list_iter(_type=client_type, client_id=list(client_ids)) + + def backup_start(self) -> bytes | str: + """Start a coordinated backup on the server.""" + return self.client.backup_start() + + def backup_status(self) -> dict[str | bytes, Any]: + """Return the server's current backup status.""" + return self.client.backup_status() + + def backup_list(self) -> list[bytes | str]: + """List files generated for the active backup.""" + return self.client.backup_list() + + def backup_seal(self) -> bytes | str: + """Seal the backup so its files can be copied.""" + return self.client.backup_seal() + + def backup_abort(self) -> bytes | str: + """Abort the active backup.""" + return self.client.backup_abort() + + def backup_cleanup(self) -> bytes | str: + """Remove temporary artifacts of the last backup.""" + return self.client.backup_cleanup() + + def cms_initbydim(self, key: KeyT, width: int, depth: int, *, cell_size: int | None = None) -> bool: + """Create a Count-Min Sketch with fixed dimensions and optional counter width.""" + return self.client.cms().initbydim(key, width, depth, cell_size=cell_size) + + def cms_initbyprob(self, key: KeyT, error: float, probability: float, *, cell_size: int | None = None) -> bool: + """Create a Count-Min Sketch sized by error bounds and optional counter width.""" + return self.client.cms().initbyprob(key, error, probability, cell_size=cell_size) + + _sentinel: Sentinel | None = None + + def __init__( + self, + redis_config: RedisConfig | None = None, + *, + cache_config: CacheConfig | None = None, + metadata_resolver: MetadataResolver | None = None, + ) -> None: """Initialize the RedisAdapter with configuration settings. Args: redis_config (RedisConfig, optional): Configuration settings for Redis. If None, retrieves from global config. Defaults to None. + cache_config: Client-side cache settings for standalone or cluster mode. Requires RESP3. + metadata_resolver: Optional command metadata for cached reads and cluster routing. """ configs: RedisConfig = redis_config or BaseConfig.global_config().REDIS + if configs.MODE == RedisMode.SENTINEL and (cache_config is not None or metadata_resolver is not None): + raise ConfigurationError(operation="redis_connect", reason="sentinel_cache_or_metadata_unsupported") + if cache_config is not None and (configs.PROTOCOL is None or not check_protocol_version(configs.PROTOCOL, 3)): + raise ConfigurationError(operation="redis_connect", reason="client_side_cache_requires_explicit_resp3") self._configs = configs + self._cache_config = cache_config + self._metadata_resolver = metadata_resolver self._search_client: Redis | RedisCluster | None = None self._set_clients(configs) @@ -89,7 +148,7 @@ def _set_standalone_clients(self, configs: RedisConfig) -> None: Args: configs (RedisConfig): Configuration settings for Redis. """ - if redis_master_host := configs.MASTER_HOST: + if redis_master_host := configs.MASTER_HOST or configs.UNIX_SOCKET_PATH: self.client: Redis | RedisCluster = self._get_client(redis_master_host, configs) if redis_slave_host := configs.SLAVE_HOST: self.read_only_client: Redis | RedisCluster = self._get_client(redis_slave_host, configs) @@ -124,6 +183,9 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: health_check_interval=configs.HEALTH_CHECK_INTERVAL, require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, + topology_refresh_min_interval=configs.CLUSTER.TOPOLOGY_REFRESH_MIN_INTERVAL, + cache_config=self._cache_config, + metadata_resolver=self._metadata_resolver, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=False), **cluster_kwargs, @@ -151,18 +213,18 @@ def _set_sentinel_clients(self, configs: RedisConfig) -> None: sentinel_kwargs=_sentinel_kwargs(configs), ) + self._sentinel = sentinel_connection self.client = sentinel_connection.master_for( sentinel_service_name, **_sentinel_redis_kwargs(configs, is_async=False), ) - self.read_only_client = sentinel_connection.slave_for( + self.read_only_client = sentinel_connection.replica_for( sentinel_service_name, **_sentinel_redis_kwargs(configs, is_async=False), ) - @staticmethod - def _get_client(host: str, configs: RedisConfig, *, decode_responses: bool | None = None) -> Redis: + def _get_client(self, host: str, configs: RedisConfig, *, decode_responses: bool | None = None) -> Redis: """Create a Redis client with the specified configuration. Args: @@ -177,6 +239,9 @@ def _get_client(host: str, configs: RedisConfig, *, decode_responses: bool | Non host=host, port=configs.PORT, db=configs.DATABASE, + unix_socket_path=configs.UNIX_SOCKET_PATH, + cache_config=self._cache_config if decode_responses is not False else None, + metadata_resolver=self._metadata_resolver if decode_responses is not False else None, **_redis_connection_kwargs(configs, decode_responses=decode_responses, is_async=False), ) @@ -210,6 +275,8 @@ def _build_binary_client(self, configs: RedisConfig) -> Redis | RedisCluster: health_check_interval=configs.HEALTH_CHECK_INTERVAL, require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, + topology_refresh_min_interval=configs.CLUSTER.TOPOLOGY_REFRESH_MIN_INTERVAL, + metadata_resolver=self._metadata_resolver, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=False), **cluster_kwargs, @@ -270,6 +337,8 @@ def close(self) -> None: client.close() if not isinstance(client, RedisCluster): client.connection_pool.disconnect() + if self._sentinel is not None: + self._sentinel.close() self._search_client = None def __enter__(self) -> Self: @@ -329,15 +398,66 @@ def config_get(self, pattern: str = "*") -> dict[str, str]: class AsyncRedisConnectionMixin(AsyncRedisMixinBase): """Async Redis mixin for connection operations.""" - def __init__(self, redis_config: RedisConfig | None = None) -> None: + async def client_list_iter( + self, client_type: str | None = None, *, client_ids: Sequence[EncodableT] = () + ) -> Iterator[dict[str, str]]: + """Iterate over parsed records from the server's client list.""" + return await self.client.client_list_iter(_type=client_type, client_id=list(client_ids)) + + async def backup_start(self) -> bytes | str: + """Start a coordinated backup on the server.""" + return await self.client.backup_start() + + async def backup_status(self) -> dict[str | bytes, Any]: + """Return the server's current backup status.""" + return await self.client.backup_status() + + async def backup_list(self) -> list[bytes | str]: + """List files generated for the active backup.""" + return await self.client.backup_list() + + async def backup_seal(self) -> bytes | str: + """Seal the backup so its files can be copied.""" + return await self.client.backup_seal() + + async def backup_abort(self) -> bytes | str: + """Abort the active backup.""" + return await self.client.backup_abort() + + async def backup_cleanup(self) -> bytes | str: + """Remove temporary artifacts of the last backup.""" + return await self.client.backup_cleanup() + + async def cms_initbydim(self, key: KeyT, width: int, depth: int, *, cell_size: int | None = None) -> bool: + """Create a Count-Min Sketch with fixed dimensions and optional counter width.""" + return await self._ensure_async_bool(self.client.cms().initbydim(key, width, depth, cell_size=cell_size)) + + async def cms_initbyprob( + self, key: KeyT, error: float, probability: float, *, cell_size: int | None = None + ) -> bool: + """Create a Count-Min Sketch sized by error bounds and optional counter width.""" + return await self._ensure_async_bool(self.client.cms().initbyprob(key, error, probability, cell_size=cell_size)) + + _sentinel: AsyncSentinel | None = None + + def __init__( + self, + redis_config: RedisConfig | None = None, + *, + metadata_resolver: AsyncMetadataResolver | None = None, + ) -> None: """Initialize the AsyncRedisAdapter with configuration settings. Args: redis_config (RedisConfig, optional): Configuration settings for Redis. If None, retrieves from global config. Defaults to None. + metadata_resolver: Optional command metadata for asynchronous cluster routing. """ configs: RedisConfig = redis_config or BaseConfig.global_config().REDIS + if metadata_resolver is not None and configs.MODE != RedisMode.CLUSTER: + raise ConfigurationError(operation="redis_connect", reason="async_metadata_requires_cluster") self._configs = configs + self._metadata_resolver = metadata_resolver self._search_client: AsyncRedis | AsyncRedisCluster | None = None self._set_clients(configs) @@ -367,7 +487,7 @@ def _set_standalone_clients(self, configs: RedisConfig) -> None: Args: configs (RedisConfig): Configuration settings for Redis. """ - if redis_master_host := configs.MASTER_HOST: + if redis_master_host := configs.MASTER_HOST or configs.UNIX_SOCKET_PATH: self.client: AsyncRedis | AsyncRedisCluster = self._get_client(redis_master_host, configs) if redis_slave_host := configs.SLAVE_HOST: self.read_only_client: AsyncRedis | AsyncRedisCluster = self._get_client(redis_slave_host, configs) @@ -402,6 +522,8 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: health_check_interval=configs.HEALTH_CHECK_INTERVAL, require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, + topology_refresh_min_interval=configs.CLUSTER.TOPOLOGY_REFRESH_MIN_INTERVAL, + metadata_resolver=self._metadata_resolver, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=True), **cluster_kwargs, @@ -429,12 +551,13 @@ def _set_sentinel_clients(self, configs: RedisConfig) -> None: sentinel_kwargs=_sentinel_kwargs(configs), ) + self._sentinel = sentinel_connection self.client = sentinel_connection.master_for( sentinel_service_name, **_sentinel_redis_kwargs(configs, is_async=True), ) - self.read_only_client = sentinel_connection.slave_for( + self.read_only_client = sentinel_connection.replica_for( sentinel_service_name, **_sentinel_redis_kwargs(configs, is_async=True), ) @@ -455,6 +578,7 @@ def _get_client(host: str, configs: RedisConfig, *, decode_responses: bool | Non host=host, port=configs.PORT, db=configs.DATABASE, + unix_socket_path=configs.UNIX_SOCKET_PATH, **_redis_connection_kwargs(configs, decode_responses=decode_responses, is_async=True), ) @@ -488,6 +612,8 @@ def _build_binary_client(self, configs: RedisConfig) -> AsyncRedis | AsyncRedisC health_check_interval=configs.HEALTH_CHECK_INTERVAL, require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, + topology_refresh_min_interval=configs.CLUSTER.TOPOLOGY_REFRESH_MIN_INTERVAL, + metadata_resolver=self._metadata_resolver, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=True), **cluster_kwargs, @@ -623,6 +749,8 @@ async def close(self) -> None: await client.aclose() else: await client.aclose(close_connection_pool=True) + if self._sentinel is not None: + await self._sentinel.aclose() self._search_client = None async def __aenter__(self) -> Self: diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/keys.py b/packages/redis/archipy/adapters/redis/adapter_mixins/keys.py index 431d5ae4b..90253fdab 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/keys.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/keys.py @@ -15,10 +15,35 @@ if TYPE_CHECKING: from datetime import datetime, timedelta + from redis.commands.core import BlessFlag + from redis.typing import KeyT, ScanResponse + class RedisKeysMixin(SyncRedisMixinBase): """Sync Redis mixin for keys operations.""" + def bitrangeintarray( + self, key: KeyT, start: int, end: int, *, mode: str | None = None, limit: int | None = None, zeros: bool = False + ) -> list[int]: + """Return positions of set or unset bits within a range.""" + return self.read_only_client.bitrangeintarray(key, start, end, mode=mode, limit=limit, zeros=zeros) + + def bless_get(self, name: KeyT) -> list[bytes | str]: + """Return the bless flags on a key.""" + return self.read_only_client.bless_get(name) + + def bless_set(self, name: KeyT, flag: BlessFlag) -> int: + """Set a bless flag on a key.""" + return self.client.bless_set(name, flag) + + def bless_clear(self, name: KeyT, flag: BlessFlag) -> int: + """Remove a bless flag from a key.""" + return self.client.bless_clear(name, flag) + + def bless_scan(self, cursor: int, flag: BlessFlag, *, count: int | None = None) -> ScanResponse: + """Scan keys that have the specified bless flag.""" + return self.client.bless_scan(cursor, flag, count=count) + def pttl(self, name: bytes | str) -> int: """Get the time to live in milliseconds for a key. @@ -302,6 +327,28 @@ def scan_iter( class AsyncRedisKeysMixin(AsyncRedisMixinBase): """Async Redis mixin for keys operations.""" + async def bitrangeintarray( + self, key: KeyT, start: int, end: int, *, mode: str | None = None, limit: int | None = None, zeros: bool = False + ) -> list[int]: + """Return positions of set or unset bits within a range.""" + return await self.read_only_client.bitrangeintarray(key, start, end, mode=mode, limit=limit, zeros=zeros) + + async def bless_get(self, name: KeyT) -> list[bytes | str]: + """Return the bless flags on a key.""" + return await self.read_only_client.bless_get(name) + + async def bless_set(self, name: KeyT, flag: BlessFlag) -> int: + """Set a bless flag on a key.""" + return await self.client.bless_set(name, flag) + + async def bless_clear(self, name: KeyT, flag: BlessFlag) -> int: + """Remove a bless flag from a key.""" + return await self.client.bless_clear(name, flag) + + async def bless_scan(self, cursor: int, flag: BlessFlag, *, count: int | None = None) -> ScanResponse: + """Scan keys that have the specified bless flag.""" + return await self.client.bless_scan(cursor, flag, count=count) + async def pttl(self, name: bytes | str) -> int: """Get the time to live in milliseconds for a key asynchronously. diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/lists.py b/packages/redis/archipy/adapters/redis/adapter_mixins/lists.py index 50f96a313..cd0570ac5 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/lists.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/lists.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Awaitable, Iterable +from typing import Literal from archipy.adapters.redis.adapter_mixins._shared import ( AsyncRedisMixinBase, @@ -14,6 +15,60 @@ class RedisListsMixin(SyncRedisMixinBase): """Sync Redis mixin for lists operations.""" + def lmovem( + self, + first_list: str, + second_list: str, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Atomically move elements from one list to another. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + result = self.client.lmovem( + first_list, + second_list, + src=src, + dest=dest, + count=count, + mode=mode, + ordering=ordering, + ) + return result + + def blmovem( + self, + first_list: str, + second_list: str, + timeout_seconds: float, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Wait for a source list and atomically move elements to a destination list. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + result = self.client.blmovem( + first_list, + second_list, + timeout_seconds, + src=src, + dest=dest, + count=count, + mode=mode, + ordering=ordering, + ) + return result + def llen(self, name: str) -> int: """Get the length of a list. @@ -123,6 +178,60 @@ def rpush(self, name: str, *values: bytes | str | float) -> int: class AsyncRedisListsMixin(AsyncRedisMixinBase): """Async Redis mixin for lists operations.""" + async def lmovem( + self, + first_list: str, + second_list: str, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Atomically move elements from one list to another. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + result = self.client.lmovem( + first_list, + second_list, + src=src, + dest=dest, + count=count, + mode=mode, + ordering=ordering, + ) + return await result + + async def blmovem( + self, + first_list: str, + second_list: str, + timeout_seconds: float, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Wait for a source list and atomically move elements to a destination list. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + result = self.client.blmovem( + first_list, + second_list, + timeout_seconds, + src=src, + dest=dest, + count=count, + mode=mode, + ordering=ordering, + ) + return await result + async def llen(self, name: str) -> int: """Get the length of a list asynchronously. diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/pubsub.py b/packages/redis/archipy/adapters/redis/adapter_mixins/pubsub.py index 1da4a5786..1001ac9b1 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/pubsub.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/pubsub.py @@ -30,6 +30,10 @@ def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> """ return self.client.publish(channel, message, **kwargs) + def spublish(self, channel: bytes | str, message: bytes | str) -> int: + """Publish a message to a Redis shard channel.""" + return self.client.spublish(channel, message) + def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]: """List active channels matching a pattern. @@ -70,6 +74,10 @@ async def publish(self, channel: bytes | str, message: bytes | str, **kwargs: An """ return await self.client.publish(channel, message, **kwargs) + async def spublish(self, channel: bytes | str, message: bytes | str) -> int: + """Publish a message to a Redis shard channel.""" + return await self.client.spublish(channel, message) + async def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]: """List active channels matching pattern asynchronously. diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py b/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py index a25b95e73..3eac8c688 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py @@ -2,7 +2,8 @@ from __future__ import annotations -from collections.abc import Awaitable, Iterable, Iterator +from collections.abc import Awaitable, Iterable, Iterator, Sequence +from typing import TYPE_CHECKING from archipy.adapters.redis.adapter_mixins._shared import ( AsyncRedisMixinBase, @@ -13,10 +14,123 @@ from archipy.adapters.redis.async_iteration import AwaitableAsyncIterator from archipy.models.errors import InternalError, InvalidArgumentError +if TYPE_CHECKING: + from redis.commands.core import SetDataPersistOptions + from redis.typing import AbsExpiryT, ExpiryT, FieldT, KeyT + class RedisSetsMixin(SyncRedisMixinBase): """Sync Redis mixin for sets operations.""" + def saddex( + self, + name: KeyT, + *members: FieldT, + ex: ExpiryT | str | None = None, + px: ExpiryT | str | None = None, + exat: AbsExpiryT | None = None, + pxat: AbsExpiryT | None = None, + data_persist_option: SetDataPersistOptions | None = None, + keepttl: bool = False, + ) -> int: + """Add set members with optional expiration and existence conditions.""" + return self.client.saddex( + name, *members, ex=ex, px=px, exat=exat, pxat=pxat, data_persist_option=data_persist_option, keepttl=keepttl + ) + + def sexpire( + self, + name: KeyT, + seconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in seconds and return per-member status codes.""" + return self.client.sexpire(name, seconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + def spexpire( + self, + name: KeyT, + milliseconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in milliseconds and return per-member status codes.""" + return self.client.spexpire(name, milliseconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + def sexpireat( + self, + name: KeyT, + unix_time_seconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in seconds and return per-member status codes.""" + return self.client.sexpireat(name, unix_time_seconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + def spexpireat( + self, + name: KeyT, + unix_time_milliseconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in milliseconds and return per-member status codes.""" + return self.client.spexpireat(name, unix_time_milliseconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + def sttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in seconds.""" + return self.read_only_client.sttl(name, *members) + + def spttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in milliseconds.""" + return self.read_only_client.spttl(name, *members) + + def sexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in seconds.""" + return self.read_only_client.sexpiretime(name, *members) + + def spexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in milliseconds.""" + return self.read_only_client.spexpiretime(name, *members) + + def spersist(self, name: KeyT, *members: FieldT) -> list[int]: + """Remove expiration from the members and return per-member status codes.""" + return self.client.spersist(name, *members) + + def sdiffcard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + ) -> int: + """Return the cardinality of the set difference.""" + return self._ensure_sync_int(self.read_only_client.sdiffcard(len(keys), list(keys), limit=limit)) + + def sunioncard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + approx: bool = False, + ) -> int: + """Return the cardinality of the set union.""" + return self._ensure_sync_int( + self.read_only_client.sunioncard(len(keys), list(keys), limit=limit, approx=approx) + ) + def sscan( self, name: bytes | str, @@ -158,6 +272,115 @@ def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]: class AsyncRedisSetsMixin(AsyncRedisMixinBase): """Async Redis mixin for sets operations.""" + async def saddex( + self, + name: KeyT, + *members: FieldT, + ex: ExpiryT | str | None = None, + px: ExpiryT | str | None = None, + exat: AbsExpiryT | None = None, + pxat: AbsExpiryT | None = None, + data_persist_option: SetDataPersistOptions | None = None, + keepttl: bool = False, + ) -> int: + """Add set members with optional expiration and existence conditions.""" + return await self.client.saddex( + name, *members, ex=ex, px=px, exat=exat, pxat=pxat, data_persist_option=data_persist_option, keepttl=keepttl + ) + + async def sexpire( + self, + name: KeyT, + seconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in seconds and return per-member status codes.""" + return await self.client.sexpire(name, seconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + async def spexpire( + self, + name: KeyT, + milliseconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in milliseconds and return per-member status codes.""" + return await self.client.spexpire(name, milliseconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + async def sexpireat( + self, + name: KeyT, + unix_time_seconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in seconds and return per-member status codes.""" + return await self.client.sexpireat(name, unix_time_seconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + async def spexpireat( + self, + name: KeyT, + unix_time_milliseconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in milliseconds and return per-member status codes.""" + return await self.client.spexpireat(name, unix_time_milliseconds, *members, nx=nx, xx=xx, gt=gt, lt=lt) + + async def sttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in seconds.""" + return await self.read_only_client.sttl(name, *members) + + async def spttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in milliseconds.""" + return await self.read_only_client.spttl(name, *members) + + async def sexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in seconds.""" + return await self.read_only_client.sexpiretime(name, *members) + + async def spexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in milliseconds.""" + return await self.read_only_client.spexpiretime(name, *members) + + async def spersist(self, name: KeyT, *members: FieldT) -> list[int]: + """Remove expiration from the members and return per-member status codes.""" + return await self.client.spersist(name, *members) + + async def sdiffcard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + ) -> int: + """Return the cardinality of the set difference.""" + return await self._ensure_async_int(self.read_only_client.sdiffcard(len(keys), list(keys), limit=limit)) + + async def sunioncard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + approx: bool = False, + ) -> int: + """Return the cardinality of the set union.""" + return await self._ensure_async_int( + self.read_only_client.sunioncard(len(keys), list(keys), limit=limit, approx=approx) + ) + async def sscan( self, name: bytes | str, diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/sorted_sets.py b/packages/redis/archipy/adapters/redis/adapter_mixins/sorted_sets.py index 1d01d3db9..f9c0c66c1 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/sorted_sets.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/sorted_sets.py @@ -13,12 +13,52 @@ ) if TYPE_CHECKING: + from redis.typing import EncodableT, KeyT, ZMoveResponse, ZScoreBoundT + from archipy.adapters.redis.port_mixins.sorted_sets import RedisScoreCastType class RedisSortedSetsMixin(SyncRedisMixinBase): """Sync Redis mixin for sorted_sets operations.""" + def zmove( + self, + source: KeyT, + destination: KeyT, + *, + lowest: bool = False, + highest: bool = False, + byscore: tuple[ZScoreBoundT, ZScoreBoundT] | None = None, + count: int | None = None, + ) -> ZMoveResponse: + """Move sorted-set members selected by rank or score.""" + return self.client.zmove(source, destination, min=lowest, max=highest, byscore=byscore, count=count) + + def bzmove( + self, + source: KeyT, + destination: KeyT, + timeout_seconds: float, + *, + lowest: bool = False, + highest: bool = False, + count: int | None = None, + ) -> ZMoveResponse: + """Wait for source members and move them to the destination sorted set.""" + return self.client.bzmove(source, destination, timeout_seconds, min=lowest, max=highest, count=count) + + def zmovemember( + self, + source: KeyT, + destination: KeyT, + members: EncodableT | Iterable[EncodableT], + *, + nx: bool = False, + xx: bool = False, + ) -> ZMoveResponse: + """Move named members from one sorted set to another.""" + return self.client.zmovemember(source, destination, members, nx=nx, xx=xx) + def zadd( self, name: bytes | str, @@ -290,6 +330,44 @@ def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) class AsyncRedisSortedSetsMixin(AsyncRedisMixinBase): """Async Redis mixin for sorted_sets operations.""" + async def zmove( + self, + source: KeyT, + destination: KeyT, + *, + lowest: bool = False, + highest: bool = False, + byscore: tuple[ZScoreBoundT, ZScoreBoundT] | None = None, + count: int | None = None, + ) -> ZMoveResponse: + """Move sorted-set members selected by rank or score.""" + return await self.client.zmove(source, destination, min=lowest, max=highest, byscore=byscore, count=count) + + async def bzmove( + self, + source: KeyT, + destination: KeyT, + timeout_seconds: float, + *, + lowest: bool = False, + highest: bool = False, + count: int | None = None, + ) -> ZMoveResponse: + """Wait for source members and move them to the destination sorted set.""" + return await self.client.bzmove(source, destination, timeout_seconds, min=lowest, max=highest, count=count) + + async def zmovemember( + self, + source: KeyT, + destination: KeyT, + members: EncodableT | Iterable[EncodableT], + *, + nx: bool = False, + xx: bool = False, + ) -> ZMoveResponse: + """Move named members from one sorted set to another.""" + return await self.client.zmovemember(source, destination, members, nx=nx, xx=xx) + async def zadd( self, name: bytes | str, diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/streams.py b/packages/redis/archipy/adapters/redis/adapter_mixins/streams.py new file mode 100644 index 000000000..3eeb916b8 --- /dev/null +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/streams.py @@ -0,0 +1,122 @@ +"""Redis stream adapter methods.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from archipy.adapters.redis.adapter_mixins._shared import AsyncRedisMixinBase, SyncRedisMixinBase + +if TYPE_CHECKING: + from redis.typing import KeyT, StreamIdT, XReadGroupResponse, XReadResponse + + +class RedisStreamsMixin(SyncRedisMixinBase): + """Synchronous Redis stream operations.""" + + def xread( + self, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadResponse: + """Read stream entries, optionally waiting for new ones. + + The Redis 8.10+ limits apply across all streams in the request. + """ + result = self.client.xread( + streams, + count=count, + block=block, + max_count=max_count, + max_size=max_size, + ) + return result + + def xreadgroup( + self, + groupname: str, + consumername: str, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + noack: bool = False, + claim_min_idle_time: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadGroupResponse: + """Read stream entries for a consumer group. + + The Redis 8.10+ limits apply across all streams in the request. + """ + result = self.client.xreadgroup( + groupname, + consumername, + streams, + count=count, + block=block, + noack=noack, + claim_min_idle_time=claim_min_idle_time, + max_count=max_count, + max_size=max_size, + ) + return result + + +class AsyncRedisStreamsMixin(AsyncRedisMixinBase): + """Asynchronous Redis stream operations.""" + + async def xread( + self, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadResponse: + """Read stream entries, optionally waiting for new ones. + + The Redis 8.10+ limits apply across all streams in the request. + """ + result = self.client.xread( + streams, + count=count, + block=block, + max_count=max_count, + max_size=max_size, + ) + return await result + + async def xreadgroup( + self, + groupname: str, + consumername: str, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + noack: bool = False, + claim_min_idle_time: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadGroupResponse: + """Read stream entries for a consumer group. + + The Redis 8.10+ limits apply across all streams in the request. + """ + result = self.client.xreadgroup( + groupname, + consumername, + streams, + count=count, + block=block, + noack=noack, + claim_min_idle_time=claim_min_idle_time, + max_count=max_count, + max_size=max_size, + ) + return await result diff --git a/packages/redis/archipy/adapters/redis/adapters.py b/packages/redis/archipy/adapters/redis/adapters.py index d56e3b192..f0f151875 100644 --- a/packages/redis/archipy/adapters/redis/adapters.py +++ b/packages/redis/archipy/adapters/redis/adapters.py @@ -12,6 +12,7 @@ AsyncRedisPubSubMixin, AsyncRedisSetsMixin, AsyncRedisSortedSetsMixin, + AsyncRedisStreamsMixin, RedisArraysMixin, RedisClusterMixin, RedisConnectionMixin, @@ -21,6 +22,7 @@ RedisPubSubMixin, RedisSetsMixin, RedisSortedSetsMixin, + RedisStreamsMixin, ) from archipy.adapters.redis.error_mapping import map_redis_errors from archipy.adapters.redis.ports import AsyncRedisPort, RedisPort @@ -38,6 +40,7 @@ class RedisAdapter( RedisListsMixin, RedisSetsMixin, RedisSortedSetsMixin, + RedisStreamsMixin, RedisArraysMixin, RedisHashesMixin, RedisPubSubMixin, @@ -60,6 +63,7 @@ class AsyncRedisAdapter( AsyncRedisListsMixin, AsyncRedisSetsMixin, AsyncRedisSortedSetsMixin, + AsyncRedisStreamsMixin, AsyncRedisArraysMixin, AsyncRedisHashesMixin, AsyncRedisPubSubMixin, diff --git a/packages/redis/archipy/adapters/redis/port_mixins/__init__.py b/packages/redis/archipy/adapters/redis/port_mixins/__init__.py index b13f8c239..53bfdfcc6 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/__init__.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/__init__.py @@ -28,6 +28,7 @@ RedisScoreCastType, RedisSortedSetsPort, ) +from archipy.adapters.redis.port_mixins.streams import AsyncRedisStreamsPort, RedisStreamsPort __all__ = [ "AsyncRedisArraysPort", @@ -39,6 +40,7 @@ "AsyncRedisPubSubPort", "AsyncRedisSetsPort", "AsyncRedisSortedSetsPort", + "AsyncRedisStreamsPort", "RedisArraysPort", "RedisClusterPort", "RedisConnectionPort", @@ -49,4 +51,5 @@ "RedisScoreCastType", "RedisSetsPort", "RedisSortedSetsPort", + "RedisStreamsPort", ] diff --git a/packages/redis/archipy/adapters/redis/port_mixins/connection.py b/packages/redis/archipy/adapters/redis/port_mixins/connection.py index 27f86f4dc..b5ea926d6 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/connection.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/connection.py @@ -6,9 +6,12 @@ from typing import TYPE_CHECKING, Any, Self if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + from redis.asyncio.client import Pipeline as AsyncPipeline from redis.asyncio.cluster import ClusterPipeline as AsyncClusterPipeline from redis.client import Pipeline + from redis.typing import EncodableT, KeyT from archipy.adapters.redis.search_ports import ( AsyncRedisSearchHandlePort, @@ -19,6 +22,53 @@ class RedisConnectionPort: """Sync Redis port for connection operations.""" + @abstractmethod + def client_list_iter( + self, client_type: str | None = None, *, client_ids: Sequence[EncodableT] = () + ) -> Iterator[dict[str, str]]: + """Iterate over parsed records from the server's client list.""" + raise NotImplementedError + + @abstractmethod + def backup_start(self) -> bytes | str: + """Start a coordinated backup on the server.""" + raise NotImplementedError + + @abstractmethod + def backup_status(self) -> dict[str | bytes, Any]: + """Return the server's current backup status.""" + raise NotImplementedError + + @abstractmethod + def backup_list(self) -> list[bytes | str]: + """List files generated for the active backup.""" + raise NotImplementedError + + @abstractmethod + def backup_seal(self) -> bytes | str: + """Seal the backup so its files can be copied.""" + raise NotImplementedError + + @abstractmethod + def backup_abort(self) -> bytes | str: + """Abort the active backup.""" + raise NotImplementedError + + @abstractmethod + def backup_cleanup(self) -> bytes | str: + """Remove temporary artifacts of the last backup.""" + raise NotImplementedError + + @abstractmethod + def cms_initbydim(self, key: KeyT, width: int, depth: int, *, cell_size: int | None = None) -> bool: + """Create a Count-Min Sketch with fixed dimensions and optional counter width.""" + raise NotImplementedError + + @abstractmethod + def cms_initbyprob(self, key: KeyT, error: float, probability: float, *, cell_size: int | None = None) -> bool: + """Create a Count-Min Sketch sized by error bounds and optional counter width.""" + raise NotImplementedError + @abstractmethod def close(self) -> None: """Close every client and connection pool the adapter opened. @@ -131,6 +181,55 @@ def search_index(self, name: str) -> RedisSearchHandlePort: class AsyncRedisConnectionPort: """Async Redis port for connection operations.""" + @abstractmethod + async def client_list_iter( + self, client_type: str | None = None, *, client_ids: Sequence[EncodableT] = () + ) -> Iterator[dict[str, str]]: + """Iterate over parsed records from the server's client list.""" + raise NotImplementedError + + @abstractmethod + async def backup_start(self) -> bytes | str: + """Start a coordinated backup on the server.""" + raise NotImplementedError + + @abstractmethod + async def backup_status(self) -> dict[str | bytes, Any]: + """Return the server's current backup status.""" + raise NotImplementedError + + @abstractmethod + async def backup_list(self) -> list[bytes | str]: + """List files generated for the active backup.""" + raise NotImplementedError + + @abstractmethod + async def backup_seal(self) -> bytes | str: + """Seal the backup so its files can be copied.""" + raise NotImplementedError + + @abstractmethod + async def backup_abort(self) -> bytes | str: + """Abort the active backup.""" + raise NotImplementedError + + @abstractmethod + async def backup_cleanup(self) -> bytes | str: + """Remove temporary artifacts of the last backup.""" + raise NotImplementedError + + @abstractmethod + async def cms_initbydim(self, key: KeyT, width: int, depth: int, *, cell_size: int | None = None) -> bool: + """Create a Count-Min Sketch with fixed dimensions and optional counter width.""" + raise NotImplementedError + + @abstractmethod + async def cms_initbyprob( + self, key: KeyT, error: float, probability: float, *, cell_size: int | None = None + ) -> bool: + """Create a Count-Min Sketch sized by error bounds and optional counter width.""" + raise NotImplementedError + @abstractmethod async def close(self) -> None: """Close every client and connection pool the adapter opened asynchronously. diff --git a/packages/redis/archipy/adapters/redis/port_mixins/keys.py b/packages/redis/archipy/adapters/redis/port_mixins/keys.py index 9f1585c4e..41d1159f4 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/keys.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/keys.py @@ -9,12 +9,42 @@ from collections.abc import Iterable, Iterator, Mapping from datetime import datetime, timedelta + from redis.commands.core import BlessFlag + from redis.typing import KeyT, ScanResponse + from archipy.adapters.redis.async_iteration import AwaitableAsyncIterator class RedisKeysPort: """Sync Redis port for keys operations.""" + @abstractmethod + def bitrangeintarray( + self, key: KeyT, start: int, end: int, *, mode: str | None = None, limit: int | None = None, zeros: bool = False + ) -> list[int]: + """Return positions of set or unset bits within a range.""" + raise NotImplementedError + + @abstractmethod + def bless_get(self, name: KeyT) -> list[bytes | str]: + """Return the bless flags on a key.""" + raise NotImplementedError + + @abstractmethod + def bless_set(self, name: KeyT, flag: BlessFlag) -> int: + """Set a bless flag on a key.""" + raise NotImplementedError + + @abstractmethod + def bless_clear(self, name: KeyT, flag: BlessFlag) -> int: + """Remove a bless flag from a key.""" + raise NotImplementedError + + @abstractmethod + def bless_scan(self, cursor: int, flag: BlessFlag, *, count: int | None = None) -> ScanResponse: + """Scan keys that have the specified bless flag.""" + raise NotImplementedError + @abstractmethod def pttl(self, name: bytes | str) -> int: """Gets the remaining time to live of a key in milliseconds. @@ -355,6 +385,33 @@ def scan_iter( class AsyncRedisKeysPort: """Async Redis port for keys operations.""" + @abstractmethod + async def bitrangeintarray( + self, key: KeyT, start: int, end: int, *, mode: str | None = None, limit: int | None = None, zeros: bool = False + ) -> list[int]: + """Return positions of set or unset bits within a range.""" + raise NotImplementedError + + @abstractmethod + async def bless_get(self, name: KeyT) -> list[bytes | str]: + """Return the bless flags on a key.""" + raise NotImplementedError + + @abstractmethod + async def bless_set(self, name: KeyT, flag: BlessFlag) -> int: + """Set a bless flag on a key.""" + raise NotImplementedError + + @abstractmethod + async def bless_clear(self, name: KeyT, flag: BlessFlag) -> int: + """Remove a bless flag from a key.""" + raise NotImplementedError + + @abstractmethod + async def bless_scan(self, cursor: int, flag: BlessFlag, *, count: int | None = None) -> ScanResponse: + """Scan keys that have the specified bless flag.""" + raise NotImplementedError + @abstractmethod async def pttl(self, name: bytes | str) -> int: """Gets the remaining time to live of a key in milliseconds asynchronously. diff --git a/packages/redis/archipy/adapters/redis/port_mixins/lists.py b/packages/redis/archipy/adapters/redis/port_mixins/lists.py index 9a83e8966..f971e053a 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/lists.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/lists.py @@ -3,11 +3,49 @@ from __future__ import annotations from abc import abstractmethod +from typing import Literal class RedisListsPort: """Sync Redis port for lists operations.""" + @abstractmethod + def lmovem( + self, + first_list: str, + second_list: str, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Atomically move elements from one list to another. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + raise NotImplementedError + + @abstractmethod + def blmovem( + self, + first_list: str, + second_list: str, + timeout_seconds: float, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Wait for a source list and atomically move elements to a destination list. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + raise NotImplementedError + @abstractmethod def llen(self, name: str) -> int: """Gets the length of a list. @@ -142,6 +180,43 @@ def rpush(self, name: str, *values: bytes | str | float) -> int: class AsyncRedisListsPort: """Async Redis port for lists operations.""" + @abstractmethod + async def lmovem( + self, + first_list: str, + second_list: str, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Atomically move elements from one list to another. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + raise NotImplementedError + + @abstractmethod + async def blmovem( + self, + first_list: str, + second_list: str, + timeout_seconds: float, + *, + src: Literal["LEFT", "RIGHT"] = "LEFT", + dest: Literal["LEFT", "RIGHT"] = "RIGHT", + count: int | None = None, + mode: Literal["COUNT", "EXACTLY"] | None = None, + ordering: Literal["OBO", "BULK"] | None = None, + ) -> list[bytes | str] | None: + """Wait for a source list and atomically move elements to a destination list. + + A count requires an ordering. In Cluster, both keys must share a slot. + """ + raise NotImplementedError + @abstractmethod async def llen(self, name: str) -> int: """Gets the length of a list asynchronously. diff --git a/packages/redis/archipy/adapters/redis/port_mixins/pubsub.py b/packages/redis/archipy/adapters/redis/port_mixins/pubsub.py index eb4ecf71a..79e90d405 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/pubsub.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/pubsub.py @@ -30,6 +30,11 @@ def publish(self, channel: bytes | str, message: bytes | str, **kwargs: Any) -> """ raise NotImplementedError + @abstractmethod + def spublish(self, channel: bytes | str, message: bytes | str) -> int: + """Publish a message to a Redis shard channel.""" + raise NotImplementedError + @abstractmethod def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]: """Lists active channels matching a pattern. @@ -82,6 +87,11 @@ async def publish(self, channel: bytes | str, message: bytes | str, **kwargs: An """ raise NotImplementedError + @abstractmethod + async def spublish(self, channel: bytes | str, message: bytes | str) -> int: + """Publish a message to a Redis shard channel.""" + raise NotImplementedError + @abstractmethod async def pubsub_channels(self, pattern: bytes | str = "*", **kwargs: Any) -> list[bytes | str]: """Lists active channels matching a pattern asynchronously. diff --git a/packages/redis/archipy/adapters/redis/port_mixins/sets.py b/packages/redis/archipy/adapters/redis/port_mixins/sets.py index b36d66c31..321e27d7c 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/sets.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/sets.py @@ -6,7 +6,10 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Iterator, Sequence + + from redis.commands.core import SetDataPersistOptions + from redis.typing import AbsExpiryT, ExpiryT, FieldT, KeyT from archipy.adapters.redis.async_iteration import AwaitableAsyncIterator @@ -16,6 +19,123 @@ class RedisSetsPort: """Sync Redis port for sets operations.""" + @abstractmethod + def saddex( + self, + name: KeyT, + *members: FieldT, + ex: ExpiryT | str | None = None, + px: ExpiryT | str | None = None, + exat: AbsExpiryT | None = None, + pxat: AbsExpiryT | None = None, + data_persist_option: SetDataPersistOptions | None = None, + keepttl: bool = False, + ) -> int: + """Add set members with optional expiration and existence conditions.""" + raise NotImplementedError + + @abstractmethod + def sexpire( + self, + name: KeyT, + seconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in seconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + def spexpire( + self, + name: KeyT, + milliseconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in milliseconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + def sexpireat( + self, + name: KeyT, + unix_time_seconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in seconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + def spexpireat( + self, + name: KeyT, + unix_time_milliseconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in milliseconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + def sttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in seconds.""" + raise NotImplementedError + + @abstractmethod + def spttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in milliseconds.""" + raise NotImplementedError + + @abstractmethod + def sexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in seconds.""" + raise NotImplementedError + + @abstractmethod + def spexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in milliseconds.""" + raise NotImplementedError + + @abstractmethod + def spersist(self, name: KeyT, *members: FieldT) -> list[int]: + """Remove expiration from the members and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + def sdiffcard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + ) -> int: + """Return the cardinality of the set difference.""" + raise NotImplementedError + + @abstractmethod + def sunioncard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + approx: bool = False, + ) -> int: + """Return the cardinality of the set union.""" + raise NotImplementedError + @abstractmethod def sscan( self, @@ -176,6 +296,123 @@ def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]: class AsyncRedisSetsPort: """Async Redis port for sets operations.""" + @abstractmethod + async def saddex( + self, + name: KeyT, + *members: FieldT, + ex: ExpiryT | str | None = None, + px: ExpiryT | str | None = None, + exat: AbsExpiryT | None = None, + pxat: AbsExpiryT | None = None, + data_persist_option: SetDataPersistOptions | None = None, + keepttl: bool = False, + ) -> int: + """Add set members with optional expiration and existence conditions.""" + raise NotImplementedError + + @abstractmethod + async def sexpire( + self, + name: KeyT, + seconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in seconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + async def spexpire( + self, + name: KeyT, + milliseconds: ExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration in milliseconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + async def sexpireat( + self, + name: KeyT, + unix_time_seconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in seconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + async def spexpireat( + self, + name: KeyT, + unix_time_milliseconds: AbsExpiryT, + *members: FieldT, + nx: bool = False, + xx: bool = False, + gt: bool = False, + lt: bool = False, + ) -> list[int]: + """Set member expiration at a Unix timestamp in milliseconds and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + async def sttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in seconds.""" + raise NotImplementedError + + @abstractmethod + async def spttl(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's remaining lifetime in milliseconds.""" + raise NotImplementedError + + @abstractmethod + async def sexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in seconds.""" + raise NotImplementedError + + @abstractmethod + async def spexpiretime(self, name: KeyT, *members: FieldT) -> list[int]: + """Return each member's expiration as a Unix timestamp in milliseconds.""" + raise NotImplementedError + + @abstractmethod + async def spersist(self, name: KeyT, *members: FieldT) -> list[int]: + """Remove expiration from the members and return per-member status codes.""" + raise NotImplementedError + + @abstractmethod + async def sdiffcard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + ) -> int: + """Return the cardinality of the set difference.""" + raise NotImplementedError + + @abstractmethod + async def sunioncard( + self, + keys: Sequence[bytes | str], + *, + limit: int = 0, + approx: bool = False, + ) -> int: + """Return the cardinality of the set union.""" + raise NotImplementedError + @abstractmethod async def sscan( self, diff --git a/packages/redis/archipy/adapters/redis/port_mixins/sorted_sets.py b/packages/redis/archipy/adapters/redis/port_mixins/sorted_sets.py index 7b23deff5..d559ee08b 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/sorted_sets.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/sorted_sets.py @@ -4,14 +4,59 @@ from abc import abstractmethod from collections.abc import Callable, Iterable, Mapping -from typing import Any +from typing import TYPE_CHECKING, Any RedisScoreCastType = type | Callable[..., Any] +if TYPE_CHECKING: + from redis.typing import EncodableT, KeyT, ZMoveResponse, ZScoreBoundT + + class RedisSortedSetsPort: """Sync Redis port for sorted_sets operations.""" + @abstractmethod + def zmove( + self, + source: KeyT, + destination: KeyT, + *, + lowest: bool = False, + highest: bool = False, + byscore: tuple[ZScoreBoundT, ZScoreBoundT] | None = None, + count: int | None = None, + ) -> ZMoveResponse: + """Move sorted-set members selected by rank or score.""" + raise NotImplementedError + + @abstractmethod + def bzmove( + self, + source: KeyT, + destination: KeyT, + timeout_seconds: float, + *, + lowest: bool = False, + highest: bool = False, + count: int | None = None, + ) -> ZMoveResponse: + """Wait for source members and move them to the destination sorted set.""" + raise NotImplementedError + + @abstractmethod + def zmovemember( + self, + source: KeyT, + destination: KeyT, + members: EncodableT | Iterable[EncodableT], + *, + nx: bool = False, + xx: bool = False, + ) -> ZMoveResponse: + """Move named members from one sorted set to another.""" + raise NotImplementedError + @abstractmethod def zadd( self, @@ -329,6 +374,47 @@ def zincrby(self, name: bytes | str, amount: float, value: bytes | str | float) class AsyncRedisSortedSetsPort: """Async Redis port for sorted_sets operations.""" + @abstractmethod + async def zmove( + self, + source: KeyT, + destination: KeyT, + *, + lowest: bool = False, + highest: bool = False, + byscore: tuple[ZScoreBoundT, ZScoreBoundT] | None = None, + count: int | None = None, + ) -> ZMoveResponse: + """Move sorted-set members selected by rank or score.""" + raise NotImplementedError + + @abstractmethod + async def bzmove( + self, + source: KeyT, + destination: KeyT, + timeout_seconds: float, + *, + lowest: bool = False, + highest: bool = False, + count: int | None = None, + ) -> ZMoveResponse: + """Wait for source members and move them to the destination sorted set.""" + raise NotImplementedError + + @abstractmethod + async def zmovemember( + self, + source: KeyT, + destination: KeyT, + members: EncodableT | Iterable[EncodableT], + *, + nx: bool = False, + xx: bool = False, + ) -> ZMoveResponse: + """Move named members from one sorted set to another.""" + raise NotImplementedError + @abstractmethod async def zadd( self, diff --git a/packages/redis/archipy/adapters/redis/port_mixins/streams.py b/packages/redis/archipy/adapters/redis/port_mixins/streams.py new file mode 100644 index 000000000..612daa3ff --- /dev/null +++ b/packages/redis/archipy/adapters/redis/port_mixins/streams.py @@ -0,0 +1,89 @@ +"""Redis stream ports.""" + +from __future__ import annotations + +from abc import abstractmethod +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from redis.typing import KeyT, StreamIdT, XReadGroupResponse, XReadResponse + + +class RedisStreamsPort: + """Synchronous Redis stream operations.""" + + @abstractmethod + def xread( + self, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadResponse: + """Read stream entries, optionally waiting for new ones. + + The Redis 8.10+ limits apply across all streams in the request. + """ + raise NotImplementedError + + @abstractmethod + def xreadgroup( + self, + groupname: str, + consumername: str, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + noack: bool = False, + claim_min_idle_time: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadGroupResponse: + """Read stream entries for a consumer group. + + The Redis 8.10+ limits apply across all streams in the request. + """ + raise NotImplementedError + + +class AsyncRedisStreamsPort: + """Asynchronous Redis stream operations.""" + + @abstractmethod + async def xread( + self, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadResponse: + """Read stream entries, optionally waiting for new ones. + + The Redis 8.10+ limits apply across all streams in the request. + """ + raise NotImplementedError + + @abstractmethod + async def xreadgroup( + self, + groupname: str, + consumername: str, + streams: dict[KeyT, StreamIdT], + *, + count: int | None = None, + block: int | None = None, + noack: bool = False, + claim_min_idle_time: int | None = None, + max_count: int | None = None, + max_size: int | None = None, + ) -> XReadGroupResponse: + """Read stream entries for a consumer group. + + The Redis 8.10+ limits apply across all streams in the request. + """ + raise NotImplementedError diff --git a/packages/redis/archipy/adapters/redis/ports.py b/packages/redis/archipy/adapters/redis/ports.py index 922f1b9a8..b77ce2089 100644 --- a/packages/redis/archipy/adapters/redis/ports.py +++ b/packages/redis/archipy/adapters/redis/ports.py @@ -12,6 +12,7 @@ AsyncRedisPubSubPort, AsyncRedisSetsPort, AsyncRedisSortedSetsPort, + AsyncRedisStreamsPort, RedisArraysPort, RedisClusterPort, RedisConnectionPort, @@ -22,6 +23,7 @@ RedisScoreCastType, RedisSetsPort, RedisSortedSetsPort, + RedisStreamsPort, ) __all__ = [ @@ -38,6 +40,7 @@ class RedisPort( RedisListsPort, RedisSetsPort, RedisSortedSetsPort, + RedisStreamsPort, RedisArraysPort, RedisHashesPort, RedisPubSubPort, @@ -56,6 +59,7 @@ class AsyncRedisPort( AsyncRedisListsPort, AsyncRedisSetsPort, AsyncRedisSortedSetsPort, + AsyncRedisStreamsPort, AsyncRedisArraysPort, AsyncRedisHashesPort, AsyncRedisPubSubPort, diff --git a/packages/redis/archipy/adapters/redis/search.py b/packages/redis/archipy/adapters/redis/search.py index 1c84352e5..aaaf64dfd 100644 --- a/packages/redis/archipy/adapters/redis/search.py +++ b/packages/redis/archipy/adapters/redis/search.py @@ -11,9 +11,10 @@ from redis.commands.search import Search from redis.commands.search.aggregation import AggregateRequest, Asc, Desc from redis.commands.search.field import NumericField, TagField, TextField, VectorField +from redis.commands.search.hybrid_result import HybridResult from redis.commands.search.index_definition import IndexDefinition, IndexType from redis.commands.search.query import Query -from redis.commands.search.reducers import count as agg_count +from redis.commands.search.reducers import collect as agg_collect, count as agg_count from redis.commands.search.result import Result from archipy.adapters.redis.error_mapping import map_redis_errors @@ -39,6 +40,13 @@ if TYPE_CHECKING: from redis.asyncio.client import Redis as AsyncRedis from redis.client import Redis + from redis.commands.search.hybrid_query import ( + CombineResultsMethod, + HybridCursorQuery, + HybridPostProcessingConfig, + HybridQuery, + ) + from redis.commands.search.hybrid_result import HybridCursorResult from archipy.models.dtos.redis.search.aggregation_dto import AggregationDTO from archipy.models.dtos.redis.search.document_dto import ( @@ -463,12 +471,27 @@ def _build_range_query( def _build_aggregate_request(aggregation: AggregationDTO) -> AggregateRequest: """Build a redis-py AggregateRequest from an AggregationDTO.""" request = AggregateRequest(aggregation.query) - if aggregation.group_by: + if aggregation.group_by or aggregation.reduce_function == "COLLECT": reducers = [] if aggregation.reduce_function == "COUNT": alias = aggregation.reduce_field or "count" reducers.append(agg_count().alias(alias)) - group_by = [_normalize_search_field_ref(field) for field in aggregation.group_by] + elif aggregation.reduce_function == "COLLECT": + fields = [_normalize_search_field_ref(field) for field in aggregation.collect_fields] or "*" + alias = aggregation.reduce_field or "collected" + sort_by = None + if aggregation.collect_sort_by: + sort_cls = Asc if aggregation.collect_sort_direction == "ASC" else Desc + sort_by = sort_cls(_normalize_search_field_ref(aggregation.collect_sort_by)) + if fields == "*": + request.load() + else: + load_fields = [*fields, *[_normalize_search_field_ref(field) for field in aggregation.group_by or []]] + if aggregation.collect_sort_by: + load_fields.append(_normalize_search_field_ref(aggregation.collect_sort_by)) + request.load(*dict.fromkeys(load_fields)) + reducers.append(agg_collect(fields, sort_by=sort_by, limit=aggregation.collect_limit).alias(alias)) + group_by = [_normalize_search_field_ref(field) for field in aggregation.group_by or []] request.group_by(group_by, *reducers) if aggregation.sort_by: sort_field = _normalize_search_field_ref(aggregation.sort_by) @@ -694,6 +717,37 @@ def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any return cast("dict[str, Any]", self._search.aggregate(request, **kwargs)) return _aggregate_result_to_dict(self._search.aggregate(request, **kwargs)) + @override + def hybrid_search( + self, + query: HybridQuery, + *, + combine_method: CombineResultsMethod | None = None, + post_processing: HybridPostProcessingConfig | None = None, + params_substitution: dict[str, str | int | float | bytes] | None = None, + timeout_ms: int | None = None, + cursor: HybridCursorQuery | None = None, + explain_score: bool = False, + ) -> HybridResult | HybridCursorResult: + """Search text and vectors together, optionally requesting score explanations.""" + result = self._client.ft(self._index_name).hybrid_search( + query, + combine_method=combine_method, + post_processing=post_processing, + params_substitution=params_substitution, + timeout=timeout_ms, + cursor=cursor, + explain_score=explain_score, + ) + if isinstance(result, dict): + return HybridResult(**result) + return cast("HybridResult | HybridCursorResult", result) + + @override + def list_aliases(self) -> list[str]: + """List the aliases assigned to this index.""" + return sorted(_normalize_index_names(self._search.aliaslist())) + @override def add_alias(self, alias: str) -> bool: """Add an alias for the index.""" @@ -901,6 +955,38 @@ async def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[st ) return _aggregate_result_to_dict(await self._await_result(self._search.aggregate(request, **kwargs))) + @override + async def hybrid_search( + self, + query: HybridQuery, + *, + combine_method: CombineResultsMethod | None = None, + post_processing: HybridPostProcessingConfig | None = None, + params_substitution: dict[str, str | int | float | bytes] | None = None, + timeout_ms: int | None = None, + cursor: HybridCursorQuery | None = None, + explain_score: bool = False, + ) -> HybridResult | HybridCursorResult: + """Search text and vectors together, optionally requesting score explanations.""" + result = await self._client.ft(self._index_name).hybrid_search( + query, + combine_method=combine_method, + post_processing=post_processing, + params_substitution=params_substitution, + timeout=timeout_ms, + cursor=cursor, + explain_score=explain_score, + ) + if isinstance(result, dict): + return HybridResult(**result) + return cast("HybridResult | HybridCursorResult", result) + + @override + async def list_aliases(self) -> list[str]: + """List the aliases assigned to this index.""" + aliases = await self._client.ft(self._index_name).aliaslist() + return sorted(_normalize_index_names(aliases)) + @override async def add_alias(self, alias: str) -> bool: """Add an alias for the index asynchronously.""" diff --git a/packages/redis/archipy/adapters/redis/search_ports.py b/packages/redis/archipy/adapters/redis/search_ports.py index ad78741f4..548d66232 100644 --- a/packages/redis/archipy/adapters/redis/search_ports.py +++ b/packages/redis/archipy/adapters/redis/search_ports.py @@ -6,6 +6,14 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: + from redis.commands.search.hybrid_query import ( + CombineResultsMethod, + HybridCursorQuery, + HybridPostProcessingConfig, + HybridQuery, + ) + from redis.commands.search.hybrid_result import HybridCursorResult, HybridResult + from archipy.models.dtos.redis.search.aggregation_dto import AggregationDTO from archipy.models.dtos.redis.search.document_dto import ( HashDocumentUpsertDTO, @@ -105,6 +113,26 @@ def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any """Execute a RediSearch aggregation.""" raise NotImplementedError + @abstractmethod + def hybrid_search( # noqa: PLR0913 + self, + query: HybridQuery, + *, + combine_method: CombineResultsMethod | None = None, + post_processing: HybridPostProcessingConfig | None = None, + params_substitution: dict[str, str | int | float | bytes] | None = None, + timeout_ms: int | None = None, + cursor: HybridCursorQuery | None = None, + explain_score: bool = False, + ) -> HybridResult | HybridCursorResult: + """Search text and vectors together, optionally requesting score explanations.""" + raise NotImplementedError + + @abstractmethod + def list_aliases(self) -> list[str]: + """List the aliases assigned to this index.""" + raise NotImplementedError + @abstractmethod def add_alias(self, alias: str) -> bool: """Add an alias for the index.""" @@ -206,6 +234,26 @@ async def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[st """Execute a RediSearch aggregation asynchronously.""" raise NotImplementedError + @abstractmethod + async def hybrid_search( # noqa: PLR0913 + self, + query: HybridQuery, + *, + combine_method: CombineResultsMethod | None = None, + post_processing: HybridPostProcessingConfig | None = None, + params_substitution: dict[str, str | int | float | bytes] | None = None, + timeout_ms: int | None = None, + cursor: HybridCursorQuery | None = None, + explain_score: bool = False, + ) -> HybridResult | HybridCursorResult: + """Search text and vectors together, optionally requesting score explanations.""" + raise NotImplementedError + + @abstractmethod + async def list_aliases(self) -> list[str]: + """List the aliases assigned to this index.""" + raise NotImplementedError + @abstractmethod async def add_alias(self, alias: str) -> bool: """Add an alias for the index asynchronously.""" diff --git a/pyproject.toml b/pyproject.toml index 062e18098..591fb3308 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -504,7 +504,7 @@ unused-type-ignore-comment = "error" pyproject_root_var = "pyproject" [tool.codespell] -ignore-words-list = "exat,convertor" +ignore-words-list = "exat,convertor,optin" skip = ".git,__pycache__,build,dist" [tool.bandit]