From 9cfca2894aa0ba23cf5c0d83acf628b5fa30aff2 Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 17:39:36 +0330 Subject: [PATCH 01/10] feat(redis): expose Redis 8.10 adapter capabilities Add typed sync and async list moves, set cardinality, stream limits, TimeSeries queries and Search aggregation and alias support. Cover the new behavior with capability-tagged scenarios and document HIMPORT. Refs #641 --- .../dtos/redis/search/aggregation_dto.py | 12 +- docs/tutorials/adapters/redis.md | 70 +++- features/redis_adapter.feature | 267 ++++++++++++--- features/redis_adapter_apm.feature | 3 +- features/steps/redis_81_steps.py | 313 ++++++++++++++++++ .../adapters/redis/adapter_mixins/__init__.py | 6 + .../redis/adapter_mixins/connection.py | 14 +- .../adapters/redis/adapter_mixins/lists.py | 109 ++++++ .../adapters/redis/adapter_mixins/sets.py | 44 ++- .../adapters/redis/adapter_mixins/streams.py | 122 +++++++ .../redis/adapter_mixins/time_series.py | 197 +++++++++++ .../redis/archipy/adapters/redis/adapters.py | 8 + .../adapters/redis/port_mixins/__init__.py | 6 + .../adapters/redis/port_mixins/lists.py | 75 +++++ .../adapters/redis/port_mixins/sets.py | 44 ++- .../adapters/redis/port_mixins/streams.py | 89 +++++ .../adapters/redis/port_mixins/time_series.py | 188 +++++++++++ .../redis/archipy/adapters/redis/ports.py | 8 + .../redis/archipy/adapters/redis/search.py | 25 +- .../archipy/adapters/redis/search_ports.py | 10 + 20 files changed, 1552 insertions(+), 58 deletions(-) create mode 100644 features/steps/redis_81_steps.py create mode 100644 packages/redis/archipy/adapters/redis/adapter_mixins/streams.py create mode 100644 packages/redis/archipy/adapters/redis/adapter_mixins/time_series.py create mode 100644 packages/redis/archipy/adapters/redis/port_mixins/streams.py create mode 100644 packages/redis/archipy/adapters/redis/port_mixins/time_series.py 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..346c7d77d 100644 --- a/docs/tutorials/adapters/redis.md +++ b/docs/tutorials/adapters/redis.md @@ -179,6 +179,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 @@ -266,6 +270,51 @@ logger.info(f"Second call (cached): {result2}") ## Advanced Redis Features +### List batches, set cardinality, streams, and TimeSeries + +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, stream, or `TS.NRANGE` 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) + +redis_adapter.ts_read("{room}:temperature", 0, max_count=10) +redis_adapter.ts_nrange(["{room}:temperature", "{room}:humidity"], "-", "+") +redis_adapter.ts_nrevrange(["{room}:temperature", "{room}:humidity"], "-", "+") +redis_adapter.ts_querylabels(label="location", filters=["type=sensor"]) +redis_adapter.ts_mrange("-", "+", ["type=sensor"], exclude_empty=True) +redis_adapter.ts_mrevrange("-", "+", ["type=sensor"], exclude_empty=True) +``` + +`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. +TimeSeries queries by label are coordinated by Redis across the cluster. `exclude_empty` omits series that have +no returned samples and is incompatible with `groupby`. + +Use real Redis to test stream limits and RediSearch. Fakeredis 2.40.0 lacks those behaviors. + +### 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 The `publish` and `pubsub` methods are available through the port interface: @@ -846,6 +895,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 +936,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 +953,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..f329e53e2 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,92 @@ 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-timeseries + Scenario Outline: Query TimeSeries samples and label metadata + Given a configured + When I query populated and empty time series through the Redis adapter + Then the TimeSeries queries return aligned samples and exclude empty series when requested + + @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 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_81_steps.py b/features/steps/redis_81_steps.py new file mode 100644 index 000000000..ba333a40c --- /dev/null +++ b/features/steps/redis_81_steps.py @@ -0,0 +1,313 @@ +"""Behavior of the redis-py 8.1 command surfaces exposed by ArchiPy.""" + +import asyncio +import inspect +import socket +from uuid import uuid4 + +from behave import then, use_step_matcher, when +from pydantic import ValidationError +from redis import Redis +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, TagFieldConfig, TextFieldConfig +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) + adapter = scenario.async_adapter or scenario.adapter + + async def run(): + 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("redis81", asyncio.run(run())) + + +@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 = get_current_scenario_context(context).get("redis81") + 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 = get_current_scenario_context(context).get("redis81") + assert result == [["1-0"]] * 4, result + + +def _series_names(reply): + if isinstance(reply, dict): + return set(reply) + return {name for series in reply for name in series} + + +@when("I query populated and empty time series through the Redis adapter") +def query_time_series(context): + async def exercise(adapter, token): + a, b, c, empty = f"{{a}}:{token}:ts:a", f"{{a}}:{token}:ts:b", f"{{b}}:{token}:ts:c", f"{{b}}:{token}:ts:empty" + series = adapter.client.ts() + await _call(series.add, a, 10, 2, labels={"probe": token, "signal": "first"}) + await _call(series.add, a, 20, 3) + await _call(series.add, b, 10, 4, labels={"probe": token, "signal": "second"}) + await _call(series.add, b, 20, 5) + await _call(series.add, c, 10, 6, labels={"probe": token, "signal": "third"}) + await _call(series.create, empty, labels={"probe": token, "signal": "empty"}) + filters = [f"probe={token}"] + sample = await _call(adapter.ts_read, a, 0, max_count=1) + values = await _call(adapter.ts_querylabels, label="signal", filters=filters) + forward = await _call(adapter.ts_nrange, [a, b], 0, 100) + reverse = await _call(adapter.ts_nrevrange, [a, b], 0, 100) + all_series = await _call(adapter.ts_mrange, 0, 100, filters) + without_empty = await _call(adapter.ts_mrange, 0, 100, filters, exclude_empty=True) + reverse_without_empty = await _call(adapter.ts_mrevrange, 0, 100, filters, exclude_empty=True) + return ( + list(sample[0]), + values, + forward, + reverse, + empty in _series_names(all_series), + _series_names(without_empty) == {a, b, c}, + _series_names(reverse_without_empty) == {a, b, c}, + ) + + _run(context, exercise) + + +@then("the TimeSeries queries return aligned samples and exclude empty series when requested") +def verify_time_series(context): + result = get_current_scenario_context(context).get("redis81") + head, labels, forward, reverse, *series_checks = result + assert head == [10, 2.0], result + assert labels == {"first", "second", "third", "empty"}, result + assert forward == [[10, [2.0, 4.0]], [20, [3.0, 5.0]]], result + assert reverse == list(reversed(forward)), result + assert all(series_checks), 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")]) + assert await _call(handle.create_index, schema, prefix) + try: + for suffix, value in (("a", "article"), ("b", "video"), ("c", "audiobook")): + assert await _call(handle.upsert_hash, prefix + suffix, {"kind": "book", "value": value}) + 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"], + collect_sort_by="value", + 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 = get_current_scenario_context(context).get("redis81") + 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"] for entry in entries] == [b"video", b"audiobook"], 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("redis81", error.errors()[0]["loc"]) + + +@then("the search aggregation is rejected") +def verify_unsupported_reducer(context): + assert get_current_scenario_context(context).get("redis81") == ("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("redis81:sentinel", "present") + assert adapter.get("redis81: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("redis81: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"redis81: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("redis81", value) + + +@then("the adapter learns the new owner and can read the migrated key") +def verify_migrated_key(context): + assert get_current_scenario_context(context).get("redis81") == "migrated" diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py b/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py index fd6a3b9ec..d5a3d68ce 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py @@ -36,6 +36,8 @@ AsyncRedisSortedSetsMixin, RedisSortedSetsMixin, ) +from archipy.adapters.redis.adapter_mixins.streams import AsyncRedisStreamsMixin, RedisStreamsMixin +from archipy.adapters.redis.adapter_mixins.time_series import AsyncRedisTimeSeriesMixin, RedisTimeSeriesMixin __all__ = [ "AsyncRedisArraysMixin", @@ -47,6 +49,8 @@ "AsyncRedisPubSubMixin", "AsyncRedisSetsMixin", "AsyncRedisSortedSetsMixin", + "AsyncRedisStreamsMixin", + "AsyncRedisTimeSeriesMixin", "RedisArraysMixin", "RedisClusterMixin", "RedisConnectionMixin", @@ -56,4 +60,6 @@ "RedisPubSubMixin", "RedisSetsMixin", "RedisSortedSetsMixin", + "RedisStreamsMixin", + "RedisTimeSeriesMixin", ] diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py b/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py index c432a2dd4..e973786b9 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py @@ -51,6 +51,8 @@ class RedisConnectionMixin(SyncRedisMixinBase): """Sync Redis mixin for connection operations.""" + _sentinel: Sentinel | None = None + def __init__(self, redis_config: RedisConfig | None = None) -> None: """Initialize the RedisAdapter with configuration settings. @@ -151,12 +153,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=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), ) @@ -270,6 +273,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,6 +334,8 @@ def config_get(self, pattern: str = "*") -> dict[str, str]: class AsyncRedisConnectionMixin(AsyncRedisMixinBase): """Async Redis mixin for connection operations.""" + _sentinel: AsyncSentinel | None = None + def __init__(self, redis_config: RedisConfig | None = None) -> None: """Initialize the AsyncRedisAdapter with configuration settings. @@ -429,12 +436,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), ) @@ -623,6 +631,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/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/sets.py b/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py index a25b95e73..94bc75fc5 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import Awaitable, Iterable, Iterator +from collections.abc import Awaitable, Iterable, Iterator, Sequence from archipy.adapters.redis.adapter_mixins._shared import ( AsyncRedisMixinBase, @@ -17,6 +17,27 @@ class RedisSetsMixin(SyncRedisMixinBase): """Sync Redis mixin for sets operations.""" + 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 +179,27 @@ def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]: class AsyncRedisSetsMixin(AsyncRedisMixinBase): """Async Redis mixin for sets operations.""" + 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/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/adapter_mixins/time_series.py b/packages/redis/archipy/adapters/redis/adapter_mixins/time_series.py new file mode 100644 index 000000000..3da18f375 --- /dev/null +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/time_series.py @@ -0,0 +1,197 @@ +"""Redis time series adapter methods.""" + +from __future__ import annotations + +from functools import partial +from typing import TYPE_CHECKING, Unpack + +from redis import RedisCluster +from redis.asyncio import RedisCluster as AsyncRedisCluster +from redis.exceptions import RedisClusterException + +from archipy.adapters.redis.adapter_mixins._shared import AsyncRedisMixinBase, SyncRedisMixinBase + +if TYPE_CHECKING: + from collections.abc import Iterable + + from redis.commands.timeseries import AsyncTimeSeries, TimeSeries + from redis.typing import KeyT, TimeSeriesMRangeResponse, TimeSeriesNRangeResponse, TimeSeriesRangeResponse + + from archipy.adapters.redis.port_mixins.time_series import TimeSeriesMRangeOptions, TimeSeriesNRangeOptions + + +class RedisTimeSeriesMixin(SyncRedisMixinBase): + """Synchronous Redis time series operations.""" + + def _time_series_query(self) -> TimeSeries: + """Route keyless queries through a primary, which coordinates all shards.""" + client = self.client + series = client.ts() + if isinstance(client, RedisCluster): + primaries = client.get_primaries() + if not primaries: + msg = "No Redis primary available for a TimeSeries query" + raise RedisClusterException(msg) + series.execute_command = partial(client.execute_command, target_nodes=primaries[0]) + return series + + def ts_read( + self, + key: KeyT, + timestamp: int | str, + *, + block_milliseconds: int | None = None, + block_min_count: int | None = None, + max_count: int | None = None, + ) -> TimeSeriesRangeResponse: + """Read samples after a timestamp, optionally blocking.""" + result = self.client.ts().read( + key, timestamp, block_milliseconds=block_milliseconds, block_min_count=block_min_count, max_count=max_count + ) + return result + + def ts_querylabels( + self, + *, + label: str | None = None, + filters: Iterable[str] | None = None, + ) -> set[bytes | str]: + """List matching label names or values for a requested label.""" + series = self._time_series_query() + result = series.querylabels(label=label, filters=filters) + return result + + def ts_nrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in ascending order.""" + result = self.client.ts().nrange(keys, from_time, to_time, **options) + return result + + def ts_nrevrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in descending order.""" + result = self.client.ts().nrevrange(keys, from_time, to_time, **options) + return result + + def ts_mrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in ascending order.""" + series = self._time_series_query() + result = series.mrange(from_time, to_time, filters, **options) + return result + + def ts_mrevrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in descending order.""" + series = self._time_series_query() + result = series.mrevrange(from_time, to_time, filters, **options) + return result + + +class AsyncRedisTimeSeriesMixin(AsyncRedisMixinBase): + """Asynchronous Redis time series operations.""" + + async def _time_series_query(self) -> AsyncTimeSeries: + """Route keyless queries through a primary, which coordinates all shards.""" + client = self.client + series = client.ts() + if isinstance(client, AsyncRedisCluster): + await client.initialize() + primaries = client.get_primaries() + if not primaries: + msg = "No Redis primary available for a TimeSeries query" + raise RedisClusterException(msg) + series.execute_command = partial(client.execute_command, target_nodes=primaries[0]) + return series + + async def ts_read( + self, + key: KeyT, + timestamp: int | str, + *, + block_milliseconds: int | None = None, + block_min_count: int | None = None, + max_count: int | None = None, + ) -> TimeSeriesRangeResponse: + """Read samples after a timestamp, optionally blocking.""" + result = self.client.ts().read( + key, timestamp, block_milliseconds=block_milliseconds, block_min_count=block_min_count, max_count=max_count + ) + return await result + + async def ts_querylabels( + self, + *, + label: str | None = None, + filters: Iterable[str] | None = None, + ) -> set[bytes | str]: + """List matching label names or values for a requested label.""" + series = await self._time_series_query() + result = series.querylabels(label=label, filters=filters) + return await result + + async def ts_nrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in ascending order.""" + result = self.client.ts().nrange(keys, from_time, to_time, **options) + return await result + + async def ts_nrevrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in descending order.""" + result = self.client.ts().nrevrange(keys, from_time, to_time, **options) + return await result + + async def ts_mrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in ascending order.""" + series = await self._time_series_query() + result = series.mrange(from_time, to_time, filters, **options) + return await result + + async def ts_mrevrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in descending order.""" + series = await self._time_series_query() + result = series.mrevrange(from_time, to_time, filters, **options) + return await result diff --git a/packages/redis/archipy/adapters/redis/adapters.py b/packages/redis/archipy/adapters/redis/adapters.py index d56e3b192..8d3391b77 100644 --- a/packages/redis/archipy/adapters/redis/adapters.py +++ b/packages/redis/archipy/adapters/redis/adapters.py @@ -12,6 +12,8 @@ AsyncRedisPubSubMixin, AsyncRedisSetsMixin, AsyncRedisSortedSetsMixin, + AsyncRedisStreamsMixin, + AsyncRedisTimeSeriesMixin, RedisArraysMixin, RedisClusterMixin, RedisConnectionMixin, @@ -21,6 +23,8 @@ RedisPubSubMixin, RedisSetsMixin, RedisSortedSetsMixin, + RedisStreamsMixin, + RedisTimeSeriesMixin, ) from archipy.adapters.redis.error_mapping import map_redis_errors from archipy.adapters.redis.ports import AsyncRedisPort, RedisPort @@ -38,6 +42,8 @@ class RedisAdapter( RedisListsMixin, RedisSetsMixin, RedisSortedSetsMixin, + RedisTimeSeriesMixin, + RedisStreamsMixin, RedisArraysMixin, RedisHashesMixin, RedisPubSubMixin, @@ -60,6 +66,8 @@ class AsyncRedisAdapter( AsyncRedisListsMixin, AsyncRedisSetsMixin, AsyncRedisSortedSetsMixin, + AsyncRedisTimeSeriesMixin, + 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..ed04c628b 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/__init__.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/__init__.py @@ -28,6 +28,8 @@ RedisScoreCastType, RedisSortedSetsPort, ) +from archipy.adapters.redis.port_mixins.streams import AsyncRedisStreamsPort, RedisStreamsPort +from archipy.adapters.redis.port_mixins.time_series import AsyncRedisTimeSeriesPort, RedisTimeSeriesPort __all__ = [ "AsyncRedisArraysPort", @@ -39,6 +41,8 @@ "AsyncRedisPubSubPort", "AsyncRedisSetsPort", "AsyncRedisSortedSetsPort", + "AsyncRedisStreamsPort", + "AsyncRedisTimeSeriesPort", "RedisArraysPort", "RedisClusterPort", "RedisConnectionPort", @@ -49,4 +53,6 @@ "RedisScoreCastType", "RedisSetsPort", "RedisSortedSetsPort", + "RedisStreamsPort", + "RedisTimeSeriesPort", ] 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/sets.py b/packages/redis/archipy/adapters/redis/port_mixins/sets.py index b36d66c31..c381c3ac4 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/sets.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/sets.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Iterator, Sequence from archipy.adapters.redis.async_iteration import AwaitableAsyncIterator @@ -16,6 +16,27 @@ class RedisSetsPort: """Sync Redis port for sets operations.""" + @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 +197,27 @@ def sunion(self, keys: bytes | str, *args: bytes | str) -> _set[bytes | str]: class AsyncRedisSetsPort: """Async Redis port for sets operations.""" + @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/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/port_mixins/time_series.py b/packages/redis/archipy/adapters/redis/port_mixins/time_series.py new file mode 100644 index 000000000..abd60c47d --- /dev/null +++ b/packages/redis/archipy/adapters/redis/port_mixins/time_series.py @@ -0,0 +1,188 @@ +"""Redis time series ports.""" + +from __future__ import annotations + +from abc import abstractmethod +from typing import TYPE_CHECKING, TypedDict, Unpack + +if TYPE_CHECKING: + from collections.abc import Iterable + + from redis.typing import KeyT, TimeSeriesMRangeResponse, TimeSeriesNRangeResponse, TimeSeriesRangeResponse + + +class TimeSeriesNRangeOptions(TypedDict, total=False): + """Optional arguments for a timestamp-aligned multi-key range query.""" + + count: int | None + aggregators: str | list[str] | None + bucket_size_msec: int | None + filter_by_ts: list[int] | None + filter_by_min_value: int | None + filter_by_max_value: int | None + align: int | str | None + latest: bool | None + bucket_timestamp: str | None + empty: bool | None + + +class TimeSeriesMRangeOptions(TypedDict, total=False): + """Optional arguments for a label-filtered range query.""" + + count: int | None + aggregation_type: str | list[str] | None + bucket_size_msec: int | None + with_labels: bool | None + filter_by_ts: list[int] | None + filter_by_min_value: int | None + filter_by_max_value: int | None + groupby: str | None + reduce: str | None + select_labels: list[str] | None + align: int | str | None + latest: bool | None + bucket_timestamp: str | None + empty: bool | None + exclude_empty: bool | None + + +class RedisTimeSeriesPort: + """Synchronous Redis time series operations.""" + + @abstractmethod + def ts_read( + self, + key: KeyT, + timestamp: int | str, + *, + block_milliseconds: int | None = None, + block_min_count: int | None = None, + max_count: int | None = None, + ) -> TimeSeriesRangeResponse: + """Read samples after a timestamp, optionally blocking.""" + raise NotImplementedError + + @abstractmethod + def ts_querylabels( + self, + *, + label: str | None = None, + filters: Iterable[str] | None = None, + ) -> set[bytes | str]: + """List matching label names or values for a requested label.""" + raise NotImplementedError + + @abstractmethod + def ts_nrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in ascending order.""" + raise NotImplementedError + + @abstractmethod + def ts_nrevrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in descending order.""" + raise NotImplementedError + + @abstractmethod + def ts_mrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in ascending order.""" + raise NotImplementedError + + @abstractmethod + def ts_mrevrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in descending order.""" + raise NotImplementedError + + +class AsyncRedisTimeSeriesPort: + """Asynchronous Redis time series operations.""" + + @abstractmethod + async def ts_read( + self, + key: KeyT, + timestamp: int | str, + *, + block_milliseconds: int | None = None, + block_min_count: int | None = None, + max_count: int | None = None, + ) -> TimeSeriesRangeResponse: + """Read samples after a timestamp, optionally blocking.""" + raise NotImplementedError + + @abstractmethod + async def ts_querylabels( + self, + *, + label: str | None = None, + filters: Iterable[str] | None = None, + ) -> set[bytes | str]: + """List matching label names or values for a requested label.""" + raise NotImplementedError + + @abstractmethod + async def ts_nrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in ascending order.""" + raise NotImplementedError + + @abstractmethod + async def ts_nrevrange( + self, + keys: list[KeyT], + from_time: int | str, + to_time: int | str, + **options: Unpack[TimeSeriesNRangeOptions], + ) -> TimeSeriesNRangeResponse: + """Read timestamp-aligned samples in descending order.""" + raise NotImplementedError + + @abstractmethod + async def ts_mrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in ascending order.""" + raise NotImplementedError + + @abstractmethod + async def ts_mrevrange( + self, + from_time: int | str, + to_time: int | str, + filters: list[str], + **options: Unpack[TimeSeriesMRangeOptions], + ) -> TimeSeriesMRangeResponse: + """Read series matching label filters in descending order.""" + raise NotImplementedError diff --git a/packages/redis/archipy/adapters/redis/ports.py b/packages/redis/archipy/adapters/redis/ports.py index 922f1b9a8..6f0d70fd9 100644 --- a/packages/redis/archipy/adapters/redis/ports.py +++ b/packages/redis/archipy/adapters/redis/ports.py @@ -12,6 +12,8 @@ AsyncRedisPubSubPort, AsyncRedisSetsPort, AsyncRedisSortedSetsPort, + AsyncRedisStreamsPort, + AsyncRedisTimeSeriesPort, RedisArraysPort, RedisClusterPort, RedisConnectionPort, @@ -22,6 +24,8 @@ RedisScoreCastType, RedisSetsPort, RedisSortedSetsPort, + RedisStreamsPort, + RedisTimeSeriesPort, ) __all__ = [ @@ -38,6 +42,8 @@ class RedisPort( RedisListsPort, RedisSetsPort, RedisSortedSetsPort, + RedisTimeSeriesPort, + RedisStreamsPort, RedisArraysPort, RedisHashesPort, RedisPubSubPort, @@ -56,6 +62,8 @@ class AsyncRedisPort( AsyncRedisListsPort, AsyncRedisSetsPort, AsyncRedisSortedSetsPort, + AsyncRedisTimeSeriesPort, + AsyncRedisStreamsPort, AsyncRedisArraysPort, AsyncRedisHashesPort, AsyncRedisPubSubPort, diff --git a/packages/redis/archipy/adapters/redis/search.py b/packages/redis/archipy/adapters/redis/search.py index 1c84352e5..08d69a5ff 100644 --- a/packages/redis/archipy/adapters/redis/search.py +++ b/packages/redis/archipy/adapters/redis/search.py @@ -13,7 +13,7 @@ from redis.commands.search.field import NumericField, TagField, TextField, VectorField 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 @@ -463,12 +463,20 @@ 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)) + 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 +702,11 @@ 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 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 +914,12 @@ 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 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..1f0ac199f 100644 --- a/packages/redis/archipy/adapters/redis/search_ports.py +++ b/packages/redis/archipy/adapters/redis/search_ports.py @@ -105,6 +105,11 @@ def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[str, Any """Execute a RediSearch aggregation.""" 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 +211,11 @@ async def aggregate(self, aggregation: AggregationDTO, **kwargs: Any) -> dict[st """Execute a RediSearch aggregation asynchronously.""" 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.""" From 27757f1ef197747bc2704fab13e892e9f8412693 Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 17:39:36 +0330 Subject: [PATCH 02/10] chore(deps): align redis and type stub minimums with the lockfile Raise the Redis adapter and three direct development requirements to the resolved versions while keeping their lower-bound constraints. Refs #641 --- packages/redis/pyproject.toml | 2 +- pyproject.toml | 6 +++--- uv.lock | 32 ++++++++++++++++---------------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/redis/pyproject.toml b/packages/redis/pyproject.toml index 4b7d71635..de6e889b1 100644 --- a/packages/redis/pyproject.toml +++ b/packages/redis/pyproject.toml @@ -9,7 +9,7 @@ version = "0.1.0" # This version is set on publish flow! requires-python = ">=3.14,<4" dependencies = [ "archipy==0.1.0", # Pinned to core version on publish flow! - "redis[hiredis]>=8.1.0", + "redis[hiredis]>=8.2.0", ] license = "Apache-2.0" diff --git a/pyproject.toml b/pyproject.toml index f89e21849..f61889314 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -125,9 +125,9 @@ dev = [ "pre-commit>=4.7.0", "ruff>=0.17.6", "ty>=0.0.108", - "types-grpcio>=1.85.0.20261028", - "types-protobuf>=7.35.1.20260906", - "types-pymysql>=1.2.4.20261116", + "types-grpcio>=1.85.0.20261122", + "types-protobuf>=7.35.1.20261122", + "types-pymysql>=1.2.4.20261122", "validate-pyproject>=0.27", ] diff --git a/uv.lock b/uv.lock index 0c1cf0f43..b9b2c1ea7 100644 --- a/uv.lock +++ b/uv.lock @@ -548,9 +548,9 @@ dev = [ { name = "pre-commit-hooks", specifier = ">=6.0.0" }, { name = "ruff", specifier = ">=0.17.6" }, { name = "ty", specifier = ">=0.0.108" }, - { name = "types-grpcio", specifier = ">=1.85.0.20261028" }, - { name = "types-protobuf", specifier = ">=7.35.1.20260906" }, - { name = "types-pymysql", specifier = ">=1.2.4.20261116" }, + { name = "types-grpcio", specifier = ">=1.85.0.20261122" }, + { name = "types-protobuf", specifier = ">=7.35.1.20261122" }, + { name = "types-pymysql", specifier = ">=1.2.4.20261122" }, { name = "validate-pyproject", specifier = ">=0.27" }, ] docs = [ @@ -709,7 +709,7 @@ dependencies = [ [package.metadata] requires-dist = [ { name = "archipy", editable = "." }, - { name = "redis", extras = ["hiredis"], specifier = ">=8.1.0" }, + { name = "redis", extras = ["hiredis"], specifier = ">=8.2.0" }, ] [[package]] @@ -3789,11 +3789,11 @@ wheels = [ [[package]] name = "redis" -version = "8.1.0" +version = "8.2.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a8/99/604f0b666d4c616d891cf77ebb9db6bb21601344c051aebf1b72b9ff915f/redis-8.1.0.tar.gz", hash = "sha256:6e1a19beef9225c83efd689c7e6b7da2d5215b1f42cd13b7fc3714d0a09c7b25", size = 5254356, upload-time = "2026-07-30T08:51:00.269Z" } +sdist = { url = "https://files.pythonhosted.org/packages/10/8a/408dd829367bb62972bd5d91bd8cc283c24c8344f80a880d4b3901ce43fd/redis-8.2.0.tar.gz", hash = "sha256:58b1493d83ba8f0e3ffe6bd781194ca5c01c91267ae03d29c1087b0b3c7d79c9", size = 5809579, upload-time = "2026-11-23T08:31:56.692Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/66/9d/c5731f6e3608663d4d3656fd8d3aecee8b509c3082818f5a13eae925baea/redis-8.1.0-py3-none-any.whl", hash = "sha256:a4fe1aac3d3b3cc791d4b3d5931c5a956045dc951ee74d1c913ee3ac4d2ee9fb", size = 560618, upload-time = "2026-07-30T08:50:58.497Z" }, + { url = "https://files.pythonhosted.org/packages/ea/8f/98458650cca985032598a59caca0641e7889cf4d536dc12dc032bef7df47/redis-8.2.0-py3-none-any.whl", hash = "sha256:4ff649f10fae5e7e97798fb2a84e84a0a66e98310d75cad2b5a572ce0f9f15a7", size = 732892, upload-time = "2026-11-23T08:31:55.011Z" }, ] [package.optional-dependencies] @@ -4321,29 +4321,29 @@ wheels = [ [[package]] name = "types-grpcio" -version = "1.85.0.20261028" +version = "1.85.0.20261122" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/6b/5248f1b10df2c02ffbd99f3c913259bf73cabd2bee0ca1c28d6f3e66c3f4/types_grpcio-1.85.0.20261028.tar.gz", hash = "sha256:4ea4f36a54cf9a62fcb09515f7305e89c01f4edca54b32de24f6b1204b84522c", size = 16127, upload-time = "2026-10-28T07:38:58.025Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e6/0f/61dc0d3fa50011cfae5a3247ff92558e53925ab1bef9792d061c1d91a481/types_grpcio-1.85.0.20261122.tar.gz", hash = "sha256:2541b5f1093b15649ba6621fa8ebfe18de1c0b6d75c5ebd3529c7d0d359efccf", size = 16156, upload-time = "2026-11-22T08:58:14.928Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/ee/e2b2f2d677478456869ca922c1d5bb68f64052c9dfd9ad6c2a91a1122269/types_grpcio-1.85.0.20261028-py3-none-any.whl", hash = "sha256:2c2684330ae57ab64ffb43183ac652e73d2609024e6076e3e9d2b8ae06816207", size = 16076, upload-time = "2026-10-28T07:38:57.193Z" }, + { url = "https://files.pythonhosted.org/packages/00/ad/2fe9e5f0ece134e650838f2c3673e6af64c666ab4f8310326566779c0140/types_grpcio-1.85.0.20261122-py3-none-any.whl", hash = "sha256:8e204a0760dbfa41b0b9066abad584027a032cc5930e13a6a772801771c4b942", size = 16101, upload-time = "2026-11-22T08:58:14.116Z" }, ] [[package]] name = "types-protobuf" -version = "7.35.1.20260906" +version = "7.35.1.20261122" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e1/6c/e3e5b3e10bc328126a39637c138f9ebfd734bf14342b9f3540039b4ab995/types_protobuf-7.35.1.20260906.tar.gz", hash = "sha256:efd1a3862d4c967dad5512ef8d56b1530ac84f182c41735b94004756518c4998", size = 69895, upload-time = "2026-09-06T06:35:28.308Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2b/01/2b04865447656eeb92eb075e42c221d6a2262aef89ccc2053d556381404a/types_protobuf-7.35.1.20261122.tar.gz", hash = "sha256:705644f0c8618252eacf878047dc649b875eb8f4b7518df336513173334a1976", size = 69901, upload-time = "2026-11-22T08:57:48.005Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/44/4e/f63e826c68f77ef875506d72f225918800346545ee99847bc28f3394f18d/types_protobuf-7.35.1.20260906-py3-none-any.whl", hash = "sha256:5155e48569e0dabff303fdf578db96cd31ea9a4a63b18018a4ceac6b0ae17462", size = 86419, upload-time = "2026-09-06T06:35:27.247Z" }, + { url = "https://files.pythonhosted.org/packages/cc/9c/1f3c4f73b50db06a1ec4f1c76d696738d5bbe3c85966abfc3f7ac8bdd83c/types_protobuf-7.35.1.20261122-py3-none-any.whl", hash = "sha256:b4e002599d9d7e8e377dd0faa5e70d133081148a0e370ba920f93c402526ed90", size = 86471, upload-time = "2026-11-22T08:57:46.937Z" }, ] [[package]] name = "types-pymysql" -version = "1.2.4.20261116" +version = "1.2.4.20261122" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9b/5f/5c75921a6347614498a5a7ba9e8d0bd511eafcfcffd69d346508765b421b/types_pymysql-1.2.4.20261116.tar.gz", hash = "sha256:f3ac18c67025589cb9118afe58d0c46ea50dae9ffac6f7c83030a2456b39c549", size = 23084, upload-time = "2026-11-16T08:43:05.42Z" } +sdist = { url = "https://files.pythonhosted.org/packages/46/bc/76d0dd75c73f9de9924b79551a2d926041aab02485ac4382a1ec8b8cba95/types_pymysql-1.2.4.20261122.tar.gz", hash = "sha256:fcd8a185893a81358154647645f2990d8fef45a31c7bc99446f57bb54c891418", size = 23145, upload-time = "2026-11-22T08:57:18.28Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5a/be/ad88550f6aa77c3497c522d02ea08f9f634b673e03497ad4a1b908f43570/types_pymysql-1.2.4.20261116-py3-none-any.whl", hash = "sha256:9bfa6dad28311fa1f674ce7d26c3435c7f33c86a636d4d6a28a1097dd42cc750", size = 23462, upload-time = "2026-11-16T08:43:04.383Z" }, + { url = "https://files.pythonhosted.org/packages/bb/7b/01cabf1c90ab0c7d4444ca40c1583e8d54662ae024b9b7aab99b6f256775/types_pymysql-1.2.4.20261122-py3-none-any.whl", hash = "sha256:e37bd5b3e187973e983e29a8d522bd9e3d71569d1c2abab24374745fe2696f7e", size = 23497, upload-time = "2026-11-22T08:57:17.498Z" }, ] [[package]] From 0809bee9ee9e7ce206ed6592792558c27944cdb1 Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 18:31:01 +0330 Subject: [PATCH 03/10] fix(redis): use fakeredis with redis-py 8.2 support Fakeredis 2.40.0 fails to initialize sync and async mock clients with redis-py 8.2.0. Use the upstream 2.41.0 release and update the Redis adapter guide to reflect the integration test coverage. Refs #641 --- docs/tutorials/adapters/redis.md | 2 +- pyproject.toml | 2 +- uv.lock | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/tutorials/adapters/redis.md b/docs/tutorials/adapters/redis.md index 346c7d77d..caeac7f1a 100644 --- a/docs/tutorials/adapters/redis.md +++ b/docs/tutorials/adapters/redis.md @@ -298,7 +298,7 @@ Create the consumer group before calling `xreadgroup`. Stream reply shapes follo TimeSeries queries by label are coordinated by Redis across the cluster. `exclude_empty` omits series that have no returned samples and is incompatible with `groupby`. -Use real Redis to test stream limits and RediSearch. Fakeredis 2.40.0 lacks those behaviors. +The stream-limit and RediSearch integration scenarios run against real Redis. ### Experimental hash fieldsets diff --git a/pyproject.toml b/pyproject.toml index f61889314..062e18098 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ cache = [ dependency-injection = ["dependency-injector>=4.49.1"] elasticsearch = ["archipy-elasticsearch==0.1.0"] # Pinned to core version on publish flow! elasticsearch-async = ["archipy-elasticsearch==0.1.0", "elasticsearch[async]>=9.5.1"] # Pinned to core version on publish flow! -fakeredis = ["fakeredis>=2.40.0"] +fakeredis = ["fakeredis>=2.41.0"] fastapi = [ "fastapi[all]>=0.165.0", ] diff --git a/uv.lock b/uv.lock index b9b2c1ea7..eb04a814c 100644 --- a/uv.lock +++ b/uv.lock @@ -503,7 +503,7 @@ requires-dist = [ { name = "cachetools", marker = "extra == 'cache'", specifier = ">=8.0.2" }, { name = "dependency-injector", marker = "extra == 'dependency-injection'", specifier = ">=4.49.1" }, { name = "elasticsearch", extras = ["async"], marker = "extra == 'elasticsearch-async'", specifier = ">=9.5.1" }, - { name = "fakeredis", marker = "extra == 'fakeredis'", specifier = ">=2.40.0" }, + { name = "fakeredis", marker = "extra == 'fakeredis'", specifier = ">=2.41.0" }, { name = "fastapi", extras = ["all"], marker = "extra == 'fastapi'", specifier = ">=0.165.0" }, { name = "grpcio", marker = "extra == 'grpc'", specifier = ">=1.85.3" }, { name = "grpcio-health-checking", marker = "extra == 'grpc'", specifier = ">=1.85.3" }, @@ -1564,15 +1564,15 @@ wheels = [ [[package]] name = "fakeredis" -version = "2.40.0" +version = "2.41.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "redis" }, { name = "sortedcontainers" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/61/d0/8cbd1339c2a606a0ceda74e1a181248d372bb2c66bc6cf9d954871839ff9/fakeredis-2.40.0.tar.gz", hash = "sha256:16eb05a3e97c37a033c73d1da7e885eb2aa47ba7604cc377144339efa2780a02", size = 332674, upload-time = "2026-10-14T12:46:01.851Z" } +sdist = { url = "https://files.pythonhosted.org/packages/8e/74/1d78df11d3c168a7fe4e11315e77b762c1f89b8ddeaeb0f0486c55fd64cd/fakeredis-2.41.0.tar.gz", hash = "sha256:a10d97197e6c6e9e98affc10abba9fb0efa9bc5671bbc425dca7f47063c2c577", size = 351444, upload-time = "2026-11-23T14:47:49.136Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c7/e4/6919d3653d72c53d1fb22c97ceb6fa3664cad302994e90ee52279f7eb394/fakeredis-2.40.0-py3-none-any.whl", hash = "sha256:b155ef2442134372eb1cc5664cf5638ccbe0a6dde9d1942153708e2782f315c9", size = 204148, upload-time = "2026-10-14T12:46:00.014Z" }, + { url = "https://files.pythonhosted.org/packages/3a/47/1a20be7813c4f079b478d9d2c54fcfc4178062a3acd028dd289cdced3904/fakeredis-2.41.0-py3-none-any.whl", hash = "sha256:9a2bb58889e8bf646b991324ac4d226a3ae74a3bdde7b6e533c7072c853f236e", size = 211330, upload-time = "2026-11-23T14:47:47.667Z" }, ] [[package]] From 52676c58f6cecaba45110d75d234e048b7069b9e Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 18:43:50 +0330 Subject: [PATCH 04/10] ci: check repository links from the checkout --- .github/workflows/link-check.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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 From fc9289822f2b77a297f3ccbbbb39902cdd4265be Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 19:02:53 +0330 Subject: [PATCH 05/10] fix(redis): stabilize Search COLLECT aggregation Load reducer fields before grouping and wait for the test documents to be indexed before asserting rank order. Refs #641 --- features/steps/redis_81_steps.py | 24 +++++++++++++++---- .../redis/archipy/adapters/redis/search.py | 7 ++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/features/steps/redis_81_steps.py b/features/steps/redis_81_steps.py index ba333a40c..2dfd42870 100644 --- a/features/steps/redis_81_steps.py +++ b/features/steps/redis_81_steps.py @@ -3,6 +3,7 @@ import asyncio import inspect import socket +from time import monotonic from uuid import uuid4 from behave import then, use_step_matcher, when @@ -15,7 +16,12 @@ 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, TagFieldConfig, TextFieldConfig +from archipy.models.dtos.redis.search.index_schema_dto import ( + IndexSchemaDTO, + NumericFieldConfig, + TagFieldConfig, + TextFieldConfig, +) from features.test_containers import ContainerManager from features.test_helpers import get_current_scenario_context @@ -157,11 +163,19 @@ 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")]) + schema = IndexSchemaDTO( + fields=[TagFieldConfig(name="kind"), TextFieldConfig(name="value"), NumericFieldConfig(name="rank")] + ) assert await _call(handle.create_index, schema, prefix) try: - for suffix, value in (("a", "article"), ("b", "video"), ("c", "audiobook")): - assert await _call(handle.upsert_hash, prefix + suffix, {"kind": "book", "value": value}) + 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} + ) + deadline = monotonic() + 3 + while int((await _call(handle.info))["num_docs"]) < len(values): + assert monotonic() < deadline, "RediSearch did not index all three documents" alias = f"alias-{token}" assert await _call(handle.add_alias, alias) aliases = await _call(handle.list_aliases) @@ -172,7 +186,7 @@ async def exercise(adapter, token): reduce_field="entries", reduce_function="COLLECT", collect_fields=["value"], - collect_sort_by="value", + collect_sort_by="rank", collect_sort_direction="DESC", collect_limit=(0, 2), ), diff --git a/packages/redis/archipy/adapters/redis/search.py b/packages/redis/archipy/adapters/redis/search.py index 08d69a5ff..5b2295e22 100644 --- a/packages/redis/archipy/adapters/redis/search.py +++ b/packages/redis/archipy/adapters/redis/search.py @@ -475,6 +475,13 @@ def _build_aggregate_request(aggregation: AggregationDTO) -> AggregateRequest: 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) From a6f4bc1aba79650067b117ec3bfd3d16b935fa3f Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 19:03:22 +0330 Subject: [PATCH 06/10] feat(redis): expose redis-py 8.2 capabilities Add typed sync and async command support, optional cache and cluster routing configuration, and integration coverage on Redis 8.12. Refs #641 --- .env.test | 2 +- archipy/configs/sections/redis.py | 21 +- docs/tutorials/adapters/redis.md | 62 +++ features/redis_adapter.feature | 149 +++++++ features/steps/redis_capability_steps.py | 411 ++++++++++++++++++ features/test_containers.py | 3 +- .../adapters/redis/adapter_mixins/_shared.py | 8 +- .../redis/adapter_mixins/connection.py | 132 +++++- .../adapters/redis/adapter_mixins/keys.py | 47 ++ .../adapters/redis/adapter_mixins/pubsub.py | 8 + .../adapters/redis/adapter_mixins/sets.py | 181 ++++++++ .../redis/adapter_mixins/sorted_sets.py | 78 ++++ .../adapters/redis/port_mixins/connection.py | 99 +++++ .../adapters/redis/port_mixins/keys.py | 57 +++ .../adapters/redis/port_mixins/pubsub.py | 10 + .../adapters/redis/port_mixins/sets.py | 195 +++++++++ .../adapters/redis/port_mixins/sorted_sets.py | 88 +++- .../redis/archipy/adapters/redis/search.py | 60 +++ .../archipy/adapters/redis/search_ports.py | 38 ++ 19 files changed, 1634 insertions(+), 15 deletions(-) create mode 100644 features/steps/redis_capability_steps.py diff --git a/.env.test b/.env.test index 6a9a06729..bbf6e7c61 100644 --- a/.env.test +++ b/.env.test @@ -1,7 +1,7 @@ # Container Images TESTCONTAINERS_RYUK_CONTAINER_IMAGE=testcontainers/ryuk:0.14.0 TEMPORAL__IMAGE=temporalio/temporal:1.10.1 -REDIS__IMAGE=redis:8.10.3-alpine +REDIS__IMAGE=ghcr.io/redis/docker-library-redis:8.12.0-alpine POSTGRES__IMAGE=postgres:18.7-alpine MYSQL__IMAGE=mysql:8.4.13 STARROCKS__IMAGE=starrocks/allin1-ubuntu:4.1.8 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/docs/tutorials/adapters/redis.md b/docs/tutorials/adapters/redis.md index caeac7f1a..b5d4b7688 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" @@ -190,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 @@ -300,6 +334,28 @@ no returned samples and is incompatible with `groupby`. 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. @@ -317,6 +373,8 @@ finally: ### 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 @@ -868,6 +926,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`: diff --git a/features/redis_adapter.feature b/features/redis_adapter.feature index f329e53e2..01f42a96f 100644 --- a/features/redis_adapter.feature +++ b/features/redis_adapter.feature @@ -1748,3 +1748,152 @@ Feature: Redis Testing 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/steps/redis_capability_steps.py b/features/steps/redis_capability_steps.py new file mode 100644 index 000000000..56f72416e --- /dev/null +++ b/features/steps/redis_capability_steps.py @@ -0,0 +1,411 @@ +"""Behavior of the Redis adapters' newer Redis command and connection capabilities.""" + +import asyncio +import inspect +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 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 +from archipy.models.dtos.redis.search.index_schema_dto import IndexSchemaDTO, TextFieldConfig, VectorFieldConfig +from archipy.models.errors import CacheError +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}) + 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) diff --git a/features/test_containers.py b/features/test_containers.py index 25e8b4dec..3841e40e2 100644 --- a/features/test_containers.py +++ b/features/test_containers.py @@ -349,7 +349,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/_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 e973786b9..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,17 +56,69 @@ class RedisConnectionMixin(SyncRedisMixinBase): """Sync Redis mixin for connection operations.""" + 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) -> 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) @@ -91,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) @@ -126,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, @@ -164,8 +224,7 @@ def _set_sentinel_clients(self, configs: RedisConfig) -> None: **_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: @@ -180,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), ) @@ -213,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, @@ -334,17 +398,66 @@ def config_get(self, pattern: str = "*") -> dict[str, str]: class AsyncRedisConnectionMixin(AsyncRedisMixinBase): """Async Redis mixin for connection operations.""" + 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) -> 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) @@ -374,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) @@ -409,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, @@ -463,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), ) @@ -496,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, 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/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 94bc75fc5..3eac8c688 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/sets.py @@ -3,6 +3,7 @@ from __future__ import annotations 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,102 @@ 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], @@ -179,6 +272,94 @@ 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], 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/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/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 c381c3ac4..321e27d7c 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/sets.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/sets.py @@ -8,6 +8,9 @@ if TYPE_CHECKING: 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 _set = set @@ -16,6 +19,102 @@ 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, @@ -197,6 +296,102 @@ 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, 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/search.py b/packages/redis/archipy/adapters/redis/search.py index 5b2295e22..aaaf64dfd 100644 --- a/packages/redis/archipy/adapters/redis/search.py +++ b/packages/redis/archipy/adapters/redis/search.py @@ -11,6 +11,7 @@ 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 collect as agg_collect, count as agg_count @@ -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 ( @@ -709,6 +717,32 @@ 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.""" @@ -921,6 +955,32 @@ 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.""" diff --git a/packages/redis/archipy/adapters/redis/search_ports.py b/packages/redis/archipy/adapters/redis/search_ports.py index 1f0ac199f..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,21 @@ 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.""" @@ -211,6 +234,21 @@ 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.""" From afb32945ff258609eab18e0599abecaa8cee4645 Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 19:13:16 +0330 Subject: [PATCH 07/10] test(redis): wait for the initial Search index scan Seed the aggregation data before creating the index and wait until indexing finishes before checking the ordered reducer output. Refs #641 --- features/steps/redis_81_steps.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/features/steps/redis_81_steps.py b/features/steps/redis_81_steps.py index 2dfd42870..4449738ba 100644 --- a/features/steps/redis_81_steps.py +++ b/features/steps/redis_81_steps.py @@ -164,18 +164,23 @@ 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")] + 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: - 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} - ) deadline = monotonic() + 3 - while int((await _call(handle.info))["num_docs"]) < len(values): - assert monotonic() < deadline, "RediSearch did not index all three documents" + 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) @@ -185,7 +190,7 @@ async def exercise(adapter, token): group_by=["kind"], reduce_field="entries", reduce_function="COLLECT", - collect_fields=["value"], + collect_fields=["value", "rank"], collect_sort_by="rank", collect_sort_direction="DESC", collect_limit=(0, 2), @@ -206,7 +211,7 @@ def verify_alias_and_collection(context): (row,) = result["rows"] attributes = row.get(b"extra_attributes", row) entries = attributes[b"entries"] - assert [entry[b"value"] for entry in entries] == [b"video", b"audiobook"], result + 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[^"]+)"') From 60758042e0499f23da2f8fdc07aa884531859ecb Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 19:44:58 +0330 Subject: [PATCH 08/10] refactor(redis): drop the TimeSeries command surface Keyless TimeSeries cluster queries required monkeypatching the redis-py command object. Remove the mixin, ports, docs, and scenarios instead of keeping that workaround. Refs #641 --- docs/tutorials/adapters/redis.md | 13 +- features/redis_adapter.feature | 18 -- features/steps/redis_81_steps.py | 53 +---- .../adapters/redis/adapter_mixins/__init__.py | 3 - .../redis/adapter_mixins/time_series.py | 197 ------------------ .../redis/archipy/adapters/redis/adapters.py | 4 - .../adapters/redis/port_mixins/__init__.py | 3 - .../adapters/redis/port_mixins/time_series.py | 188 ----------------- .../redis/archipy/adapters/redis/ports.py | 4 - 9 files changed, 4 insertions(+), 479 deletions(-) delete mode 100644 packages/redis/archipy/adapters/redis/adapter_mixins/time_series.py delete mode 100644 packages/redis/archipy/adapters/redis/port_mixins/time_series.py diff --git a/docs/tutorials/adapters/redis.md b/docs/tutorials/adapters/redis.md index b5d4b7688..59d9fa1e5 100644 --- a/docs/tutorials/adapters/redis.md +++ b/docs/tutorials/adapters/redis.md @@ -304,10 +304,10 @@ logger.info(f"Second call (cached): {result2}") ## Advanced Redis Features -### List batches, set cardinality, streams, and TimeSeries +### 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, stream, or `TS.NRANGE` operation on Redis Cluster. +for keys in a multi-key list, set, or stream operation on Redis Cluster. ```python redis_adapter.rpush("{tasks}:ready", "a", "b", "c") @@ -318,19 +318,10 @@ 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) - -redis_adapter.ts_read("{room}:temperature", 0, max_count=10) -redis_adapter.ts_nrange(["{room}:temperature", "{room}:humidity"], "-", "+") -redis_adapter.ts_nrevrange(["{room}:temperature", "{room}:humidity"], "-", "+") -redis_adapter.ts_querylabels(label="location", filters=["type=sensor"]) -redis_adapter.ts_mrange("-", "+", ["type=sensor"], exclude_empty=True) -redis_adapter.ts_mrevrange("-", "+", ["type=sensor"], exclude_empty=True) ``` `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. -TimeSeries queries by label are coordinated by Redis across the cluster. `exclude_empty` omits series that have -no returned samples and is incompatible with `groupby`. The stream-limit and RediSearch integration scenarios run against real Redis. diff --git a/features/redis_adapter.feature b/features/redis_adapter.feature index 01f42a96f..f6d594111 100644 --- a/features/redis_adapter.feature +++ b/features/redis_adapter.feature @@ -1698,24 +1698,6 @@ Feature: Redis Testing | async container | | async cluster | - @redis-timeseries - Scenario Outline: Query TimeSeries samples and label metadata - Given a configured - When I query populated and empty time series through the Redis adapter - Then the TimeSeries queries return aligned samples and exclude empty series when requested - - @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 diff --git a/features/steps/redis_81_steps.py b/features/steps/redis_81_steps.py index 4449738ba..069239f73 100644 --- a/features/steps/redis_81_steps.py +++ b/features/steps/redis_81_steps.py @@ -109,55 +109,6 @@ def verify_stream_limits(context): assert result == [["1-0"]] * 4, result -def _series_names(reply): - if isinstance(reply, dict): - return set(reply) - return {name for series in reply for name in series} - - -@when("I query populated and empty time series through the Redis adapter") -def query_time_series(context): - async def exercise(adapter, token): - a, b, c, empty = f"{{a}}:{token}:ts:a", f"{{a}}:{token}:ts:b", f"{{b}}:{token}:ts:c", f"{{b}}:{token}:ts:empty" - series = adapter.client.ts() - await _call(series.add, a, 10, 2, labels={"probe": token, "signal": "first"}) - await _call(series.add, a, 20, 3) - await _call(series.add, b, 10, 4, labels={"probe": token, "signal": "second"}) - await _call(series.add, b, 20, 5) - await _call(series.add, c, 10, 6, labels={"probe": token, "signal": "third"}) - await _call(series.create, empty, labels={"probe": token, "signal": "empty"}) - filters = [f"probe={token}"] - sample = await _call(adapter.ts_read, a, 0, max_count=1) - values = await _call(adapter.ts_querylabels, label="signal", filters=filters) - forward = await _call(adapter.ts_nrange, [a, b], 0, 100) - reverse = await _call(adapter.ts_nrevrange, [a, b], 0, 100) - all_series = await _call(adapter.ts_mrange, 0, 100, filters) - without_empty = await _call(adapter.ts_mrange, 0, 100, filters, exclude_empty=True) - reverse_without_empty = await _call(adapter.ts_mrevrange, 0, 100, filters, exclude_empty=True) - return ( - list(sample[0]), - values, - forward, - reverse, - empty in _series_names(all_series), - _series_names(without_empty) == {a, b, c}, - _series_names(reverse_without_empty) == {a, b, c}, - ) - - _run(context, exercise) - - -@then("the TimeSeries queries return aligned samples and exclude empty series when requested") -def verify_time_series(context): - result = get_current_scenario_context(context).get("redis81") - head, labels, forward, reverse, *series_checks = result - assert head == [10, 2.0], result - assert labels == {"first", "second", "third", "empty"}, result - assert forward == [[10, [2.0, 4.0]], [20, [3.0, 5.0]]], result - assert reverse == list(reversed(forward)), result - assert all(series_checks), 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): @@ -168,7 +119,7 @@ async def exercise(adapter, token): TagFieldConfig(name="kind"), TextFieldConfig(name="value"), NumericFieldConfig(name="rank"), - ] + ], ) values = ("article", "audiobook", "video") for rank, value in enumerate(values): @@ -270,7 +221,7 @@ async def check_async_sentinel(): 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) + "sentinel_clients", (initial, sync_during, sync_after, async_during, async_after), ) diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py b/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py index d5a3d68ce..90772ee19 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/__init__.py @@ -37,7 +37,6 @@ RedisSortedSetsMixin, ) from archipy.adapters.redis.adapter_mixins.streams import AsyncRedisStreamsMixin, RedisStreamsMixin -from archipy.adapters.redis.adapter_mixins.time_series import AsyncRedisTimeSeriesMixin, RedisTimeSeriesMixin __all__ = [ "AsyncRedisArraysMixin", @@ -50,7 +49,6 @@ "AsyncRedisSetsMixin", "AsyncRedisSortedSetsMixin", "AsyncRedisStreamsMixin", - "AsyncRedisTimeSeriesMixin", "RedisArraysMixin", "RedisClusterMixin", "RedisConnectionMixin", @@ -61,5 +59,4 @@ "RedisSetsMixin", "RedisSortedSetsMixin", "RedisStreamsMixin", - "RedisTimeSeriesMixin", ] diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/time_series.py b/packages/redis/archipy/adapters/redis/adapter_mixins/time_series.py deleted file mode 100644 index 3da18f375..000000000 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/time_series.py +++ /dev/null @@ -1,197 +0,0 @@ -"""Redis time series adapter methods.""" - -from __future__ import annotations - -from functools import partial -from typing import TYPE_CHECKING, Unpack - -from redis import RedisCluster -from redis.asyncio import RedisCluster as AsyncRedisCluster -from redis.exceptions import RedisClusterException - -from archipy.adapters.redis.adapter_mixins._shared import AsyncRedisMixinBase, SyncRedisMixinBase - -if TYPE_CHECKING: - from collections.abc import Iterable - - from redis.commands.timeseries import AsyncTimeSeries, TimeSeries - from redis.typing import KeyT, TimeSeriesMRangeResponse, TimeSeriesNRangeResponse, TimeSeriesRangeResponse - - from archipy.adapters.redis.port_mixins.time_series import TimeSeriesMRangeOptions, TimeSeriesNRangeOptions - - -class RedisTimeSeriesMixin(SyncRedisMixinBase): - """Synchronous Redis time series operations.""" - - def _time_series_query(self) -> TimeSeries: - """Route keyless queries through a primary, which coordinates all shards.""" - client = self.client - series = client.ts() - if isinstance(client, RedisCluster): - primaries = client.get_primaries() - if not primaries: - msg = "No Redis primary available for a TimeSeries query" - raise RedisClusterException(msg) - series.execute_command = partial(client.execute_command, target_nodes=primaries[0]) - return series - - def ts_read( - self, - key: KeyT, - timestamp: int | str, - *, - block_milliseconds: int | None = None, - block_min_count: int | None = None, - max_count: int | None = None, - ) -> TimeSeriesRangeResponse: - """Read samples after a timestamp, optionally blocking.""" - result = self.client.ts().read( - key, timestamp, block_milliseconds=block_milliseconds, block_min_count=block_min_count, max_count=max_count - ) - return result - - def ts_querylabels( - self, - *, - label: str | None = None, - filters: Iterable[str] | None = None, - ) -> set[bytes | str]: - """List matching label names or values for a requested label.""" - series = self._time_series_query() - result = series.querylabels(label=label, filters=filters) - return result - - def ts_nrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in ascending order.""" - result = self.client.ts().nrange(keys, from_time, to_time, **options) - return result - - def ts_nrevrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in descending order.""" - result = self.client.ts().nrevrange(keys, from_time, to_time, **options) - return result - - def ts_mrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in ascending order.""" - series = self._time_series_query() - result = series.mrange(from_time, to_time, filters, **options) - return result - - def ts_mrevrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in descending order.""" - series = self._time_series_query() - result = series.mrevrange(from_time, to_time, filters, **options) - return result - - -class AsyncRedisTimeSeriesMixin(AsyncRedisMixinBase): - """Asynchronous Redis time series operations.""" - - async def _time_series_query(self) -> AsyncTimeSeries: - """Route keyless queries through a primary, which coordinates all shards.""" - client = self.client - series = client.ts() - if isinstance(client, AsyncRedisCluster): - await client.initialize() - primaries = client.get_primaries() - if not primaries: - msg = "No Redis primary available for a TimeSeries query" - raise RedisClusterException(msg) - series.execute_command = partial(client.execute_command, target_nodes=primaries[0]) - return series - - async def ts_read( - self, - key: KeyT, - timestamp: int | str, - *, - block_milliseconds: int | None = None, - block_min_count: int | None = None, - max_count: int | None = None, - ) -> TimeSeriesRangeResponse: - """Read samples after a timestamp, optionally blocking.""" - result = self.client.ts().read( - key, timestamp, block_milliseconds=block_milliseconds, block_min_count=block_min_count, max_count=max_count - ) - return await result - - async def ts_querylabels( - self, - *, - label: str | None = None, - filters: Iterable[str] | None = None, - ) -> set[bytes | str]: - """List matching label names or values for a requested label.""" - series = await self._time_series_query() - result = series.querylabels(label=label, filters=filters) - return await result - - async def ts_nrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in ascending order.""" - result = self.client.ts().nrange(keys, from_time, to_time, **options) - return await result - - async def ts_nrevrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in descending order.""" - result = self.client.ts().nrevrange(keys, from_time, to_time, **options) - return await result - - async def ts_mrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in ascending order.""" - series = await self._time_series_query() - result = series.mrange(from_time, to_time, filters, **options) - return await result - - async def ts_mrevrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in descending order.""" - series = await self._time_series_query() - result = series.mrevrange(from_time, to_time, filters, **options) - return await result diff --git a/packages/redis/archipy/adapters/redis/adapters.py b/packages/redis/archipy/adapters/redis/adapters.py index 8d3391b77..f0f151875 100644 --- a/packages/redis/archipy/adapters/redis/adapters.py +++ b/packages/redis/archipy/adapters/redis/adapters.py @@ -13,7 +13,6 @@ AsyncRedisSetsMixin, AsyncRedisSortedSetsMixin, AsyncRedisStreamsMixin, - AsyncRedisTimeSeriesMixin, RedisArraysMixin, RedisClusterMixin, RedisConnectionMixin, @@ -24,7 +23,6 @@ RedisSetsMixin, RedisSortedSetsMixin, RedisStreamsMixin, - RedisTimeSeriesMixin, ) from archipy.adapters.redis.error_mapping import map_redis_errors from archipy.adapters.redis.ports import AsyncRedisPort, RedisPort @@ -42,7 +40,6 @@ class RedisAdapter( RedisListsMixin, RedisSetsMixin, RedisSortedSetsMixin, - RedisTimeSeriesMixin, RedisStreamsMixin, RedisArraysMixin, RedisHashesMixin, @@ -66,7 +63,6 @@ class AsyncRedisAdapter( AsyncRedisListsMixin, AsyncRedisSetsMixin, AsyncRedisSortedSetsMixin, - AsyncRedisTimeSeriesMixin, AsyncRedisStreamsMixin, AsyncRedisArraysMixin, AsyncRedisHashesMixin, diff --git a/packages/redis/archipy/adapters/redis/port_mixins/__init__.py b/packages/redis/archipy/adapters/redis/port_mixins/__init__.py index ed04c628b..53bfdfcc6 100644 --- a/packages/redis/archipy/adapters/redis/port_mixins/__init__.py +++ b/packages/redis/archipy/adapters/redis/port_mixins/__init__.py @@ -29,7 +29,6 @@ RedisSortedSetsPort, ) from archipy.adapters.redis.port_mixins.streams import AsyncRedisStreamsPort, RedisStreamsPort -from archipy.adapters.redis.port_mixins.time_series import AsyncRedisTimeSeriesPort, RedisTimeSeriesPort __all__ = [ "AsyncRedisArraysPort", @@ -42,7 +41,6 @@ "AsyncRedisSetsPort", "AsyncRedisSortedSetsPort", "AsyncRedisStreamsPort", - "AsyncRedisTimeSeriesPort", "RedisArraysPort", "RedisClusterPort", "RedisConnectionPort", @@ -54,5 +52,4 @@ "RedisSetsPort", "RedisSortedSetsPort", "RedisStreamsPort", - "RedisTimeSeriesPort", ] diff --git a/packages/redis/archipy/adapters/redis/port_mixins/time_series.py b/packages/redis/archipy/adapters/redis/port_mixins/time_series.py deleted file mode 100644 index abd60c47d..000000000 --- a/packages/redis/archipy/adapters/redis/port_mixins/time_series.py +++ /dev/null @@ -1,188 +0,0 @@ -"""Redis time series ports.""" - -from __future__ import annotations - -from abc import abstractmethod -from typing import TYPE_CHECKING, TypedDict, Unpack - -if TYPE_CHECKING: - from collections.abc import Iterable - - from redis.typing import KeyT, TimeSeriesMRangeResponse, TimeSeriesNRangeResponse, TimeSeriesRangeResponse - - -class TimeSeriesNRangeOptions(TypedDict, total=False): - """Optional arguments for a timestamp-aligned multi-key range query.""" - - count: int | None - aggregators: str | list[str] | None - bucket_size_msec: int | None - filter_by_ts: list[int] | None - filter_by_min_value: int | None - filter_by_max_value: int | None - align: int | str | None - latest: bool | None - bucket_timestamp: str | None - empty: bool | None - - -class TimeSeriesMRangeOptions(TypedDict, total=False): - """Optional arguments for a label-filtered range query.""" - - count: int | None - aggregation_type: str | list[str] | None - bucket_size_msec: int | None - with_labels: bool | None - filter_by_ts: list[int] | None - filter_by_min_value: int | None - filter_by_max_value: int | None - groupby: str | None - reduce: str | None - select_labels: list[str] | None - align: int | str | None - latest: bool | None - bucket_timestamp: str | None - empty: bool | None - exclude_empty: bool | None - - -class RedisTimeSeriesPort: - """Synchronous Redis time series operations.""" - - @abstractmethod - def ts_read( - self, - key: KeyT, - timestamp: int | str, - *, - block_milliseconds: int | None = None, - block_min_count: int | None = None, - max_count: int | None = None, - ) -> TimeSeriesRangeResponse: - """Read samples after a timestamp, optionally blocking.""" - raise NotImplementedError - - @abstractmethod - def ts_querylabels( - self, - *, - label: str | None = None, - filters: Iterable[str] | None = None, - ) -> set[bytes | str]: - """List matching label names or values for a requested label.""" - raise NotImplementedError - - @abstractmethod - def ts_nrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in ascending order.""" - raise NotImplementedError - - @abstractmethod - def ts_nrevrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in descending order.""" - raise NotImplementedError - - @abstractmethod - def ts_mrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in ascending order.""" - raise NotImplementedError - - @abstractmethod - def ts_mrevrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in descending order.""" - raise NotImplementedError - - -class AsyncRedisTimeSeriesPort: - """Asynchronous Redis time series operations.""" - - @abstractmethod - async def ts_read( - self, - key: KeyT, - timestamp: int | str, - *, - block_milliseconds: int | None = None, - block_min_count: int | None = None, - max_count: int | None = None, - ) -> TimeSeriesRangeResponse: - """Read samples after a timestamp, optionally blocking.""" - raise NotImplementedError - - @abstractmethod - async def ts_querylabels( - self, - *, - label: str | None = None, - filters: Iterable[str] | None = None, - ) -> set[bytes | str]: - """List matching label names or values for a requested label.""" - raise NotImplementedError - - @abstractmethod - async def ts_nrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in ascending order.""" - raise NotImplementedError - - @abstractmethod - async def ts_nrevrange( - self, - keys: list[KeyT], - from_time: int | str, - to_time: int | str, - **options: Unpack[TimeSeriesNRangeOptions], - ) -> TimeSeriesNRangeResponse: - """Read timestamp-aligned samples in descending order.""" - raise NotImplementedError - - @abstractmethod - async def ts_mrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in ascending order.""" - raise NotImplementedError - - @abstractmethod - async def ts_mrevrange( - self, - from_time: int | str, - to_time: int | str, - filters: list[str], - **options: Unpack[TimeSeriesMRangeOptions], - ) -> TimeSeriesMRangeResponse: - """Read series matching label filters in descending order.""" - raise NotImplementedError diff --git a/packages/redis/archipy/adapters/redis/ports.py b/packages/redis/archipy/adapters/redis/ports.py index 6f0d70fd9..b77ce2089 100644 --- a/packages/redis/archipy/adapters/redis/ports.py +++ b/packages/redis/archipy/adapters/redis/ports.py @@ -13,7 +13,6 @@ AsyncRedisSetsPort, AsyncRedisSortedSetsPort, AsyncRedisStreamsPort, - AsyncRedisTimeSeriesPort, RedisArraysPort, RedisClusterPort, RedisConnectionPort, @@ -25,7 +24,6 @@ RedisSetsPort, RedisSortedSetsPort, RedisStreamsPort, - RedisTimeSeriesPort, ) __all__ = [ @@ -42,7 +40,6 @@ class RedisPort( RedisListsPort, RedisSetsPort, RedisSortedSetsPort, - RedisTimeSeriesPort, RedisStreamsPort, RedisArraysPort, RedisHashesPort, @@ -62,7 +59,6 @@ class AsyncRedisPort( AsyncRedisListsPort, AsyncRedisSetsPort, AsyncRedisSortedSetsPort, - AsyncRedisTimeSeriesPort, AsyncRedisStreamsPort, AsyncRedisArraysPort, AsyncRedisHashesPort, From 6ece7b456707105de684e495cc62b6b543401804 Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 19:49:48 +0330 Subject: [PATCH 09/10] refactor(redis): merge capability steps into one module Fold the redis-py 8.1 step definitions into redis_capability_steps.py and share the existing run/result helpers. Refs #641 --- features/steps/redis_81_steps.py | 283 ----------------------- features/steps/redis_capability_steps.py | 257 +++++++++++++++++++- pyproject.toml | 2 +- 3 files changed, 251 insertions(+), 291 deletions(-) delete mode 100644 features/steps/redis_81_steps.py diff --git a/features/steps/redis_81_steps.py b/features/steps/redis_81_steps.py deleted file mode 100644 index 069239f73..000000000 --- a/features/steps/redis_81_steps.py +++ /dev/null @@ -1,283 +0,0 @@ -"""Behavior of the redis-py 8.1 command surfaces exposed by ArchiPy.""" - -import asyncio -import inspect -import socket -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 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, -) -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) - adapter = scenario.async_adapter or scenario.adapter - - async def run(): - 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("redis81", asyncio.run(run())) - - -@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 = get_current_scenario_context(context).get("redis81") - 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 = get_current_scenario_context(context).get("redis81") - 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 = get_current_scenario_context(context).get("redis81") - 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("redis81", error.errors()[0]["loc"]) - - -@then("the search aggregation is rejected") -def verify_unsupported_reducer(context): - assert get_current_scenario_context(context).get("redis81") == ("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("redis81:sentinel", "present") - assert adapter.get("redis81: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("redis81: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"redis81: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("redis81", value) - - -@then("the adapter learns the new owner and can read the migrated key") -def verify_migrated_key(context): - assert get_current_scenario_context(context).get("redis81") == "migrated" diff --git a/features/steps/redis_capability_steps.py b/features/steps/redis_capability_steps.py index 56f72416e..b0ed94bb9 100644 --- a/features/steps/redis_capability_steps.py +++ b/features/steps/redis_capability_steps.py @@ -2,6 +2,7 @@ import asyncio import inspect +import socket import struct from dataclasses import replace from datetime import UTC, datetime, timedelta @@ -9,6 +10,7 @@ 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 ( @@ -24,9 +26,17 @@ from archipy.adapters.redis.adapters import AsyncRedisAdapter, RedisAdapter from archipy.configs.base_config import BaseConfig -from archipy.configs.sections.redis import RedisConfig -from archipy.models.dtos.redis.search.index_schema_dto import IndexSchemaDTO, TextFieldConfig, VectorFieldConfig +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") @@ -209,7 +219,7 @@ def predicate(command, keys): return command == "GET" and keys == (cache_key,) with RedisAdapter( - config, cache_config=CacheConfig(tracking_mode=mode, cache_predicate=predicate) + 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) @@ -333,9 +343,9 @@ async def exercise(adapter, key): config = config.model_copy( update={ "CLUSTER": config.CLUSTER.model_copy( - update={"TOPOLOGY_REFRESH_MIN_INTERVAL": 0.25, "READ_FROM_REPLICAS": True} - ) - } + update={"TOPOLOGY_REFRESH_MIN_INTERVAL": 0.25, "READ_FROM_REPLICAS": True}, + ), + }, ) fallback = StaticMetadataResolver() get_metadata = fallback.resolve("GET") @@ -354,7 +364,7 @@ async def check(configured): if isinstance(adapter, AsyncRedisAdapter): async with AsyncRedisAdapter( - config, metadata_resolver=AsyncDynamicMetadataResolver(metadata, AsyncStaticMetadataResolver()) + config, metadata_resolver=AsyncDynamicMetadataResolver(metadata, AsyncStaticMetadataResolver()), ) as configured: return await check(configured) with RedisAdapter(config, metadata_resolver=DynamicMetadataResolver(metadata, fallback)) as configured: @@ -409,3 +419,236 @@ async def exercise(adapter, key): @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/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] From a4b09dbf752c63ca2c6e7b603272a4e2effcdced Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Mon, 23 Nov 2026 19:58:55 +0330 Subject: [PATCH 10/10] fix(redis): wait for hybrid search indexing The asynchronous hybrid search could query before the new document was indexed and returned zero hits. Wait for the initial scan like the aggregation coverage does. Refs #641 --- features/steps/redis_capability_steps.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/features/steps/redis_capability_steps.py b/features/steps/redis_capability_steps.py index b0ed94bb9..f88fcf7b2 100644 --- a/features/steps/redis_capability_steps.py +++ b/features/steps/redis_capability_steps.py @@ -187,6 +187,12 @@ async def exercise(adapter, 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}),