Skip to content

glide_shared

ALL_CHANNELS = None module-attribute

Constant representing 'unsubscribe from all channels'. Pass this to unsubscribe() to unsubscribe from all channels.

ALL_PATTERNS = None module-attribute

Constant representing 'unsubscribe from all patterns'. Pass this to punsubscribe() to unsubscribe from all patterns.

ALL_SHARDED_CHANNELS = None module-attribute

Constant representing 'unsubscribe from all sharded channels'. Pass this to sunsubscribe() to unsubscribe from all sharded channels.

ClientSideCache dataclass

Configuration for client-side caching with TTL-based expiration.

This class configures a local cache that stores read command responses on the client side to reduce network round-trips and server load. The cache uses Time-To-Live (TTL) based expiration, where entries are automatically removed after a specified duration.

Cached entries expire based on TTL. Server-side key changes are not propagated to the cache, so values may become stale before TTL expires. Expiration is lazy — entries are removed when accessed after their TTL, not proactively in the background. Supported read commands: GET, MGET, HGETALL, SMEMBERS. An MGET response may combine locally cached values with values fetched from the server, so it does not provide an atomic snapshot across all keys.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/cache.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@dataclass
class ClientSideCache:
    """
    Configuration for client-side caching with TTL-based expiration.

    This class configures a local cache that stores read command responses
    on the client side to reduce network round-trips and server load. The cache
    uses Time-To-Live (TTL) based expiration, where entries are automatically
    removed after a specified duration.

    Cached entries expire based on TTL. Server-side key changes are not propagated
    to the cache, so values may become stale before TTL expires.
    Expiration is lazy — entries are removed when accessed after their TTL, not
    proactively in the background.
    Supported read commands: GET, MGET, HGETALL, SMEMBERS. An MGET response may
    combine locally cached values with values fetched from the server, so it
    does not provide an atomic snapshot across all keys.
    """

    # Class variables - shared across all instances
    _counter_lock: ClassVar[threading.Lock] = threading.Lock()
    _counter: ClassVar[int] = 0

    # Instance variables - unique per instance
    cache_id: str
    max_cache_kb: int
    entry_ttl_ms: int
    eviction_policy: Optional[EvictionPolicy] = None
    enable_metrics: bool = False
    server_assisted: bool = False

    @classmethod
    def create(
        cls,
        max_cache_kb: int,
        entry_ttl_ms: int,
        eviction_policy: Optional[EvictionPolicy] = None,
        enable_metrics: bool = False,
        server_assisted: bool = False,
    ) -> "ClientSideCache":
        """
        Create a new client-side cache configuration with an auto-generated unique ID.

        In order for 2 clients to share the same cache, they must be created with the
        same ``ClientSideCache`` instance.

        - Clients with different ``ClientSideCache`` instances will have separate caches,
          even if the configurations are identical.
        - Clients using different DBs cannot share the same cache.
        - Clients using different ACL users cannot share the same cache.

        Args:
            max_cache_kb (int): Maximum size of the cache in kilobytes (KB). This limits
                the total memory used by cached keys and values. When this limit is reached,
                entries are evicted based on the eviction policy.
            entry_ttl_ms (int): Time-To-Live for cached entries in milliseconds. After this
                duration, entries automatically expire and are removed from the cache.
                Set to 0 to disable TTL expiration (entries remain until evicted or invalidated).
            eviction_policy (Optional[EvictionPolicy]): Policy for evicting entries when
                the cache reaches its maximum size. If not specified (None), the default
                policy of LRU will be used.
                See `EvictionPolicy` enum for available options.
            enable_metrics (bool): If True, enables collection of cache metrics such as hit/miss rates.
            server_assisted (bool): If True, enables server-assisted client-side caching.
                When enabled, GLIDE sends CLIENT TRACKING ON BCAST during connection setup
                and the server sends invalidation messages when tracked keys are modified.
                Requires RESP3 protocol.

        Returns:
            ClientSideCache: A new ClientSideCache instance.

        Example:
            Create a basic cache:
            >>> cache = ClientSideCache.create(
            ...     max_cache_kb=10,  # 10 KB
            ...     entry_ttl_ms=60000,  # 1 minute TTL
            ...     eviction_policy=EvictionPolicy.LRU,
            ...     enable_metrics=True
            ... )
        """
        if max_cache_kb <= 0:
            raise ValueError("max_cache_kb must be positive")
        if entry_ttl_ms < 0:
            raise ValueError("entry_ttl_ms must be non-negative (0 = no expiration)")

        with cls._counter_lock:
            cache_id = str(cls._counter)
            cls._counter += 1

        return cls(
            cache_id=cache_id,
            max_cache_kb=max_cache_kb,
            entry_ttl_ms=entry_ttl_ms,
            eviction_policy=eviction_policy,
            enable_metrics=enable_metrics,
            server_assisted=server_assisted,
        )

create(max_cache_kb, entry_ttl_ms, eviction_policy=None, enable_metrics=False, server_assisted=False) classmethod

Create a new client-side cache configuration with an auto-generated unique ID.

In order for 2 clients to share the same cache, they must be created with the same ClientSideCache instance.

  • Clients with different ClientSideCache instances will have separate caches, even if the configurations are identical.
  • Clients using different DBs cannot share the same cache.
  • Clients using different ACL users cannot share the same cache.

Parameters:

Name Type Description Default
max_cache_kb int

Maximum size of the cache in kilobytes (KB). This limits the total memory used by cached keys and values. When this limit is reached, entries are evicted based on the eviction policy.

required
entry_ttl_ms int

Time-To-Live for cached entries in milliseconds. After this duration, entries automatically expire and are removed from the cache. Set to 0 to disable TTL expiration (entries remain until evicted or invalidated).

required
eviction_policy Optional[EvictionPolicy]

Policy for evicting entries when the cache reaches its maximum size. If not specified (None), the default policy of LRU will be used. See EvictionPolicy enum for available options.

None
enable_metrics bool

If True, enables collection of cache metrics such as hit/miss rates.

False
server_assisted bool

If True, enables server-assisted client-side caching. When enabled, GLIDE sends CLIENT TRACKING ON BCAST during connection setup and the server sends invalidation messages when tracked keys are modified. Requires RESP3 protocol.

False

Returns:

Name Type Description
ClientSideCache ClientSideCache

A new ClientSideCache instance.

Example

Create a basic cache:

cache = ClientSideCache.create( ... max_cache_kb=10, # 10 KB ... entry_ttl_ms=60000, # 1 minute TTL ... eviction_policy=EvictionPolicy.LRU, ... enable_metrics=True ... )

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/cache.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@classmethod
def create(
    cls,
    max_cache_kb: int,
    entry_ttl_ms: int,
    eviction_policy: Optional[EvictionPolicy] = None,
    enable_metrics: bool = False,
    server_assisted: bool = False,
) -> "ClientSideCache":
    """
    Create a new client-side cache configuration with an auto-generated unique ID.

    In order for 2 clients to share the same cache, they must be created with the
    same ``ClientSideCache`` instance.

    - Clients with different ``ClientSideCache`` instances will have separate caches,
      even if the configurations are identical.
    - Clients using different DBs cannot share the same cache.
    - Clients using different ACL users cannot share the same cache.

    Args:
        max_cache_kb (int): Maximum size of the cache in kilobytes (KB). This limits
            the total memory used by cached keys and values. When this limit is reached,
            entries are evicted based on the eviction policy.
        entry_ttl_ms (int): Time-To-Live for cached entries in milliseconds. After this
            duration, entries automatically expire and are removed from the cache.
            Set to 0 to disable TTL expiration (entries remain until evicted or invalidated).
        eviction_policy (Optional[EvictionPolicy]): Policy for evicting entries when
            the cache reaches its maximum size. If not specified (None), the default
            policy of LRU will be used.
            See `EvictionPolicy` enum for available options.
        enable_metrics (bool): If True, enables collection of cache metrics such as hit/miss rates.
        server_assisted (bool): If True, enables server-assisted client-side caching.
            When enabled, GLIDE sends CLIENT TRACKING ON BCAST during connection setup
            and the server sends invalidation messages when tracked keys are modified.
            Requires RESP3 protocol.

    Returns:
        ClientSideCache: A new ClientSideCache instance.

    Example:
        Create a basic cache:
        >>> cache = ClientSideCache.create(
        ...     max_cache_kb=10,  # 10 KB
        ...     entry_ttl_ms=60000,  # 1 minute TTL
        ...     eviction_policy=EvictionPolicy.LRU,
        ...     enable_metrics=True
        ... )
    """
    if max_cache_kb <= 0:
        raise ValueError("max_cache_kb must be positive")
    if entry_ttl_ms < 0:
        raise ValueError("entry_ttl_ms must be non-negative (0 = no expiration)")

    with cls._counter_lock:
        cache_id = str(cls._counter)
        cls._counter += 1

    return cls(
        cache_id=cache_id,
        max_cache_kb=max_cache_kb,
        entry_ttl_ms=entry_ttl_ms,
        eviction_policy=eviction_policy,
        enable_metrics=enable_metrics,
        server_assisted=server_assisted,
    )

EvictionPolicy

Bases: Enum

Defined policies for evicting entries from the client-side cache when it reaches its maximum size.

When the cache is full, it must evict existing entries to make room for new ones.

Attributes:

Name Type Description
LRU Least Recently Used)

Evicts the least recently accessed entry. Best for recency-biased workloads like event streams and job queues.

LFU Least Frequently Used)

Evicts the least frequently accessed entry. Best for frequency-biased workloads like user profiles and product catalogs.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/cache.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class EvictionPolicy(Enum):
    """
    Defined policies for evicting entries from the client-side cache when it reaches its maximum size.

    When the cache is full, it must evict existing entries to make room for new ones.

    Attributes:
        LRU (Least Recently Used) : Evicts the least recently accessed entry. Best for recency-biased
            workloads like event streams and job queues.
        LFU (Least Frequently Used) : Evicts the least frequently accessed entry. Best for frequency-biased
            workloads like user profiles and product catalogs.
    """

    LRU = ProtobufEvictionPolicy.LRU
    LFU = ProtobufEvictionPolicy.LFU

Batch

Bases: BaseBatch

Batch implementation for standalone GlideClient. Batches allow the execution of a group of commands in a single step.

Batch Response

An array of command responses is returned by the client exec command, in the order they were given. Each element in the array represents a command given to the Batch. The response for each command depends on the executed Valkey command. Specific response types are documented alongside each method.

Parameters:

Name Type Description Default
is_atomic bool

Determines whether the batch is atomic or non-atomic. If True, the batch will be executed as an atomic transaction. If False, the batch will be executed as a non-atomic pipeline.

required

See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.

Note for Standalone Mode (Cluster Mode Disabled): Standalone Batches are executed on the primary node.

Examples:

Atomic Batch - Transaction:
>>> transaction = Batch(is_atomic=True)  # Atomic (Transaction)
>>> transaction.set("key", "value")
>>> transaction.get("key")
>>> result = await client.exec(transaction, false)
>>> print(result)
[OK, b"value"]
Non-Atomic Batch - Pipeline:
>>> pipeline = Batch(is_atomic=False)  # Non-Atomic (Pipeline)
>>> pipeline.set("key1", "value1")
>>> pipeline.set("key2", "value2")
>>> pipeline.get("key1")
>>> pipeline.get("key2")
>>> result = await client.exec(pipeline, false)
>>> print(result)
[OK, OK, b"value1", b"value2"]
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
class Batch(BaseBatch):
    """
    Batch implementation for standalone GlideClient. Batches allow the execution of a group
    of commands in a single step.

    Batch Response:
        An ``array`` of command responses is returned by the client ``exec`` command,
        in the order they were given. Each element in the array represents a command given to the Batch.
        The response for each command depends on the executed Valkey command.
        Specific response types are documented alongside each method.

    Args:
        is_atomic (bool): Determines whether the batch is atomic or non-atomic. If ``True``,
            the batch will be executed as an atomic transaction. If ``False``,
            the batch will be executed as a non-atomic pipeline.

    See [Valkey Transactions (Atomic Batches)](https://valkey.io/topics/transactions/) and [Valkey Pipelines (Non-Atomic Batches)](https://valkey.io/topics/pipelining/) for details.

    Note for Standalone Mode (Cluster Mode Disabled):
        Standalone Batches are executed on the primary node.

    Examples:
        ### Atomic Batch - Transaction:
        >>> transaction = Batch(is_atomic=True)  # Atomic (Transaction)
        >>> transaction.set("key", "value")
        >>> transaction.get("key")
        >>> result = await client.exec(transaction, false)
        >>> print(result)
        [OK, b"value"]

        #### Non-Atomic Batch - Pipeline:
        >>> pipeline = Batch(is_atomic=False)  # Non-Atomic (Pipeline)
        >>> pipeline.set("key1", "value1")
        >>> pipeline.set("key2", "value2")
        >>> pipeline.get("key1")
        >>> pipeline.get("key2")
        >>> result = await client.exec(pipeline, false)
        >>> print(result)
        [OK, OK, b"value1", b"value2"]

    """

    def select(self, index: int) -> "Batch":
        """
        Change the currently selected database.

        See [valkey.io](https://valkey.io/commands/select/) for details.

        Args:
            index (int): The index of the database to select.

        Command response:
            A simple OK response.
        """
        return self.append_command(RequestType.Select, [str(index)])

    def reset(self) -> "Batch":
        """
        Reset the connection state.

        See [valkey.io](https://valkey.io/commands/reset/) for details.

        Command response:
            bytes: The string "RESET".
        """
        return self.append_command(RequestType.Reset, [])

    def copy(
        self,
        source: TEncodable,
        destination: TEncodable,
        destinationDB: Optional[int] = None,
        replace: Optional[bool] = None,
    ) -> "Batch":
        """
        Copies the value stored at the `source` to the `destination` key. If `destinationDB`
        is specified, the value will be copied to the database specified by `destinationDB`,
        otherwise the current database will be used. When `replace` is True, removes the
        `destination` key first if it already exists, otherwise performs no action.

        See [valkey.io](https://valkey.io/commands/copy) for more details.

        Args:
            source (TEncodable): The key to the source value.
            destination (TEncodable): The key where the value should be copied to.
            destinationDB (Optional[int]): The alternative logical database index for the destination key.
            replace (Optional[bool]): If the destination key should be removed before copying the value to it.

        Command response:
            bool: True if the source was copied.

            Otherwise, return False.
        """
        args = [source, destination]
        if destinationDB is not None:
            args.extend(["DB", str(destinationDB)])
        if replace is not None:
            args.append("REPLACE")

        return self.append_command(RequestType.Copy, args)

    def migrate(
        self,
        host: str,
        port: int,
        keys: Union[TEncodable, List[TEncodable]],
        destination_db: int,
        timeout: int,
        options: Optional[MigrateOptions] = None,
    ) -> "Batch":
        """
        Atomically transfers one or more keys from a source Valkey instance to a destination
        Valkey instance. Pass a list to migrate multiple keys in one command.

        See [valkey.io](https://valkey.io/commands/migrate/) for details.

        Args:
            host (str): The host of the destination Valkey instance.
            port (int): The port of the destination Valkey instance.
            keys (Union[TEncodable, List[TEncodable]]): The key or list of keys to migrate.
            destination_db (int): The database index on the destination instance.
            timeout (int): The maximum idle time in milliseconds for the bulk-transfer.
            options (Optional[MigrateOptions]): Additional migration options.

        Returns:
            Batch: The batch instance for chaining.
        """
        if isinstance(keys, list):
            if len(keys) == 0:
                raise ValueError("migrate: 'keys' list must not be empty")
            args: List[TEncodable] = [
                host,
                str(port),
                "",
                str(destination_db),
                str(timeout),
            ]
            if options:
                args.extend(options.to_args())
            args += ["KEYS"] + list(keys)
        else:
            args = [host, str(port), keys, str(destination_db), str(timeout)]
            if options:
                args.extend(options.to_args())
        return self.append_command(RequestType.Migrate, args)

    def publish(self, message: TEncodable, channel: TEncodable) -> "Batch":
        """
        Publish a message on pubsub channel.

        See [valkey.io](https://valkey.io/commands/publish) for more details.

        Args:
            message (TEncodable): Message to publish
            channel (TEncodable): Channel to publish the message on.

        Command Respose:
            int: Number of subscriptions in that shard that received the message.

        """
        return self.append_command(RequestType.Publish, [channel, message])

select(index)

Change the currently selected database.

See valkey.io for details.

Parameters:

Name Type Description Default
index int

The index of the database to select.

required
Command response

A simple OK response.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
def select(self, index: int) -> "Batch":
    """
    Change the currently selected database.

    See [valkey.io](https://valkey.io/commands/select/) for details.

    Args:
        index (int): The index of the database to select.

    Command response:
        A simple OK response.
    """
    return self.append_command(RequestType.Select, [str(index)])

reset()

Reset the connection state.

See valkey.io for details.

Command response

bytes: The string "RESET".

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
def reset(self) -> "Batch":
    """
    Reset the connection state.

    See [valkey.io](https://valkey.io/commands/reset/) for details.

    Command response:
        bytes: The string "RESET".
    """
    return self.append_command(RequestType.Reset, [])

copy(source, destination, destinationDB=None, replace=None)

Copies the value stored at the source to the destination key. If destinationDB is specified, the value will be copied to the database specified by destinationDB, otherwise the current database will be used. When replace is True, removes the destination key first if it already exists, otherwise performs no action.

See valkey.io for more details.

Parameters:

Name Type Description Default
source TEncodable

The key to the source value.

required
destination TEncodable

The key where the value should be copied to.

required
destinationDB Optional[int]

The alternative logical database index for the destination key.

None
replace Optional[bool]

If the destination key should be removed before copying the value to it.

None
Command response

bool: True if the source was copied.

Otherwise, return False.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
def copy(
    self,
    source: TEncodable,
    destination: TEncodable,
    destinationDB: Optional[int] = None,
    replace: Optional[bool] = None,
) -> "Batch":
    """
    Copies the value stored at the `source` to the `destination` key. If `destinationDB`
    is specified, the value will be copied to the database specified by `destinationDB`,
    otherwise the current database will be used. When `replace` is True, removes the
    `destination` key first if it already exists, otherwise performs no action.

    See [valkey.io](https://valkey.io/commands/copy) for more details.

    Args:
        source (TEncodable): The key to the source value.
        destination (TEncodable): The key where the value should be copied to.
        destinationDB (Optional[int]): The alternative logical database index for the destination key.
        replace (Optional[bool]): If the destination key should be removed before copying the value to it.

    Command response:
        bool: True if the source was copied.

        Otherwise, return False.
    """
    args = [source, destination]
    if destinationDB is not None:
        args.extend(["DB", str(destinationDB)])
    if replace is not None:
        args.append("REPLACE")

    return self.append_command(RequestType.Copy, args)

migrate(host, port, keys, destination_db, timeout, options=None)

Atomically transfers one or more keys from a source Valkey instance to a destination Valkey instance. Pass a list to migrate multiple keys in one command.

See valkey.io for details.

Parameters:

Name Type Description Default
host str

The host of the destination Valkey instance.

required
port int

The port of the destination Valkey instance.

required
keys Union[TEncodable, List[TEncodable]]

The key or list of keys to migrate.

required
destination_db int

The database index on the destination instance.

required
timeout int

The maximum idle time in milliseconds for the bulk-transfer.

required
options Optional[MigrateOptions]

Additional migration options.

None

Returns:

Name Type Description
Batch Batch

The batch instance for chaining.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
def migrate(
    self,
    host: str,
    port: int,
    keys: Union[TEncodable, List[TEncodable]],
    destination_db: int,
    timeout: int,
    options: Optional[MigrateOptions] = None,
) -> "Batch":
    """
    Atomically transfers one or more keys from a source Valkey instance to a destination
    Valkey instance. Pass a list to migrate multiple keys in one command.

    See [valkey.io](https://valkey.io/commands/migrate/) for details.

    Args:
        host (str): The host of the destination Valkey instance.
        port (int): The port of the destination Valkey instance.
        keys (Union[TEncodable, List[TEncodable]]): The key or list of keys to migrate.
        destination_db (int): The database index on the destination instance.
        timeout (int): The maximum idle time in milliseconds for the bulk-transfer.
        options (Optional[MigrateOptions]): Additional migration options.

    Returns:
        Batch: The batch instance for chaining.
    """
    if isinstance(keys, list):
        if len(keys) == 0:
            raise ValueError("migrate: 'keys' list must not be empty")
        args: List[TEncodable] = [
            host,
            str(port),
            "",
            str(destination_db),
            str(timeout),
        ]
        if options:
            args.extend(options.to_args())
        args += ["KEYS"] + list(keys)
    else:
        args = [host, str(port), keys, str(destination_db), str(timeout)]
        if options:
            args.extend(options.to_args())
    return self.append_command(RequestType.Migrate, args)

publish(message, channel)

Publish a message on pubsub channel.

See valkey.io for more details.

Parameters:

Name Type Description Default
message TEncodable

Message to publish

required
channel TEncodable

Channel to publish the message on.

required
Command Respose

int: Number of subscriptions in that shard that received the message.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
def publish(self, message: TEncodable, channel: TEncodable) -> "Batch":
    """
    Publish a message on pubsub channel.

    See [valkey.io](https://valkey.io/commands/publish) for more details.

    Args:
        message (TEncodable): Message to publish
        channel (TEncodable): Channel to publish the message on.

    Command Respose:
        int: Number of subscriptions in that shard that received the message.

    """
    return self.append_command(RequestType.Publish, [channel, message])

ClusterBatch

Bases: BaseBatch

Batch implementation for cluster GlideClusterClient. Batches allow the execution of a group of commands in a single step.

Batch Response

An array of command responses is returned by the client exec command, in the order they were given. Each element in the array represents a command given to the ClusterBatch. The response for each command depends on the executed Valkey command. Specific response types are documented alongside each method.

Parameters:

Name Type Description Default
is_atomic bool

Determines whether the batch is atomic or non-atomic. If True, the batch will be executed as an atomic transaction. If False, the batch will be executed as a non-atomic pipeline.

required

See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.

Examples:

Atomic Batch - Transaction in a Cluster:
>>> transaction = ClusterBatch(is_atomic=True)  # Atomic (Transaction)
>>> transaction.set("key", "value")
>>> transaction.get("key")
>>> result = await client.exec(transaction, false)
>>> print(result)
[OK, b"value"]
Non-Atomic Batch - Pipeline in a Cluster:
>>> pipeline = ClusterBatch(is_atomic=False)  # Non-Atomic (Pipeline)
>>> pipeline.set("key1", "value1")
>>> pipeline.set("key2", "value2")
>>> pipeline.get("key1")
>>> pipeline.get("key2")
>>> result = await client.exec(pipeline, false)
>>> print(result)
[OK, OK, b"value1", b"value2"]
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
class ClusterBatch(BaseBatch):
    """
    Batch implementation for cluster GlideClusterClient. Batches allow the execution of a group
    of commands in a single step.

    Batch Response:
        An ``array`` of command responses is returned by the client ``exec`` command,
        in the order they were given. Each element in the array represents a command given to the ClusterBatch.
        The response for each command depends on the executed Valkey command.
        Specific response types are documented alongside each method.

    Args:
        is_atomic (bool): Determines whether the batch is atomic or non-atomic. If ``True``,
            the batch will be executed as an atomic transaction. If ``False``,
            the batch will be executed as a non-atomic pipeline.

    See [Valkey Transactions (Atomic Batches)](https://valkey.io/topics/transactions/) and [Valkey Pipelines (Non-Atomic Batches)](https://valkey.io/topics/pipelining/) for details.

    Examples:
        ### Atomic Batch - Transaction in a Cluster:
        >>> transaction = ClusterBatch(is_atomic=True)  # Atomic (Transaction)
        >>> transaction.set("key", "value")
        >>> transaction.get("key")
        >>> result = await client.exec(transaction, false)
        >>> print(result)
        [OK, b"value"]

        ### Non-Atomic Batch - Pipeline in a Cluster:
        >>> pipeline = ClusterBatch(is_atomic=False)  # Non-Atomic (Pipeline)
        >>> pipeline.set("key1", "value1")
        >>> pipeline.set("key2", "value2")
        >>> pipeline.get("key1")
        >>> pipeline.get("key2")
        >>> result = await client.exec(pipeline, false)
        >>> print(result)
        [OK, OK, b"value1", b"value2"]

    """

    def copy(
        self,
        source: TEncodable,
        destination: TEncodable,
        # TODO next major release the arguments replace and destinationDB must have their order
        # swapped to align with the standalone order.
        # At the moment of the patch release 2.1.1. we can't have a breaking change
        replace: Optional[bool] = None,
        destinationDB: Optional[int] = None,
    ) -> "ClusterBatch":
        """
        Copies the value stored at the `source` to the `destination` key. When `replace` is True,
        removes the `destination` key first if it already exists, otherwise performs no action.

        See [valkey.io](https://valkey.io/commands/copy) for more details.

        Args:
            source (TEncodable): The key to the source value.
            destination (TEncodable): The key where the value should be copied to.
            replace (Optional[bool]): If the destination key should be removed before copying the value to it.
            destinationDB (Optional[int]): The alternative logical database index for the destination key.
        Command response:
            bool: True if the source was copied.

            Otherwise, return False.

        Since: Valkey 9.0.0.
        """
        args = [source, destination]
        if destinationDB is not None:
            args.extend(["DB", str(destinationDB)])
        if replace is not None:
            args.append("REPLACE")

        return self.append_command(RequestType.Copy, args)

    def publish(
        self, message: str, channel: str, sharded: bool = False
    ) -> "ClusterBatch":
        """
        Publish a message on pubsub channel.
        This command aggregates PUBLISH and SPUBLISH commands functionalities.
        The mode is selected using the 'sharded' parameter

        See [PUBLISH](https://valkey.io/commands/publish) and [SPUBLISH](https://valkey.io/commands/spublish)
        for more details.

        Args:
            message (str): Message to publish
            channel (str): Channel to publish the message on.
            sharded (bool): Use sharded pubsub mode. Available since Valkey 7.0.0.

        Returns:
            int: Number of subscriptions in that shard that received the message.
        """
        return self.append_command(
            RequestType.SPublish if sharded else RequestType.Publish, [channel, message]
        )

    def pubsub_shardchannels(
        self, pattern: Optional[TEncodable] = None
    ) -> "ClusterBatch":
        """
        Lists the currently active shard channels.

        See [valkey.io](https://valkey.io/commands/pubsub-shardchannels) for details.

        Args:
            pattern (Optional[TEncodable]): A glob-style pattern to match active shard channels.
                If not provided, all active shard channels are returned.

        Command response:
            List[bytes]: A list of currently active shard channels matching the given pattern.

            If no pattern is specified, all active shard channels are returned.
        """
        command_args = [pattern] if pattern is not None else []
        return self.append_command(RequestType.PubSubShardChannels, command_args)

    def pubsub_shardnumsub(
        self, channels: Optional[List[TEncodable]] = None
    ) -> "ClusterBatch":
        """
        Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified shard channels.

        Note:
            It is valid to call this command without channels. In this case, it will just return an empty map.

        See [valkey.io](https://valkey.io/commands/pubsub-shardnumsub) for details.

        Args:
            channels (Optional[List[str]]): The list of shard channels to query for the number of subscribers.
                If not provided, returns an empty map.

        Command response:
            Mapping[bytes, int]: A map where keys are the shard channel names and values are the number of subscribers.
        """
        return self.append_command(
            RequestType.PubSubShardNumSub, channels if channels else []
        )

copy(source, destination, replace=None, destinationDB=None)

Copies the value stored at the source to the destination key. When replace is True, removes the destination key first if it already exists, otherwise performs no action.

See valkey.io for more details.

Parameters:

Name Type Description Default
source TEncodable

The key to the source value.

required
destination TEncodable

The key where the value should be copied to.

required
replace Optional[bool]

If the destination key should be removed before copying the value to it.

None
destinationDB Optional[int]

The alternative logical database index for the destination key.

None

Command response: bool: True if the source was copied.

Otherwise, return False.

Since: Valkey 9.0.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
def copy(
    self,
    source: TEncodable,
    destination: TEncodable,
    # TODO next major release the arguments replace and destinationDB must have their order
    # swapped to align with the standalone order.
    # At the moment of the patch release 2.1.1. we can't have a breaking change
    replace: Optional[bool] = None,
    destinationDB: Optional[int] = None,
) -> "ClusterBatch":
    """
    Copies the value stored at the `source` to the `destination` key. When `replace` is True,
    removes the `destination` key first if it already exists, otherwise performs no action.

    See [valkey.io](https://valkey.io/commands/copy) for more details.

    Args:
        source (TEncodable): The key to the source value.
        destination (TEncodable): The key where the value should be copied to.
        replace (Optional[bool]): If the destination key should be removed before copying the value to it.
        destinationDB (Optional[int]): The alternative logical database index for the destination key.
    Command response:
        bool: True if the source was copied.

        Otherwise, return False.

    Since: Valkey 9.0.0.
    """
    args = [source, destination]
    if destinationDB is not None:
        args.extend(["DB", str(destinationDB)])
    if replace is not None:
        args.append("REPLACE")

    return self.append_command(RequestType.Copy, args)

publish(message, channel, sharded=False)

Publish a message on pubsub channel. This command aggregates PUBLISH and SPUBLISH commands functionalities. The mode is selected using the 'sharded' parameter

See PUBLISH and SPUBLISH for more details.

Parameters:

Name Type Description Default
message str

Message to publish

required
channel str

Channel to publish the message on.

required
sharded bool

Use sharded pubsub mode. Available since Valkey 7.0.0.

False

Returns:

Name Type Description
int ClusterBatch

Number of subscriptions in that shard that received the message.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
def publish(
    self, message: str, channel: str, sharded: bool = False
) -> "ClusterBatch":
    """
    Publish a message on pubsub channel.
    This command aggregates PUBLISH and SPUBLISH commands functionalities.
    The mode is selected using the 'sharded' parameter

    See [PUBLISH](https://valkey.io/commands/publish) and [SPUBLISH](https://valkey.io/commands/spublish)
    for more details.

    Args:
        message (str): Message to publish
        channel (str): Channel to publish the message on.
        sharded (bool): Use sharded pubsub mode. Available since Valkey 7.0.0.

    Returns:
        int: Number of subscriptions in that shard that received the message.
    """
    return self.append_command(
        RequestType.SPublish if sharded else RequestType.Publish, [channel, message]
    )

pubsub_shardchannels(pattern=None)

Lists the currently active shard channels.

See valkey.io for details.

Parameters:

Name Type Description Default
pattern Optional[TEncodable]

A glob-style pattern to match active shard channels. If not provided, all active shard channels are returned.

None
Command response

List[bytes]: A list of currently active shard channels matching the given pattern.

If no pattern is specified, all active shard channels are returned.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
def pubsub_shardchannels(
    self, pattern: Optional[TEncodable] = None
) -> "ClusterBatch":
    """
    Lists the currently active shard channels.

    See [valkey.io](https://valkey.io/commands/pubsub-shardchannels) for details.

    Args:
        pattern (Optional[TEncodable]): A glob-style pattern to match active shard channels.
            If not provided, all active shard channels are returned.

    Command response:
        List[bytes]: A list of currently active shard channels matching the given pattern.

        If no pattern is specified, all active shard channels are returned.
    """
    command_args = [pattern] if pattern is not None else []
    return self.append_command(RequestType.PubSubShardChannels, command_args)

pubsub_shardnumsub(channels=None)

Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified shard channels.

Note

It is valid to call this command without channels. In this case, it will just return an empty map.

See valkey.io for details.

Parameters:

Name Type Description Default
channels Optional[List[str]]

The list of shard channels to query for the number of subscribers. If not provided, returns an empty map.

None
Command response

Mapping[bytes, int]: A map where keys are the shard channel names and values are the number of subscribers.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
def pubsub_shardnumsub(
    self, channels: Optional[List[TEncodable]] = None
) -> "ClusterBatch":
    """
    Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified shard channels.

    Note:
        It is valid to call this command without channels. In this case, it will just return an empty map.

    See [valkey.io](https://valkey.io/commands/pubsub-shardnumsub) for details.

    Args:
        channels (Optional[List[str]]): The list of shard channels to query for the number of subscribers.
            If not provided, returns an empty map.

    Command response:
        Mapping[bytes, int]: A map where keys are the shard channel names and values are the number of subscribers.
    """
    return self.append_command(
        RequestType.PubSubShardNumSub, channels if channels else []
    )

BatchOptions

Bases: BaseBatchOptions

Options for a batch request for a standalone client.

Parameters:

Name Type Description Default
timeout Optional[int]

The duration in milliseconds that the client should wait for the batch request to complete. This duration encompasses sending the request, awaiting a response from the server, and any required reconnections or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

None
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch_options.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
class BatchOptions(BaseBatchOptions):
    """
    Options for a batch request for a standalone client.

    Args:
        timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
            to complete. This duration encompasses sending the request, awaiting a response from the server,
            and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
            it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
    """

    def __init__(
        self,
        timeout: Optional[int] = None,
    ):
        """
        Options for a batch request for a standalone client

        Args:
            timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
                to complete. This duration encompasses sending the request, awaiting a response from the server,
                and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
                it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
        """
        super().__init__(timeout)

BatchRetryStrategy

Defines a retry strategy for cluster batch requests, allowing control over retries in case of server or connection errors.

This strategy determines whether failed commands should be retried, impacting execution order and potential side effects.

Behavior
  • If retry_server_error is True, failed commands with a retriable error (e.g., TRYAGAIN) will be retried.
  • If retry_connection_error is True, batch requests will be retried on connection failures.
Cautions
  • Server Errors: Retrying may cause commands targeting the same slot to be executed out of order.
  • Connection Errors: Retrying may lead to duplicate executions, since the server might have already received and processed the request before the error occurred.
Example Scenario
MGET key {key}:1
SET key "value"

Expected response when keys are empty:

[None, None]
"OK"

However, if the slot is migrating, both commands may return an ASK error and be redirected. Upon ASK redirection, a multi-key command may return a TRYAGAIN error (triggering a retry), while the SET command succeeds immediately. This can result in an unintended reordering of commands if the first command is retried after the slot stabilizes:

["value", None]
"OK"

Note

Currently, retry strategies are supported only for non-atomic batches.

Default

Both retry_server_error and retry_connection_error are set to False.

Parameters:

Name Type Description Default
retry_server_error bool

If True, failed commands with a retriable error (e.g., TRYAGAIN) will be automatically retried.

⚠️ Warning: Enabling this flag may cause commands targeting the same slot to execute out of order.

By default, this is set to False.

False
retry_connection_error bool

If True, batch requests will be retried in case of connection errors.

⚠️ Warning: Retrying after a connection error may lead to duplicate executions, since the server might have already received and processed the request before the error occurred.

By default, this is set to False.

False
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch_options.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class BatchRetryStrategy:
    """
    Defines a retry strategy for cluster batch requests, allowing control over retries in case of
    server or connection errors.

    This strategy determines whether failed commands should be retried, impacting execution order
    and potential side effects.

    Behavior:
        - If `retry_server_error` is `True`, failed commands with a retriable error (e.g.,
          `TRYAGAIN`) will be retried.
        - If `retry_connection_error` is `True`, batch requests will be retried on
          connection failures.

    Cautions:
        - **Server Errors:** Retrying may cause commands targeting the same slot to be executed
          out of order.
        - **Connection Errors:** Retrying may lead to duplicate executions, since the server might
          have already received and processed the request before the error occurred.

    Example Scenario:
        ```
        MGET key {key}:1
        SET key "value"
        ```

        Expected response when keys are empty:
        ```
        [None, None]
        "OK"
        ```

        However, if the slot is migrating, both commands may return an `ASK` error and be
        redirected. Upon `ASK` redirection, a multi-key command may return a `TRYAGAIN`
        error (triggering a retry), while the `SET` command succeeds immediately. This
        can result in an unintended reordering of commands if the first command is retried
        after the slot stabilizes:
        ```
        ["value", None]
        "OK"
        ```

    Note:
        Currently, retry strategies are supported only for non-atomic batches.

    Default:
        Both `retry_server_error` and `retry_connection_error` are set to `False`.

    Args:
        retry_server_error (bool): If `True`, failed commands with a retriable error (e.g., `TRYAGAIN`)
            will be automatically retried.

            ⚠️ **Warning:** Enabling this flag may cause commands targeting the same slot to execute
            out of order.

            By default, this is set to `False`.

        retry_connection_error (bool): If `True`, batch requests will be retried in case of connection errors.

            ⚠️ **Warning:** Retrying after a connection error may lead to duplicate executions, since
            the server might have already received and processed the request before the error occurred.

            By default, this is set to `False`.

    """

    def __init__(
        self,
        retry_server_error: bool = False,
        retry_connection_error: bool = False,
    ):
        """
        Initialize a BatchRetryStrategy.

        Args:
            retry_server_error (bool): If `True`, failed commands with a retriable error (e.g., `TRYAGAIN`)
                will be automatically retried.

                ⚠️ **Warning:** Enabling this flag may cause commands targeting the same slot to execute
                out of order.

                By default, this is set to `False`.

            retry_connection_error (bool): If `True`, batch requests will be retried in case of connection errors.

                ⚠️ **Warning:** Retrying after a connection error may lead to duplicate executions, since
                the server might have already received and processed the request before the error occurred.

                By default, this is set to `False`.

        """
        self.retry_server_error = retry_server_error
        self.retry_connection_error = retry_connection_error

ClusterBatchOptions

Bases: BaseBatchOptions

Options for cluster batch operations.

Parameters:

Name Type Description Default
timeout Optional[int]

The duration in milliseconds that the client should wait for the batch request to complete. This duration encompasses sending the request, awaiting a response from the server, and any required reconnections or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

None
route Optional[TSingleNodeRoute]

Configures single-node routing for the batch request. The client will send the batch to the specified node defined by route.

If a redirection error occurs:

  • For Atomic Batches (Transactions), the entire transaction will be redirected.
  • For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors will be redirected.
None
retry_strategy Optional[BatchRetryStrategy]

⚠️ Please see BatchRetryStrategy and read carefully before enabling these options.

Defines the retry strategy for handling cluster batch request failures.

This strategy determines whether failed commands should be retried, potentially impacting execution order.

  • If retry_server_error is True, retriable errors (e.g., TRYAGAIN) will trigger a retry.
  • If retry_connection_error is True, connection failures will trigger a retry.

Warnings:

  • Retrying server errors may cause commands targeting the same slot to execute out of order.
  • Retrying connection errors may lead to duplicate executions, as it is unclear which commands have already been processed.

Note: Currently, retry strategies are supported only for non-atomic batches.

Recommendation: It is recommended to increase the timeout in timeout when enabling these strategies.

Default: Both retry_server_error and retry_connection_error are set to False.

None
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch_options.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class ClusterBatchOptions(BaseBatchOptions):
    """
    Options for cluster batch operations.

    Args:
        timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
            to complete. This duration encompasses sending the request, awaiting a response from the server,
            and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
            it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

        route (Optional[TSingleNodeRoute]): Configures single-node routing for the batch request. The client
            will send the batch to the specified node defined by `route`.

            If a redirection error occurs:

            - For Atomic Batches (Transactions), the entire transaction will be redirected.
            - For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors
              will be redirected.

        retry_strategy (Optional[BatchRetryStrategy]): ⚠️ **Please see `BatchRetryStrategy` and read carefully before enabling these
            options.**

            Defines the retry strategy for handling cluster batch request failures.

            This strategy determines whether failed commands should be retried, potentially impacting
            execution order.

            - If `retry_server_error` is `True`, retriable errors (e.g., TRYAGAIN) will
              trigger a retry.
            - If `retry_connection_error` is `True`, connection failures will trigger a
              retry.

            **Warnings:**

            - Retrying server errors may cause commands targeting the same slot to execute out of
              order.
            - Retrying connection errors may lead to duplicate executions, as it is unclear which
              commands have already been processed.

            **Note:** Currently, retry strategies are supported only for non-atomic batches.

            **Recommendation:** It is recommended to increase the timeout in `timeout`
            when enabling these strategies.

            **Default:** Both `retry_server_error` and `retry_connection_error` are set to
            `False`.

    """

    def __init__(
        self,
        timeout: Optional[int] = None,
        route: Optional[TSingleNodeRoute] = None,
        retry_strategy: Optional[BatchRetryStrategy] = None,
    ):
        """
        Initialize ClusterBatchOptions.

        Args:
            timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
                to complete. This duration encompasses sending the request, awaiting a response from the server,
                and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
                it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

            route (Optional[TSingleNodeRoute]): Configures single-node routing for the batch request. The client
                will send the batch to the specified node defined by `route`.

                If a redirection error occurs:

                - For Atomic Batches (Transactions), the entire transaction will be redirected.
                - For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors
                will be redirected.

            retry_strategy (Optional[BatchRetryStrategy]): ⚠️ **Please see `BatchRetryStrategy` and read carefully before enabling these
                options.**

                Defines the retry strategy for handling cluster batch request failures.

                This strategy determines whether failed commands should be retried, potentially impacting
                execution order.

                - If `retry_server_error` is `True`, retriable errors (e.g., TRYAGAIN) will
                trigger a retry.
                - If `retry_connection_error` is `True`, connection failures will trigger a
                retry.

                **Warnings:**

                - Retrying server errors may cause commands targeting the same slot to execute out of
                order.
                - Retrying connection errors may lead to duplicate executions, as it is unclear which
                commands have already been processed.

                **Note:** Currently, retry strategies are supported only for non-atomic batches.

                **Recommendation:** It is recommended to increase the timeout in `timeout`
                when enabling these strategies.

                **Default:** Both `retry_server_error` and `retry_connection_error` are set to
                `False`.
        """
        super().__init__(timeout)
        self.retry_strategy = retry_strategy
        self.route = route

BitEncoding

Bases: ABC

Abstract Base Class used to specify a signed or unsigned argument encoding for the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
73
74
75
76
77
78
79
80
81
82
83
84
85
class BitEncoding(ABC):
    """
    Abstract Base Class used to specify a signed or unsigned argument encoding for the `BITFIELD` or `BITFIELD_RO`
    commands.
    """

    @abstractmethod
    def to_arg(self) -> str:
        """
        Returns the encoding as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
        commands.
        """
        pass

to_arg() abstractmethod

Returns the encoding as a string argument to be used in the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
79
80
81
82
83
84
85
@abstractmethod
def to_arg(self) -> str:
    """
    Returns the encoding as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
    commands.
    """
    pass

BitFieldGet

Bases: BitFieldSubCommands

Represents the "GET" subcommand for getting a value in the binary representation of the string stored in key.

Attributes:

Name Type Description
encoding BitEncoding

The bit encoding for the subcommand.

offset BitFieldOffset

The offset in the array of bits from which to get the value.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class BitFieldGet(BitFieldSubCommands):
    """
    Represents the "GET" subcommand for getting a value in the binary representation of the string stored in `key`.

    Attributes:
        encoding (BitEncoding): The bit encoding for the subcommand.
        offset (BitFieldOffset): The offset in the array of bits from which to get the value.
    """

    #: "GET" subcommand string for use in the `BITFIELD` or `BITFIELD_RO` commands.
    GET_COMMAND_STRING = "GET"

    def __init__(self, encoding: BitEncoding, offset: BitFieldOffset):
        self._encoding = encoding
        self._offset = offset

    def to_args(self) -> List[str]:
        return [self.GET_COMMAND_STRING, self._encoding.to_arg(), self._offset.to_arg()]

BitFieldIncrBy

Bases: BitFieldSubCommands

Represents the "INCRBY" subcommand for increasing or decreasing bits in the binary representation of the string stored in key.

Attributes:

Name Type Description
encoding BitEncoding

The bit encoding for the subcommand.

offset BitOffset

The offset in the array of bits where the value will be incremented.

increment int

The value to increment the bits in the binary value by.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class BitFieldIncrBy(BitFieldSubCommands):
    """
    Represents the "INCRBY" subcommand for increasing or decreasing bits in the binary representation of the
    string stored in `key`.

    Attributes:
        encoding (BitEncoding): The bit encoding for the subcommand.
        offset (BitOffset): The offset in the array of bits where the value will be incremented.
        increment (int): The value to increment the bits in the binary value by.
    """

    #: "INCRBY" subcommand string for use in the `BITFIELD` command.
    INCRBY_COMMAND_STRING = "INCRBY"

    def __init__(self, encoding: BitEncoding, offset: BitFieldOffset, increment: int):
        self._encoding = encoding
        self._offset = offset
        self._increment = increment

    def to_args(self) -> List[str]:
        return [
            self.INCRBY_COMMAND_STRING,
            self._encoding.to_arg(),
            self._offset.to_arg(),
            str(self._increment),
        ]

BitFieldOffset

Bases: ABC

Abstract Base Class representing an offset for an array of bits for the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
124
125
126
127
128
129
130
131
132
133
class BitFieldOffset(ABC):
    """Abstract Base Class representing an offset for an array of bits for the `BITFIELD` or `BITFIELD_RO` commands."""

    @abstractmethod
    def to_arg(self) -> str:
        """
        Returns the offset as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
        commands.
        """
        pass

to_arg() abstractmethod

Returns the offset as a string argument to be used in the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
127
128
129
130
131
132
133
@abstractmethod
def to_arg(self) -> str:
    """
    Returns the offset as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
    commands.
    """
    pass

BitFieldOverflow

Bases: BitFieldSubCommands

Represents the "OVERFLOW" subcommand that determines the result of the "SET" or "INCRBY" BITFIELD subcommands when an underflow or overflow occurs.

Attributes:

Name Type Description
overflow_control BitOverflowControl

The desired overflow behavior.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
class BitFieldOverflow(BitFieldSubCommands):
    """
    Represents the "OVERFLOW" subcommand that determines the result of the "SET" or "INCRBY" `BITFIELD` subcommands
    when an underflow or overflow occurs.

    Attributes:
        overflow_control (BitOverflowControl): The desired overflow behavior.
    """

    #: "OVERFLOW" subcommand string for use in the `BITFIELD` command.
    OVERFLOW_COMMAND_STRING = "OVERFLOW"

    def __init__(self, overflow_control: BitOverflowControl):
        self._overflow_control = overflow_control

    def to_args(self) -> List[str]:
        return [self.OVERFLOW_COMMAND_STRING, self._overflow_control.value]

BitFieldSet

Bases: BitFieldSubCommands

Represents the "SET" subcommand for setting bits in the binary representation of the string stored in key.

Parameters:

Name Type Description Default
encoding BitEncoding

The bit encoding for the subcommand.

required
offset BitOffset

The offset in the array of bits where the value will be set.

required
value int

The value to set the bits in the binary value to.

required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
class BitFieldSet(BitFieldSubCommands):
    """
    Represents the "SET" subcommand for setting bits in the binary representation of the string stored in `key`.

    Args:
        encoding (BitEncoding): The bit encoding for the subcommand.
        offset (BitOffset): The offset in the array of bits where the value will be set.
        value (int): The value to set the bits in the binary value to.
    """

    #: "SET" subcommand string for use in the `BITFIELD` command.
    SET_COMMAND_STRING = "SET"

    def __init__(self, encoding: BitEncoding, offset: BitFieldOffset, value: int):
        self._encoding = encoding
        self._offset = offset
        self._value = value

    def to_args(self) -> List[str]:
        return [
            self.SET_COMMAND_STRING,
            self._encoding.to_arg(),
            self._offset.to_arg(),
            str(self._value),
        ]

BitFieldSubCommands

Bases: ABC

Abstract Base Class representing subcommands for the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
179
180
181
182
183
184
185
186
187
class BitFieldSubCommands(ABC):
    """Abstract Base Class representing subcommands for the `BITFIELD` or `BITFIELD_RO` commands."""

    @abstractmethod
    def to_args(self) -> List[str]:
        """
        Returns the subcommand as a list of string arguments to be used in the `BITFIELD` or `BITFIELD_RO` commands.
        """
        pass

to_args() abstractmethod

Returns the subcommand as a list of string arguments to be used in the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
182
183
184
185
186
187
@abstractmethod
def to_args(self) -> List[str]:
    """
    Returns the subcommand as a list of string arguments to be used in the `BITFIELD` or `BITFIELD_RO` commands.
    """
    pass

BitmapIndexType

Bases: Enum

Enumeration specifying if index arguments are BYTE indexes or BIT indexes. Can be specified in OffsetOptions, which is an optional argument to the BITCOUNT command.

Since: Valkey 7.0.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class BitmapIndexType(Enum):
    """
    Enumeration specifying if index arguments are BYTE indexes or BIT indexes. Can be specified in `OffsetOptions`,
    which is an optional argument to the `BITCOUNT` command.

    Since: Valkey 7.0.0.
    """

    BYTE = "BYTE"
    """
    Specifies that indexes provided to `OffsetOptions` are byte indexes.
    """
    BIT = "BIT"
    """
    Specifies that indexes provided to `OffsetOptions` are bit indexes.
    """

BYTE = 'BYTE' class-attribute instance-attribute

Specifies that indexes provided to OffsetOptions are byte indexes.

BIT = 'BIT' class-attribute instance-attribute

Specifies that indexes provided to OffsetOptions are bit indexes.

BitOffset

Bases: BitFieldOffset

Represents an offset in an array of bits for the BITFIELD or BITFIELD_RO commands. Must be greater than or equal to 0.

For example, if we have the binary 01101001 with offset of 1 for an unsigned encoding of size 4, then the value is 13 from 0(1101)001.

Attributes:

Name Type Description
offset int

The bit index offset in the array of bits.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class BitOffset(BitFieldOffset):
    """
    Represents an offset in an array of bits for the `BITFIELD` or `BITFIELD_RO` commands. Must be greater than or
    equal to 0.

    For example, if we have the binary `01101001` with offset of 1 for an unsigned encoding of size 4, then the value
    is 13 from `0(1101)001`.

    Attributes:
        offset (int): The bit index offset in the array of bits.
    """

    def __init__(self, offset: int):
        self._offset = str(offset)

    def to_arg(self) -> str:
        return self._offset

BitOffsetMultiplier

Bases: BitFieldOffset

Represents an offset in an array of bits for the BITFIELD or BITFIELD_RO commands. The bit offset index is calculated as the numerical value of the offset multiplied by the encoding value. Must be greater than or equal to 0.

For example, if we have the binary 01101001 with offset multiplier of 1 for an unsigned encoding of size 4, then the value is 9 from 0110(1001).

Attributes:

Name Type Description
offset int

The offset in the array of bits, which will be multiplied by the encoding value to get the final bit index offset.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
class BitOffsetMultiplier(BitFieldOffset):
    """
    Represents an offset in an array of bits for the `BITFIELD` or `BITFIELD_RO` commands. The bit offset index is
    calculated as the numerical value of the offset multiplied by the encoding value. Must be greater than or equal
    to 0.

    For example, if we have the binary 01101001 with offset multiplier of 1 for an unsigned encoding of size 4, then
    the value is 9 from `0110(1001)`.

    Attributes:
        offset (int): The offset in the array of bits, which will be multiplied by the encoding value to get the
            final bit index offset.
    """

    #: Prefix specifying that the offset uses an encoding multiplier.
    OFFSET_MULTIPLIER_PREFIX = "#"

    def __init__(self, offset: int):
        self._offset = f"{self.OFFSET_MULTIPLIER_PREFIX}{str(offset)}"

    def to_arg(self) -> str:
        return self._offset

BitOverflowControl

Bases: Enum

Enumeration specifying bit overflow controls for the BITFIELD command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
class BitOverflowControl(Enum):
    """
    Enumeration specifying bit overflow controls for the `BITFIELD` command.
    """

    WRAP = "WRAP"
    """
    Performs modulo when overflows occur with unsigned encoding. When overflows occur with signed encoding, the value
    restarts at the most negative value. When underflows occur with signed encoding, the value restarts at the most
    positive value.
    """
    SAT = "SAT"
    """
    Underflows remain set to the minimum value, and overflows remain set to the maximum value.
    """
    FAIL = "FAIL"
    """
    Returns `None` when overflows occur.
    """

WRAP = 'WRAP' class-attribute instance-attribute

Performs modulo when overflows occur with unsigned encoding. When overflows occur with signed encoding, the value restarts at the most negative value. When underflows occur with signed encoding, the value restarts at the most positive value.

SAT = 'SAT' class-attribute instance-attribute

Underflows remain set to the minimum value, and overflows remain set to the maximum value.

FAIL = 'FAIL' class-attribute instance-attribute

Returns None when overflows occur.

BitwiseOperation

Bases: Enum

Enumeration defining the bitwise operation to use in the BITOP command. Specifies the bitwise operation to perform between the passed in keys.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
61
62
63
64
65
66
67
68
69
70
class BitwiseOperation(Enum):
    """
    Enumeration defining the bitwise operation to use in the `BITOP` command. Specifies the bitwise operation to
    perform between the passed in keys.
    """

    AND = "AND"
    OR = "OR"
    XOR = "XOR"
    NOT = "NOT"

OffsetOptions

Represents offsets specifying a string interval to analyze in the BITCOUNT command. The offsets are zero-based indexes, with 0 being the first index of the string, 1 being the next index and so on. The offsets can also be negative numbers indicating offsets starting at the end of the string, with -1 being the last index of the string, -2 being the penultimate, and so on.

Attributes:

Name Type Description
start int

The starting offset index.

end Optional[int]

The ending offset index. Optional since Valkey 8.0.0 for the BITCOUNT command. If not provided, it will default to the end of the string.

index_type Optional[BitmapIndexType]

The index offset type. This option can only be specified if you are using Valkey version 7.0.0 or above. Could be either BitmapIndexType.BYTE or BitmapIndexType.BIT. If no index type is provided, the indexes will be assumed to be byte indexes.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class OffsetOptions:
    """
    Represents offsets specifying a string interval to analyze in the `BITCOUNT` command. The offsets are
    zero-based indexes, with `0` being the first index of the string, `1` being the next index and so on.
    The offsets can also be negative numbers indicating offsets starting at the end of the string, with `-1` being
    the last index of the string, `-2` being the penultimate, and so on.

    Attributes:
        start (int): The starting offset index.
        end (Optional[int]): The ending offset index. Optional since Valkey 8.0.0 for the BITCOUNT
            command. If not provided, it will default to the end of the string.
        index_type (Optional[BitmapIndexType]): The index offset type. This option can only be specified if you are
            using Valkey version 7.0.0 or above. Could be either `BitmapIndexType.BYTE` or `BitmapIndexType.BIT`.
            If no index type is provided, the indexes will be assumed to be byte indexes.
    """

    def __init__(
        self,
        start: int,
        end: Optional[int] = None,
        index_type: Optional[BitmapIndexType] = None,
    ):
        self.start = start
        self.end = end
        self.index_type = index_type

    def to_args(self) -> List[str]:
        args = [str(self.start)]
        if self.end is not None:
            args.append(str(self.end))
        if self.index_type is not None:
            args.append(self.index_type.value)

        return args

SignedEncoding

Bases: BitEncoding

Represents a signed argument encoding. Must be less than 65 bits long.

Attributes:

Name Type Description
encoding_length int

The bit size of the encoding.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class SignedEncoding(BitEncoding):
    """
    Represents a signed argument encoding. Must be less than 65 bits long.

    Attributes:
        encoding_length (int): The bit size of the encoding.
    """

    #: Prefix specifying that the encoding is signed.
    SIGNED_ENCODING_PREFIX = "i"

    def __init__(self, encoding_length: int):
        self._encoding = f"{self.SIGNED_ENCODING_PREFIX}{str(encoding_length)}"

    def to_arg(self) -> str:
        return self._encoding

UnsignedEncoding

Bases: BitEncoding

Represents an unsigned argument encoding. Must be less than 64 bits long.

Attributes:

Name Type Description
encoding_length int

The bit size of the encoding.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class UnsignedEncoding(BitEncoding):
    """
    Represents an unsigned argument encoding. Must be less than 64 bits long.

    Attributes:
        encoding_length (int): The bit size of the encoding.
    """

    #: Prefix specifying that the encoding is unsigned.
    UNSIGNED_ENCODING_PREFIX = "u"

    def __init__(self, encoding_length: int):
        self._encoding = f"{self.UNSIGNED_ENCODING_PREFIX}{str(encoding_length)}"

    def to_arg(self) -> str:
        return self._encoding

ClientTrackingInfo dataclass

Represents a CLIENT TRACKINGINFO <https://valkey.io/commands/client-trackinginfo/>_ response.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/client_tracking.py
11
12
13
14
15
16
17
18
19
20
21
22
@dataclass
class ClientTrackingInfo:
    """Represents a `CLIENT TRACKINGINFO <https://valkey.io/commands/client-trackinginfo/>`_ response."""

    flags: Set[str]
    """Set of tracking flags."""

    redirect: int
    """Client ID receiving invalidation messages, or ``-1`` if not redirecting."""

    prefixes: Set[str]
    """Set of key prefixes monitored for invalidation."""

flags instance-attribute

Set of tracking flags.

redirect instance-attribute

Client ID receiving invalidation messages, or -1 if not redirecting.

prefixes instance-attribute

Set of key prefixes monitored for invalidation.

Limit

Represents a limit argument for range queries in various commands.

The LIMIT argument is commonly used to specify a subset of results from the matching elements, similar to the LIMIT clause in SQL (e.g., SELECT LIMIT offset, count).

This class can be utilized in multiple commands that support limit options, such as ZRANGE, SORT and others.

Parameters:

Name Type Description Default
offset int

The starting position of the range, zero based.

required
count int

The maximum number of elements to include in the range. A negative count returns all elements from the offset.

required

Examples:

>>> limit = Limit(0, 10)  # Fetch the first 10 elements
>>> limit = Limit(5, -1)  # Fetch all elements starting from the 5th element
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Limit:
    """
    Represents a limit argument for range queries in various commands.

    The `LIMIT` argument is commonly used to specify a subset of results from the matching elements,
    similar to the `LIMIT` clause in SQL (e.g., `SELECT LIMIT offset, count`).

    This class can be utilized in multiple commands that support limit options,
    such as [ZRANGE](https://valkey.io/commands/zrange), [SORT](https://valkey.io/commands/sort/) and others.

    Args:
        offset (int): The starting position of the range, zero based.
        count (int): The maximum number of elements to include in the range.
            A negative count returns all elements from the offset.

    Examples:
        >>> limit = Limit(0, 10)  # Fetch the first 10 elements
        >>> limit = Limit(5, -1)  # Fetch all elements starting from the 5th element
    """

    def __init__(self, offset: int, count: int):
        self.offset = offset
        self.count = count

ListDirection

Bases: Enum

Enumeration representing element popping or adding direction for List commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class ListDirection(Enum):
    """
    Enumeration representing element popping or adding direction for List commands.
    """

    LEFT = "LEFT"
    """
    LEFT: Represents the option that elements should be popped from or added to the left side of a list.
    """

    RIGHT = "RIGHT"
    """
    RIGHT: Represents the option that elements should be popped from or added to the right side of a list.
    """

LEFT = 'LEFT' class-attribute instance-attribute

LEFT: Represents the option that elements should be popped from or added to the left side of a list.

RIGHT = 'RIGHT' class-attribute instance-attribute

RIGHT: Represents the option that elements should be popped from or added to the right side of a list.

ObjectType

Bases: Enum

Enumeration representing the data types supported by the database.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class ObjectType(Enum):
    """
    Enumeration representing the data types supported by the database.
    """

    STRING = "String"
    """
    Represents a string data type.
    """

    LIST = "List"
    """
    Represents a list data type.
    """

    SET = "Set"
    """
    Represents a set data type.
    """

    ZSET = "ZSet"
    """
    Represents a sorted set data type.
    """

    HASH = "Hash"
    """
    Represents a hash data type.
    """

    STREAM = "Stream"
    """
    Represents a stream data type.
    """

STRING = 'String' class-attribute instance-attribute

Represents a string data type.

LIST = 'List' class-attribute instance-attribute

Represents a list data type.

SET = 'Set' class-attribute instance-attribute

Represents a set data type.

ZSET = 'ZSet' class-attribute instance-attribute

Represents a sorted set data type.

HASH = 'Hash' class-attribute instance-attribute

Represents a hash data type.

STREAM = 'Stream' class-attribute instance-attribute

Represents a stream data type.

OrderBy

Bases: Enum

Enumeration representing sorting order options.

This enum is used for the following commands:

- `SORT`: General sorting in ascending or descending order.
- `GEOSEARCH`: Sorting items based on their proximity to a center point.
- `FT.AGGREGATE`: Used in the SortBy clause of the FT.AGGREGATE command.
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class OrderBy(Enum):
    """
    Enumeration representing sorting order options.

    This enum is used for the following commands:

        - `SORT`: General sorting in ascending or descending order.
        - `GEOSEARCH`: Sorting items based on their proximity to a center point.
        - `FT.AGGREGATE`: Used in the SortBy clause of the FT.AGGREGATE command.

    """

    ASC = "ASC"
    """
    ASC: Sort in ascending order.
    """

    DESC = "DESC"
    """
    DESC: Sort in descending order.
    """

ASC = 'ASC' class-attribute instance-attribute

ASC: Sort in ascending order.

DESC = 'DESC' class-attribute instance-attribute

DESC: Sort in descending order.

ClientPauseMode

Bases: Enum

Mode option for the CLIENT PAUSE command.

See CLIENT PAUSE for details.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
443
444
445
446
447
448
449
450
451
452
453
454
class ClientPauseMode(Enum):
    """
    Mode option for the `CLIENT PAUSE` command.

    See [CLIENT PAUSE](https://valkey.io/commands/client-pause/) for details.
    """

    ALL = "ALL"
    """ Pause all client commands. """

    WRITE = "WRITE"
    """ Pause client write commands. """

ALL = 'ALL' class-attribute instance-attribute

Pause all client commands.

WRITE = 'WRITE' class-attribute instance-attribute

Pause client write commands.

ConditionalChange

Bases: Enum

A condition to the SET, ZADD, GEOADD and HSETEX commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class ConditionalChange(Enum):
    """
    A condition to the `SET`, `ZADD`, `GEOADD` and `HSETEX` commands.
    """

    ONLY_IF_EXISTS = "XX"
    """ Only update key / elements that already exist. Equivalent to `XX` in the Valkey API. """

    ONLY_IF_DOES_NOT_EXIST = "NX"
    """ Only set key / add elements that does not already exist. Equivalent to `NX` in the Valkey API. """

    def _to_args(self) -> List[TEncodable]:
        """
        Returns the condition as a list of command arguments.
        """
        return [self.value]

ONLY_IF_EXISTS = 'XX' class-attribute instance-attribute

Only update key / elements that already exist. Equivalent to XX in the Valkey API.

ONLY_IF_DOES_NOT_EXIST = 'NX' class-attribute instance-attribute

Only set key / add elements that does not already exist. Equivalent to NX in the Valkey API.

ExpireOptions

Bases: Enum

EXPIRE option: options for setting key expiry.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
class ExpireOptions(Enum):
    """
    EXPIRE option: options for setting key expiry.
    """

    HasNoExpiry = "NX"
    """ Set expiry only when the key has no expiry (Equivalent to "NX" in Valkey). """

    HasExistingExpiry = "XX"
    """ Set expiry only when the key has an existing expiry (Equivalent to "XX" in Valkey). """

    NewExpiryGreaterThanCurrent = "GT"
    """
    Set expiry only when the new expiry is greater than the current one (Equivalent to "GT" in Valkey).
    """

    NewExpiryLessThanCurrent = "LT"
    """
    Set expiry only when the new expiry is less than the current one (Equivalent to "LT" in Valkey).
    """

HasNoExpiry = 'NX' class-attribute instance-attribute

Set expiry only when the key has no expiry (Equivalent to "NX" in Valkey).

HasExistingExpiry = 'XX' class-attribute instance-attribute

Set expiry only when the key has an existing expiry (Equivalent to "XX" in Valkey).

NewExpiryGreaterThanCurrent = 'GT' class-attribute instance-attribute

Set expiry only when the new expiry is greater than the current one (Equivalent to "GT" in Valkey).

NewExpiryLessThanCurrent = 'LT' class-attribute instance-attribute

Set expiry only when the new expiry is less than the current one (Equivalent to "LT" in Valkey).

ExpiryGetEx

GetEx option: Represents the expiry type and value to be executed with "GetEx" command.

Attributes:

Name Type Description
cmd_arg str

The expiry type.

value str

The value for the expiry type.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
class ExpiryGetEx:
    """
    GetEx option: Represents the expiry type and value to be executed with "GetEx" command.

    Attributes:
        cmd_arg (str): The expiry type.
        value (str): The value for the expiry type.
    """

    def __init__(
        self,
        expiry_type: ExpiryTypeGetEx,
        value: Optional[Union[int, datetime, timedelta]],
    ) -> None:
        self.set_expiry_type_and_value(expiry_type, value)

    def set_expiry_type_and_value(
        self,
        expiry_type: ExpiryTypeGetEx,
        value: Optional[Union[int, datetime, timedelta]],
    ):
        """
        Args:
            expiry_type (ExpiryType): The expiry type.
            value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
                determines the type of expiration value:

                    - SEC: Union[int, timedelta]
                    - MILLSEC: Union[int, timedelta]
                    - UNIX_SEC: Union[int, datetime]
                    - UNIX_MILLSEC: Union[int, datetime]
                    - PERSIST: Type[None]
        """
        if not isinstance(value, get_args(expiry_type.value[1])):
            raise ValueError(
                f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
            )
        self.expiry_type = expiry_type
        if self.expiry_type == ExpiryTypeGetEx.SEC:
            self.cmd_arg = "EX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds())
        elif self.expiry_type == ExpiryTypeGetEx.MILLSEC:
            self.cmd_arg = "PX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds() * 1000)
        elif self.expiry_type == ExpiryTypeGetEx.UNIX_SEC:
            self.cmd_arg = "EXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp())
        elif self.expiry_type == ExpiryTypeGetEx.UNIX_MILLSEC:
            self.cmd_arg = "PXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp() * 1000)
        elif self.expiry_type == ExpiryTypeGetEx.PERSIST:
            self.cmd_arg = "PERSIST"
        self.value = str(value) if value is not None else None

    def get_cmd_args(self) -> List[str]:
        return [self.cmd_arg] if self.value is None else [self.cmd_arg, self.value]

set_expiry_type_and_value(expiry_type, value)

Parameters:

Name Type Description Default
expiry_type ExpiryType

The expiry type.

required
value Optional[Union[int, datetime, timedelta]]

The value of the expiration type. The type of expiration determines the type of expiration value:

- SEC: Union[int, timedelta]
- MILLSEC: Union[int, timedelta]
- UNIX_SEC: Union[int, datetime]
- UNIX_MILLSEC: Union[int, datetime]
- PERSIST: Type[None]
required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def set_expiry_type_and_value(
    self,
    expiry_type: ExpiryTypeGetEx,
    value: Optional[Union[int, datetime, timedelta]],
):
    """
    Args:
        expiry_type (ExpiryType): The expiry type.
        value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
            determines the type of expiration value:

                - SEC: Union[int, timedelta]
                - MILLSEC: Union[int, timedelta]
                - UNIX_SEC: Union[int, datetime]
                - UNIX_MILLSEC: Union[int, datetime]
                - PERSIST: Type[None]
    """
    if not isinstance(value, get_args(expiry_type.value[1])):
        raise ValueError(
            f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
        )
    self.expiry_type = expiry_type
    if self.expiry_type == ExpiryTypeGetEx.SEC:
        self.cmd_arg = "EX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds())
    elif self.expiry_type == ExpiryTypeGetEx.MILLSEC:
        self.cmd_arg = "PX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds() * 1000)
    elif self.expiry_type == ExpiryTypeGetEx.UNIX_SEC:
        self.cmd_arg = "EXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp())
    elif self.expiry_type == ExpiryTypeGetEx.UNIX_MILLSEC:
        self.cmd_arg = "PXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp() * 1000)
    elif self.expiry_type == ExpiryTypeGetEx.PERSIST:
        self.cmd_arg = "PERSIST"
    self.value = str(value) if value is not None else None

ExpirySet

SET option: Represents the expiry type and value to be executed with "SET" command.

Attributes:

Name Type Description
cmd_arg str

The expiry type.

value str

The value for the expiry type.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
class ExpirySet:
    """
    SET option: Represents the expiry type and value to be executed with "SET" command.

    Attributes:
        cmd_arg (str): The expiry type.
        value (str): The value for the expiry type.
    """

    def __init__(
        self,
        expiry_type: ExpiryType,
        value: Optional[Union[int, datetime, timedelta]],
    ) -> None:
        self.set_expiry_type_and_value(expiry_type, value)

    def __eq__(self, other: "object") -> bool:
        if not isinstance(other, ExpirySet):
            return NotImplemented
        return self.expiry_type == other.expiry_type and self.value == other.value

    def set_expiry_type_and_value(
        self, expiry_type: ExpiryType, value: Optional[Union[int, datetime, timedelta]]
    ):
        """
        Args:
            expiry_type (ExpiryType): The expiry type.
            value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
                determines the type of expiration value:

                    - SEC: Union[int, timedelta]
                    - MILLSEC: Union[int, timedelta]
                    - UNIX_SEC: Union[int, datetime]
                    - UNIX_MILLSEC: Union[int, datetime]
                    - KEEP_TTL: Type[None]
        """
        if not isinstance(value, get_args(expiry_type.value[1])):
            raise ValueError(
                f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
            )
        self.expiry_type = expiry_type
        if self.expiry_type == ExpiryType.SEC:
            self.cmd_arg = "EX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds())
        elif self.expiry_type == ExpiryType.MILLSEC:
            self.cmd_arg = "PX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds() * 1000)
        elif self.expiry_type == ExpiryType.UNIX_SEC:
            self.cmd_arg = "EXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp())
        elif self.expiry_type == ExpiryType.UNIX_MILLSEC:
            self.cmd_arg = "PXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp() * 1000)
        elif self.expiry_type == ExpiryType.KEEP_TTL:
            self.cmd_arg = "KEEPTTL"
        self.value = str(value) if value is not None else None

    def get_cmd_args(self) -> List[str]:
        return [self.cmd_arg] if self.value is None else [self.cmd_arg, self.value]

set_expiry_type_and_value(expiry_type, value)

Parameters:

Name Type Description Default
expiry_type ExpiryType

The expiry type.

required
value Optional[Union[int, datetime, timedelta]]

The value of the expiration type. The type of expiration determines the type of expiration value:

- SEC: Union[int, timedelta]
- MILLSEC: Union[int, timedelta]
- UNIX_SEC: Union[int, datetime]
- UNIX_MILLSEC: Union[int, datetime]
- KEEP_TTL: Type[None]
required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def set_expiry_type_and_value(
    self, expiry_type: ExpiryType, value: Optional[Union[int, datetime, timedelta]]
):
    """
    Args:
        expiry_type (ExpiryType): The expiry type.
        value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
            determines the type of expiration value:

                - SEC: Union[int, timedelta]
                - MILLSEC: Union[int, timedelta]
                - UNIX_SEC: Union[int, datetime]
                - UNIX_MILLSEC: Union[int, datetime]
                - KEEP_TTL: Type[None]
    """
    if not isinstance(value, get_args(expiry_type.value[1])):
        raise ValueError(
            f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
        )
    self.expiry_type = expiry_type
    if self.expiry_type == ExpiryType.SEC:
        self.cmd_arg = "EX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds())
    elif self.expiry_type == ExpiryType.MILLSEC:
        self.cmd_arg = "PX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds() * 1000)
    elif self.expiry_type == ExpiryType.UNIX_SEC:
        self.cmd_arg = "EXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp())
    elif self.expiry_type == ExpiryType.UNIX_MILLSEC:
        self.cmd_arg = "PXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp() * 1000)
    elif self.expiry_type == ExpiryType.KEEP_TTL:
        self.cmd_arg = "KEEPTTL"
    self.value = str(value) if value is not None else None

ExpiryType

Bases: Enum

SET option: The type of the expiry.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
class ExpiryType(Enum):
    """
    SET option: The type of the expiry.
    """

    SEC = 0, Union[int, timedelta]
    """
    Set the specified expire time, in seconds. Equivalent to `EX` in the Valkey API.
    """

    MILLSEC = 1, Union[int, timedelta]
    """
    Set the specified expire time, in milliseconds. Equivalent to `PX` in the Valkey API.
    """

    UNIX_SEC = 2, Union[int, datetime]
    """
    Set the specified Unix time at which the key will expire, in seconds. Equivalent to `EXAT` in the Valkey API.
    """

    UNIX_MILLSEC = 3, Union[int, datetime]
    """
    Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to `PXAT` in the Valkey API.
    """

    KEEP_TTL = 4, Type[None]
    """
    Retain the time to live associated with the key. Equivalent to `KEEPTTL` in the Valkey API.
    """

SEC = (0, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in seconds. Equivalent to EX in the Valkey API.

MILLSEC = (1, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in milliseconds. Equivalent to PX in the Valkey API.

UNIX_SEC = (2, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in seconds. Equivalent to EXAT in the Valkey API.

UNIX_MILLSEC = (3, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to PXAT in the Valkey API.

KEEP_TTL = (4, Type[None]) class-attribute instance-attribute

Retain the time to live associated with the key. Equivalent to KEEPTTL in the Valkey API.

ExpiryTypeGetEx

Bases: Enum

GetEx option: The type of the expiry.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
class ExpiryTypeGetEx(Enum):
    """
    GetEx option: The type of the expiry.
    """

    SEC = 0, Union[int, timedelta]
    """ Set the specified expire time, in seconds. Equivalent to `EX` in the Valkey API. """

    MILLSEC = 1, Union[int, timedelta]
    """ Set the specified expire time, in milliseconds. Equivalent to `PX` in the Valkey API. """

    UNIX_SEC = 2, Union[int, datetime]
    """ Set the specified Unix time at which the key will expire, in seconds. Equivalent to `EXAT` in the Valkey API. """

    UNIX_MILLSEC = 3, Union[int, datetime]
    """ Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to `PXAT` in the Valkey API. """

    PERSIST = 4, Type[None]
    """ Remove the time to live associated with the key. Equivalent to `PERSIST` in the Valkey API. """

SEC = (0, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in seconds. Equivalent to EX in the Valkey API.

MILLSEC = (1, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in milliseconds. Equivalent to PX in the Valkey API.

UNIX_SEC = (2, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in seconds. Equivalent to EXAT in the Valkey API.

UNIX_MILLSEC = (3, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to PXAT in the Valkey API.

PERSIST = (4, Type[None]) class-attribute instance-attribute

Remove the time to live associated with the key. Equivalent to PERSIST in the Valkey API.

FlushMode

Bases: Enum

Defines flushing mode for:

FLUSHALL command and FUNCTION FLUSH command.

See FLUSHALL and FUNCTION-FLUSH for details

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
411
412
413
414
415
416
417
418
419
420
421
422
class FlushMode(Enum):
    """
    Defines flushing mode for:

    `FLUSHALL` command and `FUNCTION FLUSH` command.

    See [FLUSHALL](https://valkey.io/commands/flushall/) and [FUNCTION-FLUSH](https://valkey.io/commands/function-flush/)
    for details
    """

    ASYNC = "ASYNC"
    SYNC = "SYNC"

FunctionRestorePolicy

Bases: Enum

Options for the FUNCTION RESTORE command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
class FunctionRestorePolicy(Enum):
    """
    Options for the FUNCTION RESTORE command.
    """

    APPEND = "APPEND"
    """ Appends the restored libraries to the existing libraries and aborts on collision. This is the default policy. """

    FLUSH = "FLUSH"
    """ Deletes all existing libraries before restoring the payload. """

    REPLACE = "REPLACE"
    """
    Appends the restored libraries to the existing libraries, replacing any existing ones in case
    of name collisions. Note that this policy doesn't prevent function name collisions, only libraries.
    """

APPEND = 'APPEND' class-attribute instance-attribute

Appends the restored libraries to the existing libraries and aborts on collision. This is the default policy.

FLUSH = 'FLUSH' class-attribute instance-attribute

Deletes all existing libraries before restoring the payload.

REPLACE = 'REPLACE' class-attribute instance-attribute

Appends the restored libraries to the existing libraries, replacing any existing ones in case of name collisions. Note that this policy doesn't prevent function name collisions, only libraries.

HashFieldConditionalChange

Bases: Enum

Field conditional change options for HSETEX command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
66
67
68
69
70
71
72
73
74
75
class HashFieldConditionalChange(Enum):
    """
    Field conditional change options for HSETEX command.
    """

    ONLY_IF_ALL_EXIST = "FXX"
    """ Only set fields if all of them already exist. Equivalent to `FXX` in the Valkey API. """

    ONLY_IF_NONE_EXIST = "FNX"
    """ Only set fields if none of them already exist. Equivalent to `FNX` in the Valkey API. """

ONLY_IF_ALL_EXIST = 'FXX' class-attribute instance-attribute

Only set fields if all of them already exist. Equivalent to FXX in the Valkey API.

ONLY_IF_NONE_EXIST = 'FNX' class-attribute instance-attribute

Only set fields if none of them already exist. Equivalent to FNX in the Valkey API.

InfoSection

Bases: Enum

INFO option: a specific section of information:

When no parameter is provided, the default option is assumed.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
class InfoSection(Enum):
    """
    INFO option: a specific section of information:

    When no parameter is provided, the default option is assumed.
    """

    ALL = "all"
    """ Return all sections (excluding module generated ones) """

    CLIENTS = "clients"
    """ Client connections section """

    CLUSTER = "cluster"
    """ Valkey Cluster section """

    CLUSTER_INFO = "cluster_info"
    """
    Valkey Cluster information.

    Since: Valkey 9.1.0.
    """

    COMMAND_STATS = "commandstats"
    """ Valkey command statistics """

    CPU = "cpu"
    """ CPU consumption statistics """

    DEFAULT = "default"
    """ Return only the default set of sections """

    ERROR_STATS = "errorstats"
    """ Valkey error statistics """

    EVERYTHING = "everything"
    """ Includes all and modules """

    KEYSPACE = "keyspace"
    """ Database related statistics """

    LATENCY_STATS = "latencystats"
    """ Valkey command latency percentile distribution statistics """

    MEMORY = "memory"
    """ Memory consumption related information """

    MODULES = "modules"
    """ Modules section """

    PERSISTENCE = "persistence"
    """ RDB and AOF related information """

    REPLICATION = "replication"
    """ Master/replica replication information """

    SENTINEL = "sentinel"
    """ Valkey Sentinel section (only applicable to Sentinel instances) """

    SERVER = "server"
    """ General information about the server """

    STATS = "stats"
    """ General statistics """

ALL = 'all' class-attribute instance-attribute

Return all sections (excluding module generated ones)

CLIENTS = 'clients' class-attribute instance-attribute

Client connections section

CLUSTER = 'cluster' class-attribute instance-attribute

Valkey Cluster section

CLUSTER_INFO = 'cluster_info' class-attribute instance-attribute

Valkey Cluster information.

Since: Valkey 9.1.0.

COMMAND_STATS = 'commandstats' class-attribute instance-attribute

Valkey command statistics

CPU = 'cpu' class-attribute instance-attribute

CPU consumption statistics

DEFAULT = 'default' class-attribute instance-attribute

Return only the default set of sections

ERROR_STATS = 'errorstats' class-attribute instance-attribute

Valkey error statistics

EVERYTHING = 'everything' class-attribute instance-attribute

Includes all and modules

KEYSPACE = 'keyspace' class-attribute instance-attribute

Database related statistics

LATENCY_STATS = 'latencystats' class-attribute instance-attribute

Valkey command latency percentile distribution statistics

MEMORY = 'memory' class-attribute instance-attribute

Memory consumption related information

MODULES = 'modules' class-attribute instance-attribute

Modules section

PERSISTENCE = 'persistence' class-attribute instance-attribute

RDB and AOF related information

REPLICATION = 'replication' class-attribute instance-attribute

Master/replica replication information

SENTINEL = 'sentinel' class-attribute instance-attribute

Valkey Sentinel section (only applicable to Sentinel instances)

SERVER = 'server' class-attribute instance-attribute

General information about the server

STATS = 'stats' class-attribute instance-attribute

General statistics

MigrateOptions dataclass

Optional arguments for the migrate command. See valkey.io for details.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
@dataclass
class MigrateOptions:
    """
    Optional arguments for the `migrate` command.
    See [valkey.io](https://valkey.io/commands/migrate/) for details.
    """

    copy: bool = False
    replace: bool = False
    password: Optional[str] = None
    username: Optional[str] = None

    def to_args(self) -> List[TEncodable]:
        if self.username is not None and self.password is None:
            raise ValueError("MigrateOptions: 'username' requires 'password' to be set")
        args: List[TEncodable] = []
        if self.copy:
            args.append("COPY")
        if self.replace:
            args.append("REPLACE")
        if self.username is not None and self.password is not None:
            args.extend(["AUTH2", self.username, self.password])
        elif self.password is not None:
            args.extend(["AUTH", self.password])
        return args

MonitorMsg dataclass

Represents a single line received from the MONITOR command.

Attributes:

Name Type Description
timestamp float

Unix timestamp of the command.

db int

Database index on which the command was executed.

client_addr str

Address of the client that issued the command.

command str

The command name.

args List[str]

The command arguments.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@dataclass
class MonitorMsg:
    """
    Represents a single line received from the MONITOR command.

    Attributes:
        timestamp (float): Unix timestamp of the command.
        db (int): Database index on which the command was executed.
        client_addr (str): Address of the client that issued the command.
        command (str): The command name.
        args (List[str]): The command arguments.
    """

    timestamp: float
    db: int
    client_addr: str
    command: str
    args: List[str]

OnlyIfEqual dataclass

Bases: ValueComparison

A condition that is met if the key exists and its current value is equal to the comparison value. Used by the SET command. Equivalent to the IFEQ comparison-value in the Valkey API.

Not supported when compression is enabled. See Valkey GLIDE - Data Compression <https://glide.valkey.io/concepts/client-features/compression/#incompatible-commands>_.

Since: Valkey 8.1.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
class OnlyIfEqual(ValueComparison):
    """
    A condition that is met if the key exists and its current value is equal to the comparison value.
    Used by the `SET` command. Equivalent to the `IFEQ comparison-value` in the Valkey API.

    Not supported when compression is enabled. See
    `Valkey GLIDE - Data Compression <https://glide.valkey.io/concepts/client-features/compression/#incompatible-commands>`_.

    Since: Valkey 8.1.0.
    """

    def _to_args(self) -> List[TEncodable]:
        return ["IFEQ", self.comparison_value]

OnlyIfNotEqual dataclass

Bases: ValueComparison

A condition that is met if the key does not exist or its current value is not equal to the comparison value. Used by the SET command. Equivalent to the IFNE comparison-value in the Valkey API.

Not supported when compression is enabled. See Valkey GLIDE - Data Compression <https://glide.valkey.io/concepts/client-features/compression/#incompatible-commands>_.

Since: Valkey 9.2.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
112
113
114
115
116
117
118
119
120
121
122
123
124
class OnlyIfNotEqual(ValueComparison):
    """
    A condition that is met if the key does not exist or its current value is not equal to the comparison value.
    Used by the `SET` command. Equivalent to the `IFNE comparison-value` in the Valkey API.

    Not supported when compression is enabled. See
    `Valkey GLIDE - Data Compression <https://glide.valkey.io/concepts/client-features/compression/#incompatible-commands>`_.

    Since: Valkey 9.2.0.
    """

    def _to_args(self) -> List[TEncodable]:
        return ["IFNE", self.comparison_value]

PubSubMsg dataclass

Describes the incoming pubsub message

Attributes:

Name Type Description
message TEncodable

Incoming message.

channel TEncodable

Name of an channel that triggered the message.

pattern Optional[TEncodable]

Pattern that triggered the message.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@dataclass
class PubSubMsg:
    """
    Describes the incoming pubsub message

    Attributes:
        message (TEncodable): Incoming message.
        channel (TEncodable): Name of an channel that triggered the message.
        pattern (Optional[TEncodable]): Pattern that triggered the message.
    """

    message: TEncodable
    channel: TEncodable
    pattern: Optional[TEncodable]

UpdateOptions

Bases: Enum

Options for updating elements of a sorted set key.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
267
268
269
270
271
272
273
274
275
276
class UpdateOptions(Enum):
    """
    Options for updating elements of a sorted set key.
    """

    LESS_THAN = "LT"
    """ Only update existing elements if the new score is less than the current score. """

    GREATER_THAN = "GT"
    """ Only update existing elements if the new score is greater than the current score. """

LESS_THAN = 'LT' class-attribute instance-attribute

Only update existing elements if the new score is less than the current score.

GREATER_THAN = 'GT' class-attribute instance-attribute

Only update existing elements if the new score is greater than the current score.

ValueComparison dataclass

Bases: ABC

A condition that compares the current value of a key to a comparison value.

Attributes:

Name Type Description
comparison_value TEncodable

The value to compare to the current value of a key.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@dataclass
class ValueComparison(ABC):
    """
    A condition that compares the current value of a key to a comparison value.

    Attributes:
        comparison_value (TEncodable): The value to compare to the current value of a key.
    """

    comparison_value: TEncodable

    @abstractmethod
    def _to_args(self) -> List[TEncodable]:
        """
        Returns the condition as a list of command arguments.
        """
        pass

LatencyEntry dataclass

Represents the time and latency for a latency spike.

Attributes:

Name Type Description
time int

The time of the latency spike, as a Unix timestamp in seconds.

latency int

The duration of the latency spike, in milliseconds.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/latency.py
13
14
15
16
17
18
19
20
21
22
23
@dataclass
class LatencyEntry:
    """Represents the time and latency for a latency spike.

    Attributes:
        time (int): The time of the latency spike, as a Unix timestamp in seconds.
        latency (int): The duration of the latency spike, in milliseconds.
    """

    time: int
    latency: int

LatencyEventInfo dataclass

Represents information about an event's latency spike time series.

Attributes:

Name Type Description
event_name str

The name of the event.

latest_time int

The time of the latest latency spike, as a Unix timestamp in seconds.

latest_duration int

The duration of the latest latency spike, in milliseconds.

max_duration int

The all-time maximum duration of a latency spike, in milliseconds.

sum Optional[int]

The sum of all latency spike durations in the event's time series, in milliseconds. Only populated for Valkey 8.1+.

count Optional[int]

The number of latency spikes recorded in the event's time series. Only populated for Valkey 8.1+.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/latency.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@dataclass
class LatencyEventInfo:
    """Represents information about an event's latency spike time series.

    Attributes:
        event_name (str): The name of the event.
        latest_time (int): The time of the latest latency spike, as a Unix
            timestamp in seconds.
        latest_duration (int): The duration of the latest latency spike, in milliseconds.
        max_duration (int): The all-time maximum duration of a latency spike, in milliseconds.
        sum (Optional[int]): The sum of all latency spike durations in the event's
            time series, in milliseconds. Only populated for Valkey 8.1+.
        count (Optional[int]): The number of latency spikes recorded in the event's
            time series. Only populated for Valkey 8.1+.
    """

    event_name: str
    latest_time: int
    latest_duration: int
    max_duration: int
    sum: Optional[int] = None
    count: Optional[int] = None

MemoryStats dataclass

Represents a MEMORY STATS response.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/memory.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@dataclass
class MemoryStats:
    """Represents a MEMORY STATS response."""

    db: Dict[int, MemoryStatsDb] = field(default_factory=dict)

    allocator_active: int = 0
    allocator_allocated: int = 0
    allocator_fragmentation_bytes: int = 0
    allocator_resident: int = 0
    allocator_rss_bytes: int = 0
    aof_buffer: int = 0
    clients_normal: int = 0
    clients_slaves: int = 0
    dataset_bytes: int = 0
    fragmentation_bytes: int = 0
    keys_bytes_per_key: int = 0
    keys_count: int = 0
    lua_caches: int = 0
    overhead_total: int = 0
    peak_allocated: int = 0
    replication_backlog: int = 0
    rss_overhead_bytes: int = 0
    startup_allocated: int = 0
    total_allocated: int = 0

    allocator_fragmentation_ratio: float = 0.0
    allocator_rss_ratio: float = 0.0
    dataset_percentage: float = 0.0
    fragmentation: float = 0.0
    peak_percentage: float = 0.0
    rss_overhead_ratio: float = 0.0

    # Optional Redis 7.0+ fields
    cluster_links: Optional[int] = None
    functions_caches: Optional[int] = None

    # Optional Valkey 8.0+ fields
    allocator_muzzy: Optional[int] = None
    db_dict_rehashing_count: Optional[int] = None
    overhead_db_hashtable_lut: Optional[int] = None
    overhead_db_hashtable_rehashing: Optional[int] = None

MemoryStatsDb dataclass

Database memory overhead statistics from MEMORY STATS.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/memory.py
11
12
13
14
15
16
@dataclass
class MemoryStatsDb:
    """Database memory overhead statistics from MEMORY STATS."""

    overhead_hashtable_main: int
    overhead_hashtable_expires: int

AggregationType

Bases: Enum

Enumeration representing aggregation types for ZINTERSTORE and ZUNIONSTORE sorted set commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class AggregationType(Enum):
    """
    Enumeration representing aggregation types for `ZINTERSTORE` and `ZUNIONSTORE` sorted set commands.
    """

    SUM = "SUM"
    """
    Represents aggregation by summing the scores of elements across inputs where they exist.
    """
    MIN = "MIN"
    """
    Represents aggregation by selecting the minimum score of an element across inputs where it exists.
    """
    MAX = "MAX"
    """
    Represents aggregation by selecting the maximum score of an element across inputs where it exists.
    """

SUM = 'SUM' class-attribute instance-attribute

Represents aggregation by summing the scores of elements across inputs where they exist.

MIN = 'MIN' class-attribute instance-attribute

Represents aggregation by selecting the minimum score of an element across inputs where it exists.

MAX = 'MAX' class-attribute instance-attribute

Represents aggregation by selecting the maximum score of an element across inputs where it exists.

GeoSearchByBox

Represents search criteria of searching within a specified rectangular area.

Attributes:

Name Type Description
width float

Width of the bounding box.

height float

Height of the bounding box

unit GeoUnit

Unit of the radius. See GeoUnit.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
class GeoSearchByBox:
    """
    Represents search criteria of searching within a specified rectangular area.

    Attributes:
        width (float): Width of the bounding box.
        height (float): Height of the bounding box
        unit (GeoUnit): Unit of the radius. See `GeoUnit`.
    """

    def __init__(self, width: float, height: float, unit: GeoUnit):
        """
        Initialize the search criteria.
        """
        self.width = width
        self.height = height
        self.unit = unit

    def to_args(self) -> List[str]:
        """
        Convert the search criteria to the corresponding part of the command.

        Returns:
            List[str]: List representation of the search criteria.
        """
        return ["BYBOX", str(self.width), str(self.height), self.unit.value]

to_args()

Convert the search criteria to the corresponding part of the command.

Returns:

Type Description
List[str]

List[str]: List representation of the search criteria.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
252
253
254
255
256
257
258
259
def to_args(self) -> List[str]:
    """
    Convert the search criteria to the corresponding part of the command.

    Returns:
        List[str]: List representation of the search criteria.
    """
    return ["BYBOX", str(self.width), str(self.height), self.unit.value]

GeoSearchByRadius

Represents search criteria of searching within a certain radius from a specified point.

Attributes:

Name Type Description
radius float

Radius of the search area.

unit GeoUnit

Unit of the radius. See GeoUnit.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class GeoSearchByRadius:
    """
    Represents search criteria of searching within a certain radius from a specified point.

    Attributes:
        radius (float): Radius of the search area.
        unit (GeoUnit): Unit of the radius. See `GeoUnit`.
    """

    def __init__(self, radius: float, unit: GeoUnit):
        """
        Initialize the search criteria.
        """
        self.radius = radius
        self.unit = unit

    def to_args(self) -> List[str]:
        """
        Convert the search criteria to the corresponding part of the command.

        Returns:
            List[str]: List representation of the search criteria.
        """
        return ["BYRADIUS", str(self.radius), self.unit.value]

to_args()

Convert the search criteria to the corresponding part of the command.

Returns:

Type Description
List[str]

List[str]: List representation of the search criteria.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
224
225
226
227
228
229
230
231
def to_args(self) -> List[str]:
    """
    Convert the search criteria to the corresponding part of the command.

    Returns:
        List[str]: List representation of the search criteria.
    """
    return ["BYRADIUS", str(self.radius), self.unit.value]

GeoSearchCount

Represents the count option for limiting the number of results in a GeoSearch.

Attributes:

Name Type Description
count int

The maximum number of results to return.

any_option bool

Whether to allow returning as enough matches are found. This means that the results returned may not be the ones closest to the specified point. Default to False.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class GeoSearchCount:
    """
    Represents the count option for limiting the number of results in a GeoSearch.

    Attributes:
        count (int): The maximum number of results to return.
        any_option (bool): Whether to allow returning as enough matches are found.
            This means that the results returned may not be the ones closest to the specified point. Default to False.
    """

    def __init__(self, count: int, any_option: bool = False):
        """
        Initialize the count option.
        """
        self.count = count
        self.any_option = any_option

    def to_args(self) -> List[str]:
        """
        Convert the count option to the corresponding part of the command.

        Returns:
            List[str]: List representation of the count option.
        """
        if self.any_option:
            return ["COUNT", str(self.count), "ANY"]
        return ["COUNT", str(self.count)]

to_args()

Convert the count option to the corresponding part of the command.

Returns:

Type Description
List[str]

List[str]: List representation of the count option.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
279
280
281
282
283
284
285
286
287
288
def to_args(self) -> List[str]:
    """
    Convert the count option to the corresponding part of the command.

    Returns:
        List[str]: List representation of the count option.
    """
    if self.any_option:
        return ["COUNT", str(self.count), "ANY"]
    return ["COUNT", str(self.count)]

GeospatialData

Represents a geographic position defined by longitude and latitude.

The exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:

- Valid longitudes are from -180 to 180 degrees.
- Valid latitudes are from -85.05112878 to 85.05112878 degrees.

Attributes:

Name Type Description
longitude float

The longitude coordinate.

latitude float

The latitude coordinate.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class GeospatialData:
    """
    Represents a geographic position defined by longitude and latitude.

    The exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:

        - Valid longitudes are from -180 to 180 degrees.
        - Valid latitudes are from -85.05112878 to 85.05112878 degrees.

    Attributes:
        longitude (float): The longitude coordinate.
        latitude (float): The latitude coordinate.
    """

    def __init__(self, longitude: float, latitude: float):
        self.longitude = longitude
        self.latitude = latitude

GeoUnit

Bases: Enum

Enumeration representing distance units options for the GEODIST command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class GeoUnit(Enum):
    """
    Enumeration representing distance units options for the `GEODIST` command.
    """

    METERS = "m"
    """
    Represents distance in meters.
    """
    KILOMETERS = "km"
    """
    Represents distance in kilometers.
    """
    MILES = "mi"
    """
    Represents distance in miles.
    """
    FEET = "ft"
    """
    Represents distance in feet.
    """

METERS = 'm' class-attribute instance-attribute

Represents distance in meters.

KILOMETERS = 'km' class-attribute instance-attribute

Represents distance in kilometers.

MILES = 'mi' class-attribute instance-attribute

Represents distance in miles.

FEET = 'ft' class-attribute instance-attribute

Represents distance in feet.

InfBound

Bases: Enum

Enumeration representing numeric and lexicographic positive and negative infinity bounds for sorted set.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class InfBound(Enum):
    """
    Enumeration representing numeric and lexicographic positive and negative infinity bounds for sorted set.
    """

    POS_INF = {"score_arg": "+inf", "lex_arg": "+"}
    """
    Positive infinity bound for sorted set.

    `score_arg`: represents numeric positive infinity (+inf).

    `lex_arg`: represents lexicographic positive infinity (+).
    """
    NEG_INF = {"score_arg": "-inf", "lex_arg": "-"}
    """
    Negative infinity bound for sorted set.

    `score_arg`: represents numeric negative infinity (-inf).

    `lex_arg`: represents lexicographic negative infinity (-).
    """

POS_INF = {'score_arg': '+inf', 'lex_arg': '+'} class-attribute instance-attribute

Positive infinity bound for sorted set.

score_arg: represents numeric positive infinity (+inf).

lex_arg: represents lexicographic positive infinity (+).

NEG_INF = {'score_arg': '-inf', 'lex_arg': '-'} class-attribute instance-attribute

Negative infinity bound for sorted set.

score_arg: represents numeric negative infinity (-inf).

lex_arg: represents lexicographic negative infinity (-).

LexBoundary

Represents a specific lexicographic boundary in a sorted set.

Parameters:

Name Type Description Default
value str

The lex value.

required
is_inclusive bool

Whether the score value is inclusive. Defaults to True.

True
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
84
85
86
87
88
89
90
91
92
93
94
95
class LexBoundary:
    """
    Represents a specific lexicographic boundary in a sorted set.

    Args:
        value (str): The lex value.
        is_inclusive (bool): Whether the score value is inclusive. Defaults to True.
    """

    def __init__(self, value: str, is_inclusive: bool = True):
        # Convert the lexicographic boundary to Valkey protocol format
        self.value = f"[{value}" if is_inclusive else f"({value}"

RangeByIndex

Represents a range by index (rank) in a sorted set.

The start and end arguments represent zero-based indexes.

Attributes:

Name Type Description
start int

The start index of the range.

end int

The end index of the range.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class RangeByIndex:
    """
    Represents a range by index (rank) in a sorted set.

    The `start` and `end` arguments represent zero-based indexes.

    Attributes:
        start (int): The start index of the range.
        end (int): The end index of the range.
    """

    def __init__(self, start: int, end: int):
        self.start = start
        self.end = end

RangeByLex

Represents a range by lexicographical order in a sorted set.

The start and end arguments represent lexicographical boundaries.

Attributes:

Name Type Description
start Union[InfBound, LexBoundary]

The start lexicographic boundary.

end Union[InfBound, LexBoundary]

The end lexicographic boundary.

limit Optional[Limit]

The limit argument for a range query. Defaults to None. See Limit class for more information.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
class RangeByLex:
    """
    Represents a range by lexicographical order in a sorted set.

    The `start` and `end` arguments represent lexicographical boundaries.

    Attributes:
        start (Union[InfBound, LexBoundary]): The start lexicographic boundary.
        end (Union[InfBound, LexBoundary]): The end lexicographic boundary.
        limit (Optional[Limit]): The limit argument for a range query. Defaults to None. See `Limit` class
            for more information.
    """

    def __init__(
        self,
        start: Union[InfBound, LexBoundary],
        end: Union[InfBound, LexBoundary],
        limit: Optional[Limit] = None,
    ):
        self.start = (
            start.value["lex_arg"] if isinstance(start, InfBound) else start.value
        )
        self.end = end.value["lex_arg"] if isinstance(end, InfBound) else end.value
        self.limit = limit

RangeByScore

Represents a range by score in a sorted set.

The start and end arguments represent score boundaries.

Attributes:

Name Type Description
start Union[InfBound, ScoreBoundary]

The start score boundary.

end Union[InfBound, ScoreBoundary]

The end score boundary.

limit Optional[Limit]

The limit argument for a range query. Defaults to None. See Limit class for more information.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class RangeByScore:
    """
    Represents a range by score in a sorted set.

    The `start` and `end` arguments represent score boundaries.

    Attributes:
        start (Union[InfBound, ScoreBoundary]): The start score boundary.
        end (Union[InfBound, ScoreBoundary]): The end score boundary.
        limit (Optional[Limit]): The limit argument for a range query. Defaults to None. See `Limit`
            class for more information.
    """

    def __init__(
        self,
        start: Union[InfBound, ScoreBoundary],
        end: Union[InfBound, ScoreBoundary],
        limit: Optional[Limit] = None,
    ):
        self.start = (
            start.value["score_arg"] if isinstance(start, InfBound) else start.value
        )
        self.end = end.value["score_arg"] if isinstance(end, InfBound) else end.value
        self.limit = limit

ScoreBoundary

Represents a specific numeric score boundary in a sorted set.

Parameters:

Name Type Description Default
value float

The score value.

required
is_inclusive bool

Whether the score value is inclusive. Defaults to True.

True
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
70
71
72
73
74
75
76
77
78
79
80
81
class ScoreBoundary:
    """
    Represents a specific numeric score boundary in a sorted set.

    Args:
        value (float): The score value.
        is_inclusive (bool): Whether the score value is inclusive. Defaults to True.
    """

    def __init__(self, value: float, is_inclusive: bool = True):
        # Convert the score boundary to Valkey protocol format
        self.value = str(value) if is_inclusive else f"({value}"

ScoreFilter

Bases: Enum

Defines which elements to pop from a sorted set.

ScoreFilter is a mandatory option for ZMPOP and BZMPOP.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class ScoreFilter(Enum):
    """
    Defines which elements to pop from a sorted set.

    ScoreFilter is a mandatory option for [ZMPOP](https://valkey.io/commands/zmpop)
    and [BZMPOP](https://valkey.io/commands/bzmpop).
    """

    MIN = "MIN"
    """
    Pop elements with the lowest scores.
    """
    MAX = "MAX"
    """
    Pop elements with the highest scores.
    """

MIN = 'MIN' class-attribute instance-attribute

Pop elements with the lowest scores.

MAX = 'MAX' class-attribute instance-attribute

Pop elements with the highest scores.

ExclusiveIdBound

Bases: StreamRangeBound

Exclusive (open) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete with a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can also be incomplete, with just a timestamp.

Attributes:

Name Type Description
stream_id TEncodable

The stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
class ExclusiveIdBound(StreamRangeBound):
    """
    Exclusive (open) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete with
    a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can also
    be incomplete, with just a timestamp.

    Attributes:
        stream_id (TEncodable): The stream ID.
    """

    EXCLUSIVE_BOUND_VALKEY_API = "("

    @staticmethod
    def from_timestamp(timestamp: int) -> ExclusiveIdBound:
        """
        Creates an incomplete stream ID boundary without the sequence number for a range search.

        Args:
            timestamp (int): The stream ID timestamp.
        """
        return ExclusiveIdBound(str(timestamp))

    def __init__(self, stream_id: TEncodable):
        """
        Creates a stream ID boundary for a range search.
        """
        self.stream_id: TEncodable
        if isinstance(stream_id, str):
            self.stream_id = f"{self.EXCLUSIVE_BOUND_VALKEY_API}{stream_id}"
        else:
            self.stream_id = self.EXCLUSIVE_BOUND_VALKEY_API.encode() + bytes(stream_id)

    def to_arg(self) -> TEncodable:
        return self.stream_id

from_timestamp(timestamp) staticmethod

Creates an incomplete stream ID boundary without the sequence number for a range search.

Parameters:

Name Type Description Default
timestamp int

The stream ID timestamp.

required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
228
229
230
231
232
233
234
235
236
@staticmethod
def from_timestamp(timestamp: int) -> ExclusiveIdBound:
    """
    Creates an incomplete stream ID boundary without the sequence number for a range search.

    Args:
        timestamp (int): The stream ID timestamp.
    """
    return ExclusiveIdBound(str(timestamp))

IdBound

Bases: StreamRangeBound

Inclusive (closed) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete with a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can also be incomplete, with just a timestamp.

Attributes:

Name Type Description
stream_id str

The stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
class IdBound(StreamRangeBound):
    """
    Inclusive (closed) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete
    with a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can
    also be incomplete, with just a timestamp.

    Attributes:
        stream_id (str): The stream ID.
    """

    @staticmethod
    def from_timestamp(timestamp: int) -> IdBound:
        """
        Creates an incomplete stream ID boundary without the sequence number for a range search.

        Args:
            timestamp (int): The stream ID timestamp.
        """
        return IdBound(str(timestamp))

    def __init__(self, stream_id: TEncodable):
        """
        Creates a stream ID boundary for a range search.
        """
        self.stream_id = stream_id

    def to_arg(self) -> TEncodable:
        return self.stream_id

from_timestamp(timestamp) staticmethod

Creates an incomplete stream ID boundary without the sequence number for a range search.

Parameters:

Name Type Description Default
timestamp int

The stream ID timestamp.

required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
196
197
198
199
200
201
202
203
204
@staticmethod
def from_timestamp(timestamp: int) -> IdBound:
    """
    Creates an incomplete stream ID boundary without the sequence number for a range search.

    Args:
        timestamp (int): The stream ID timestamp.
    """
    return IdBound(str(timestamp))

MaxId

Bases: StreamRangeBound

Stream ID boundary used to specify the maximum stream entry ID. Can be used in the XRANGE or XREVRANGE commands to get the last stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
174
175
176
177
178
179
180
181
182
183
class MaxId(StreamRangeBound):
    """
    Stream ID boundary used to specify the maximum stream entry ID. Can be used in the `XRANGE` or `XREVRANGE` commands
    to get the last stream ID.
    """

    MAX_RANGE_VALKEY_API = "+"

    def to_arg(self) -> str:
        return self.MAX_RANGE_VALKEY_API

MinId

Bases: StreamRangeBound

Stream ID boundary used to specify the minimum stream entry ID. Can be used in the XRANGE or XREVRANGE commands to get the first stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
162
163
164
165
166
167
168
169
170
171
class MinId(StreamRangeBound):
    """
    Stream ID boundary used to specify the minimum stream entry ID. Can be used in the `XRANGE` or `XREVRANGE` commands
    to get the first stream ID.
    """

    MIN_RANGE_VALKEY_API = "-"

    def to_arg(self) -> str:
        return self.MIN_RANGE_VALKEY_API

StreamAddOptions

Options for adding entries to a stream.

Attributes:

Name Type Description
id Optional[TEncodable]

ID for the new entry. If set, the new entry will be added with this ID. If not specified, '*' is used.

make_stream bool

If set to False, a new stream won't be created if no stream matches the given key.

trim Optional[StreamTrimOptions]

If set, the add operation will also trim the older entries in the stream. See StreamTrimOptions.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class StreamAddOptions:
    """
    Options for adding entries to a stream.

    Attributes:
        id (Optional[TEncodable]): ID for the new entry. If set, the new entry will be added with this ID. If not
            specified, '*' is used.
        make_stream (bool): If set to False, a new stream won't be created if no stream matches the given key.
        trim (Optional[StreamTrimOptions]): If set, the add operation will also trim the older entries in the stream.
            See `StreamTrimOptions`.
    """

    def __init__(
        self,
        id: Optional[TEncodable] = None,
        make_stream: bool = True,
        trim: Optional[StreamTrimOptions] = None,
    ):
        """
        Initialize stream add options.
        """
        self.id = id
        self.make_stream = make_stream
        self.trim = trim

    def to_args(self) -> List[TEncodable]:
        """
        Convert options to arguments for the command.

        Returns:
            List[str]: List of arguments for the command.
        """
        option_args: List[TEncodable] = []
        if not self.make_stream:
            option_args.append("NOMKSTREAM")
        if self.trim:
            option_args.extend(self.trim.to_args())
        option_args.append(self.id if self.id else "*")

        return option_args

to_args()

Convert options to arguments for the command.

Returns:

Type Description
List[TEncodable]

List[str]: List of arguments for the command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def to_args(self) -> List[TEncodable]:
    """
    Convert options to arguments for the command.

    Returns:
        List[str]: List of arguments for the command.
    """
    option_args: List[TEncodable] = []
    if not self.make_stream:
        option_args.append("NOMKSTREAM")
    if self.trim:
        option_args.extend(self.trim.to_args())
    option_args.append(self.id if self.id else "*")

    return option_args

StreamClaimOptions

Options for XCLAIM.

Attributes:

Name Type Description
idle Optional[int]

Set the idle time (last time it was delivered) of the message in milliseconds. If idle is not specified, an idle of 0 is assumed, that is, the time count is reset because the message now has a new owner trying to process it.

idle_unix_time Optional[int]

This is the same as idle but instead of a relative amount of milliseconds, it sets the idle time to a specific Unix time (in milliseconds). This is useful in order to rewrite the AOF file generating XCLAIM commands.

retry_count Optional[int]

Set the retry counter to the specified value. This counter is incremented every time a message is delivered again. Normally XCLAIM does not alter this counter, which is just served to clients when the XPENDING command is called: this way clients can detect anomalies, like messages that are never processed for some reason after a big number of delivery attempts.

is_force Optional[bool]

Creates the pending message entry in the PEL even if certain specified IDs are not already in the PEL assigned to a different client. However, the message must exist in the stream, otherwise the IDs of non-existing messages are ignored.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
class StreamClaimOptions:
    """
    Options for `XCLAIM`.

    Attributes:
        idle (Optional[int]): Set the idle time (last time it was delivered) of the message in milliseconds. If idle
            is not specified, an idle of `0` is assumed, that is, the time count is reset because the message now has a
            new owner trying to process it.
        idle_unix_time (Optional[int]): This is the same as idle but instead of a relative amount of milliseconds,
            it sets the idle time to a specific Unix time (in milliseconds). This is useful in order to rewrite the AOF
            file generating `XCLAIM` commands.
        retry_count (Optional[int]): Set the retry counter to the specified value. This counter is incremented every
            time a message is delivered again. Normally `XCLAIM` does not alter this counter, which is just served to
            clients when the `XPENDING` command is called: this way clients can detect anomalies, like messages that
            are never processed for some reason after a big number of delivery attempts.
        is_force (Optional[bool]): Creates the pending message entry in the PEL even if certain specified IDs are not
            already in the PEL assigned to a different client. However, the message must exist in the stream, otherwise
            the IDs of non-existing messages are ignored.
    """

    IDLE_VALKEY_API = "IDLE"
    TIME_VALKEY_API = "TIME"
    RETRY_COUNT_VALKEY_API = "RETRYCOUNT"
    FORCE_VALKEY_API = "FORCE"
    JUST_ID_VALKEY_API = "JUSTID"

    def __init__(
        self,
        idle: Optional[int] = None,
        idle_unix_time: Optional[int] = None,
        retry_count: Optional[int] = None,
        is_force: Optional[bool] = False,
    ):
        self.idle = idle
        self.idle_unix_time = idle_unix_time
        self.retry_count = retry_count
        self.is_force = is_force

    def to_args(self) -> List[TEncodable]:
        """
        Converts options for `XCLAIM` into a List.

        Returns:
            List[str]: The options as a list of arguments for the `XCLAIM` command.
        """
        args: List[TEncodable] = []
        if self.idle is not None:
            args.append(self.IDLE_VALKEY_API)
            args.append(str(self.idle))

        if self.idle_unix_time is not None:
            args.append(self.TIME_VALKEY_API)
            args.append(str(self.idle_unix_time))

        if self.retry_count is not None:
            args.append(self.RETRY_COUNT_VALKEY_API)
            args.append(str(self.retry_count))

        if self.is_force:
            args.append(self.FORCE_VALKEY_API)

        return args

to_args()

Converts options for XCLAIM into a List.

Returns:

Type Description
List[TEncodable]

List[str]: The options as a list of arguments for the XCLAIM command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
def to_args(self) -> List[TEncodable]:
    """
    Converts options for `XCLAIM` into a List.

    Returns:
        List[str]: The options as a list of arguments for the `XCLAIM` command.
    """
    args: List[TEncodable] = []
    if self.idle is not None:
        args.append(self.IDLE_VALKEY_API)
        args.append(str(self.idle))

    if self.idle_unix_time is not None:
        args.append(self.TIME_VALKEY_API)
        args.append(str(self.idle_unix_time))

    if self.retry_count is not None:
        args.append(self.RETRY_COUNT_VALKEY_API)
        args.append(str(self.retry_count))

    if self.is_force:
        args.append(self.FORCE_VALKEY_API)

    return args

StreamGroupOptions

Options for creating stream consumer groups. Can be used as an optional argument to XGROUP CREATE.

Attributes:

Name Type Description
make_stream bool

If set to True and the stream doesn't exist, this creates a new stream with a length of 0.

entries_read

(Optional[int]): A value representing the number of stream entries already read by the group. This option can only be specified if you are using Valkey version 7.0.0 or above.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class StreamGroupOptions:
    """
    Options for creating stream consumer groups. Can be used as an optional argument to `XGROUP CREATE`.

    Attributes:
        make_stream (bool): If set to True and the stream doesn't exist, this creates a new stream with a
            length of 0.
        entries_read: (Optional[int]): A value representing the number of stream entries already read by the
            group. This option can only be specified if you are using Valkey version 7.0.0 or above.
    """

    MAKE_STREAM_VALKEY_API = "MKSTREAM"
    ENTRIES_READ_VALKEY_API = "ENTRIESREAD"

    def __init__(self, make_stream: bool = False, entries_read: Optional[int] = None):
        self.make_stream = make_stream
        self.entries_read = entries_read

    def to_args(self) -> List[TEncodable]:
        """
        Returns the options as a list of string arguments to be used in the `XGROUP CREATE` command.

        Returns:
            List[TEncodable]: The options as a list of arguments for the `XGROUP CREATE` command.
        """
        args: List[TEncodable] = []
        if self.make_stream is True:
            args.append(self.MAKE_STREAM_VALKEY_API)

        if self.entries_read is not None:
            args.extend([self.ENTRIES_READ_VALKEY_API, str(self.entries_read)])

        return args

to_args()

Returns the options as a list of string arguments to be used in the XGROUP CREATE command.

Returns:

Type Description
List[TEncodable]

List[TEncodable]: The options as a list of arguments for the XGROUP CREATE command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def to_args(self) -> List[TEncodable]:
    """
    Returns the options as a list of string arguments to be used in the `XGROUP CREATE` command.

    Returns:
        List[TEncodable]: The options as a list of arguments for the `XGROUP CREATE` command.
    """
    args: List[TEncodable] = []
    if self.make_stream is True:
        args.append(self.MAKE_STREAM_VALKEY_API)

    if self.entries_read is not None:
        args.extend([self.ENTRIES_READ_VALKEY_API, str(self.entries_read)])

    return args

StreamPendingOptions

Options for XPENDING that can be used to filter returned items by minimum idle time and consumer name.

Attributes:

Name Type Description
min_idle_time_ms Optional[int]

Filters pending entries by their minimum idle time in milliseconds. This option can only be specified if you are using Valkey version 6.2.0 or above.

consumer_name Optional[TEncodable]

Filters pending entries by consumer name.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
class StreamPendingOptions:
    """
    Options for `XPENDING` that can be used to filter returned items by minimum idle time and consumer name.

    Attributes:
        min_idle_time_ms (Optional[int]): Filters pending entries by their minimum idle time in milliseconds. This
            option can only be specified if you are using Valkey version 6.2.0 or above.
        consumer_name (Optional[TEncodable]): Filters pending entries by consumer name.
    """

    IDLE_TIME_VALKEY_API = "IDLE"

    def __init__(
        self,
        min_idle_time_ms: Optional[int] = None,
        consumer_name: Optional[TEncodable] = None,
    ):
        self.min_idle_time = min_idle_time_ms
        self.consumer_name = consumer_name

StreamRangeBound

Bases: ABC

Abstract Base Class used in the XPENDING, XRANGE, and XREVRANGE commands to specify the starting and ending range bound for the stream search by stream entry ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
148
149
150
151
152
153
154
155
156
157
158
159
class StreamRangeBound(ABC):
    """
    Abstract Base Class used in the `XPENDING`, `XRANGE`, and `XREVRANGE` commands to specify the starting and ending
    range bound for the stream search by stream entry ID.
    """

    @abstractmethod
    def to_arg(self) -> TEncodable:
        """
        Returns the stream range bound as a string argument to be used in the `XRANGE` or `XREVRANGE` commands.
        """
        pass

to_arg() abstractmethod

Returns the stream range bound as a string argument to be used in the XRANGE or XREVRANGE commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
154
155
156
157
158
159
@abstractmethod
def to_arg(self) -> TEncodable:
    """
    Returns the stream range bound as a string argument to be used in the `XRANGE` or `XREVRANGE` commands.
    """
    pass

StreamReadGroupOptions

Bases: StreamReadOptions

Options for reading entries from streams using a consumer group. Can be used as an optional argument to XREADGROUP.

Attributes:

Name Type Description
no_ack bool

If set, messages are not added to the Pending Entries List (PEL). This is equivalent to acknowledging the message when it is read. Equivalent to NOACK in the Valkey API.

block_ms Optional[int]

If provided, the request will be blocked for the set amount of milliseconds or until the server has the required number of entries. Equivalent to BLOCK in the Valkey API.

count Optional[int]

The maximum number of elements requested. Equivalent to COUNT in the Valkey API.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
class StreamReadGroupOptions(StreamReadOptions):
    """
    Options for reading entries from streams using a consumer group. Can be used as an optional argument to
    `XREADGROUP`.

    Attributes:
        no_ack (bool): If set, messages are not added to the Pending Entries List (PEL). This is equivalent to
            acknowledging the message when it is read. Equivalent to `NOACK` in the Valkey API.
        block_ms (Optional[int]): If provided, the request will be blocked for the set amount of milliseconds or
            until the server has the required number of entries. Equivalent to `BLOCK` in the Valkey API.
        count (Optional[int]): The maximum number of elements requested. Equivalent to `COUNT` in the Valkey API.
    """

    READ_NOACK_VALKEY_API = "NOACK"

    def __init__(
        self, no_ack=False, block_ms: Optional[int] = None, count: Optional[int] = None
    ):
        super().__init__(block_ms=block_ms, count=count)
        self.no_ack = no_ack

    def to_args(self) -> List[TEncodable]:
        """
        Returns the options as a list of string arguments to be used in the `XREADGROUP` command.

        Returns:
            List[TEncodable]: The options as a list of arguments for the `XREADGROUP` command.
        """
        args: List[TEncodable] = super().to_args()
        if self.no_ack:
            args.append(self.READ_NOACK_VALKEY_API)

        return args

to_args()

Returns the options as a list of string arguments to be used in the XREADGROUP command.

Returns:

Type Description
List[TEncodable]

List[TEncodable]: The options as a list of arguments for the XREADGROUP command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
342
343
344
345
346
347
348
349
350
351
352
353
def to_args(self) -> List[TEncodable]:
    """
    Returns the options as a list of string arguments to be used in the `XREADGROUP` command.

    Returns:
        List[TEncodable]: The options as a list of arguments for the `XREADGROUP` command.
    """
    args: List[TEncodable] = super().to_args()
    if self.no_ack:
        args.append(self.READ_NOACK_VALKEY_API)

    return args

StreamReadOptions

Options for reading entries from streams. Can be used as an optional argument to XREAD.

Attributes:

Name Type Description
block_ms Optional[int]

If provided, the request will be blocked for the set amount of milliseconds or until the server has the required number of entries. Equivalent to BLOCK in the Valkey API.

count Optional[int]

The maximum number of elements requested. Equivalent to COUNT in the Valkey API.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
class StreamReadOptions:
    """
    Options for reading entries from streams. Can be used as an optional argument to `XREAD`.

    Attributes:
        block_ms (Optional[int]): If provided, the request will be blocked for the set amount of milliseconds or
            until the server has the required number of entries. Equivalent to `BLOCK` in the Valkey API.
        count (Optional[int]): The maximum number of elements requested. Equivalent to `COUNT` in the Valkey API.
    """

    READ_COUNT_VALKEY_API = "COUNT"
    READ_BLOCK_VALKEY_API = "BLOCK"

    def __init__(self, block_ms: Optional[int] = None, count: Optional[int] = None):
        self.block_ms = block_ms
        self.count = count

    def to_args(self) -> List[TEncodable]:
        """
        Returns the options as a list of string arguments to be used in the `XREAD` command.

        Returns:
            List[TEncodable]: The options as a list of arguments for the `XREAD` command.
        """
        args: List[TEncodable] = []
        if self.block_ms is not None:
            args.extend([self.READ_BLOCK_VALKEY_API, str(self.block_ms)])

        if self.count is not None:
            args.extend([self.READ_COUNT_VALKEY_API, str(self.count)])

        return args

to_args()

Returns the options as a list of string arguments to be used in the XREAD command.

Returns:

Type Description
List[TEncodable]

List[TEncodable]: The options as a list of arguments for the XREAD command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def to_args(self) -> List[TEncodable]:
    """
    Returns the options as a list of string arguments to be used in the `XREAD` command.

    Returns:
        List[TEncodable]: The options as a list of arguments for the `XREAD` command.
    """
    args: List[TEncodable] = []
    if self.block_ms is not None:
        args.extend([self.READ_BLOCK_VALKEY_API, str(self.block_ms)])

    if self.count is not None:
        args.extend([self.READ_COUNT_VALKEY_API, str(self.count)])

    return args

StreamTrimOptions

Bases: ABC

Abstract base class for stream trim options.

Attributes:

Name Type Description
exact bool

If true, the stream will be trimmed exactly. Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.

threshold Union[TEncodable, int]

Threshold for trimming.

method str

Method for trimming (e.g., MINID, MAXLEN).

limit Optional[int]

Max number of entries to be trimmed. Defaults to None. Note: If exact is set to True, limit cannot be specified.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class StreamTrimOptions(ABC):
    """
    Abstract base class for stream trim options.

    Attributes:
        exact (bool): If `true`, the stream will be trimmed exactly.
            Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
        threshold (Union[TEncodable, int]): Threshold for trimming.
        method (str): Method for trimming (e.g., MINID, MAXLEN).
        limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
            Note: If `exact` is set to `True`, `limit` cannot be specified.
    """

    @abstractmethod
    def __init__(
        self,
        exact: bool,
        threshold: Union[TEncodable, int],
        method: str,
        limit: Optional[int] = None,
    ):
        """
        Initialize stream trim options.
        """
        if exact and limit:
            raise ValueError(
                "If `exact` is set to `True`, `limit` cannot be specified."
            )
        self.exact = exact
        self.threshold = threshold
        self.method = method
        self.limit = limit

    def to_args(self) -> List[TEncodable]:
        """
        Convert options to arguments for the command.

        Returns:
            List[TEncodable]: List of arguments for the command.
        """
        # MAXLEN thresholds are ints; MINID thresholds are passed through as bytes or str.
        threshold: TEncodable
        if isinstance(self.threshold, int):
            threshold = str(self.threshold)
        elif isinstance(self.threshold, (bytearray, memoryview)):
            threshold = bytes(self.threshold)
        else:
            threshold = self.threshold
        option_args: List[TEncodable] = [
            self.method,
            "=" if self.exact else "~",
            threshold,
        ]
        if self.limit is not None:
            option_args.extend(["LIMIT", str(self.limit)])
        return option_args

to_args()

Convert options to arguments for the command.

Returns:

Type Description
List[TEncodable]

List[TEncodable]: List of arguments for the command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def to_args(self) -> List[TEncodable]:
    """
    Convert options to arguments for the command.

    Returns:
        List[TEncodable]: List of arguments for the command.
    """
    # MAXLEN thresholds are ints; MINID thresholds are passed through as bytes or str.
    threshold: TEncodable
    if isinstance(self.threshold, int):
        threshold = str(self.threshold)
    elif isinstance(self.threshold, (bytearray, memoryview)):
        threshold = bytes(self.threshold)
    else:
        threshold = self.threshold
    option_args: List[TEncodable] = [
        self.method,
        "=" if self.exact else "~",
        threshold,
    ]
    if self.limit is not None:
        option_args.extend(["LIMIT", str(self.limit)])
    return option_args

TrimByMaxLen

Bases: StreamTrimOptions

Stream trim option to trim by maximum length.

Attributes:

Name Type Description
exact bool

If true, the stream will be trimmed exactly. Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.

threshold int

Threshold for trimming by maximum length.

limit Optional[int]

Max number of entries to be trimmed. Defaults to None. Note: If exact is set to True, limit cannot be specified.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class TrimByMaxLen(StreamTrimOptions):
    """
    Stream trim option to trim by maximum length.

    Attributes:
        exact (bool): If `true`, the stream will be trimmed exactly.
            Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
        threshold (int): Threshold for trimming by maximum length.
        limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
            Note: If `exact` is set to `True`, `limit` cannot be specified.
    """

    def __init__(self, exact: bool, threshold: int, limit: Optional[int] = None):
        """
        Initialize trim option by maximum length.
        """
        super().__init__(exact, threshold, "MAXLEN", limit)

TrimByMinId

Bases: StreamTrimOptions

Stream trim option to trim by minimum ID.

Attributes:

Name Type Description
exact bool

If true, the stream will be trimmed exactly. Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.

threshold TEncodable

Threshold for trimming by minimum ID.

limit Optional[int]

Max number of entries to be trimmed. Defaults to None. Note: If exact is set to True, limit cannot be specified.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class TrimByMinId(StreamTrimOptions):
    """
    Stream trim option to trim by minimum ID.

    Attributes:
        exact (bool): If `true`, the stream will be trimmed exactly.
            Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
        threshold (TEncodable): Threshold for trimming by minimum ID.
        limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
            Note: If `exact` is set to `True`, `limit` cannot be specified.
    """

    def __init__(self, exact: bool, threshold: TEncodable, limit: Optional[int] = None):
        """
        Initialize trim option by minimum ID.
        """
        super().__init__(exact, threshold, "MINID", limit)

AddressResolver

Bases: Protocol

A callback protocol for resolving server addresses before connection.

When provided to a client configuration, this callback is invoked for each configured address during connection establishment and during cluster topology refreshes. The callback receives the configured host and port, and should return the actual host and port to use for the connection.

Use cases
  • Custom DNS resolution for service discovery
  • Address translation for proxy setups
  • Dynamic endpoint resolution for cloud environments
Note

The resolver must be thread-safe and should avoid blocking operations, as it may be called from multiple threads during connection and topology refresh. If the resolver raises an exception, the original address will be used as a fallback.

Example::

def my_resolver(host: str, port: int) -> Tuple[str, int]:
    # Custom resolution logic
    resolved_host = my_dns_resolver.resolve(host)
    return (resolved_host, port)

config = GlideClientConfiguration(
    addresses=[NodeAddress("my-service", 6379)],
    address_resolver=my_resolver,
)
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class AddressResolver(Protocol):
    """
    A callback protocol for resolving server addresses before connection.

    When provided to a client configuration, this callback is invoked for each
    configured address during connection establishment and during cluster topology
    refreshes. The callback receives the configured host and port, and should return
    the actual host and port to use for the connection.

    Use cases:
        - Custom DNS resolution for service discovery
        - Address translation for proxy setups
        - Dynamic endpoint resolution for cloud environments

    Note:
        The resolver must be thread-safe and should avoid blocking operations,
        as it may be called from multiple threads during connection and topology refresh.
        If the resolver raises an exception, the original address will be used as a fallback.

    Example::

        def my_resolver(host: str, port: int) -> Tuple[str, int]:
            # Custom resolution logic
            resolved_host = my_dns_resolver.resolve(host)
            return (resolved_host, port)

        config = GlideClientConfiguration(
            addresses=[NodeAddress("my-service", 6379)],
            address_resolver=my_resolver,
        )
    """

    def __call__(self, host: str, port: int) -> Tuple[str, int]:
        """
        Resolve the given host and port to the actual connection address.

        Args:
            host (str): The configured host name or IP address.
            port (int): The configured port number.

        Returns:
            Tuple[str, int]: A tuple of (resolved_host, resolved_port) to use for connection.
        """
        ...

AdvancedGlideClientConfiguration

Bases: AdvancedBaseClientConfiguration

Represents the advanced configuration settings for a Standalone Glide client.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
class AdvancedGlideClientConfiguration(AdvancedBaseClientConfiguration):
    """
    Represents the advanced configuration settings for a Standalone Glide client.
    """

    def __init__(
        self,
        connection_timeout: Optional[int] = None,
        tls_config: Optional[TlsAdvancedConfiguration] = None,
        tcp_nodelay: Optional[bool] = None,
        pubsub_reconciliation_interval: Optional[int] = None,
    ):

        super().__init__(
            connection_timeout, tls_config, tcp_nodelay, pubsub_reconciliation_interval
        )

AdvancedGlideClusterClientConfiguration

Bases: AdvancedBaseClientConfiguration

Represents the advanced configuration settings for a Glide Cluster client.

Attributes:

Name Type Description
connection_timeout Optional[int]

The duration in milliseconds to wait for a TCP/TLS connection to complete. This applies both during initial client creation and any reconnection that may occur during request processing. Note: A high connection timeout may lead to prolonged blocking of the entire command pipeline. If not explicitly set, a default value of 2000 milliseconds will be used.

tls_config Optional[TlsAdvancedConfiguration]

The advanced TLS configuration settings. This allows for more granular control of TLS behavior, such as enabling an insecure mode that bypasses certificate validation.

refresh_topology_from_initial_nodes bool

Enables refreshing the cluster topology using only the initial nodes. When this option is enabled, all topology updates (both the periodic checks and on-demand refreshes triggered by topology changes) will query only the initial nodes provided when creating the client, rather than using the internal cluster view.

pubsub_reconciliation_interval Optional[int]

The interval in milliseconds between PubSub subscription reconciliation attempts. The reconciliation process ensures that the client's desired subscriptions match the actual subscriptions on the server.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
class AdvancedGlideClusterClientConfiguration(AdvancedBaseClientConfiguration):
    """
    Represents the advanced configuration settings for a Glide Cluster client.

    Attributes:
        connection_timeout (Optional[int]): The duration in milliseconds to wait for a TCP/TLS connection to complete.
            This applies both during initial client creation and any reconnection that may occur during request processing.
            **Note**: A high connection timeout may lead to prolonged blocking of the entire command pipeline.
            If not explicitly set, a default value of 2000 milliseconds will be used.
        tls_config (Optional[TlsAdvancedConfiguration]): The advanced TLS configuration settings.
            This allows for more granular control of TLS behavior, such as enabling an insecure mode
            that bypasses certificate validation.
        refresh_topology_from_initial_nodes (bool): Enables refreshing the cluster topology using only the initial nodes.
            When this option is enabled, all topology updates (both the periodic checks and on-demand refreshes
            triggered by topology changes) will query only the initial nodes provided when creating the client, rather than using the internal cluster view.
        pubsub_reconciliation_interval (Optional[int]): The interval in milliseconds between PubSub subscription
            reconciliation attempts. The reconciliation process ensures that the client's desired subscriptions
            match the actual subscriptions on the server.
    """

    def __init__(
        self,
        connection_timeout: Optional[int] = None,
        tls_config: Optional[TlsAdvancedConfiguration] = None,
        refresh_topology_from_initial_nodes: bool = False,
        tcp_nodelay: Optional[bool] = None,
        pubsub_reconciliation_interval: Optional[int] = None,
    ):
        super().__init__(
            connection_timeout, tls_config, tcp_nodelay, pubsub_reconciliation_interval
        )
        self.refresh_topology_from_initial_nodes = refresh_topology_from_initial_nodes

    def _create_a_protobuf_conn_request(
        self, request: ConnectionRequest
    ) -> ConnectionRequest:
        super()._create_a_protobuf_conn_request(request)

        request.refresh_topology_from_initial_nodes = (
            self.refresh_topology_from_initial_nodes
        )
        return request

AwsCredentials

AWS credentials used to sign IAM authentication tokens.

access_key_id and secret_access_key must be nonblank strings. expires_at_epoch_millis, when supplied, must be an integer that fits in a signed 64-bit value. Values less than or equal to 0 mean no expiry.

Attributes:

Name Type Description
access_key_id str

The AWS access key ID.

secret_access_key str

The AWS secret access key.

session_token Optional[str]

An optional AWS session token.

expires_at_epoch_millis Optional[int]

Optional expiration time as Unix epoch milliseconds. A nonpositive value is treated as no expiration by the core.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
class AwsCredentials:
    """AWS credentials used to sign IAM authentication tokens.

    ``access_key_id`` and ``secret_access_key`` must be nonblank strings.
    ``expires_at_epoch_millis``, when supplied, must be an integer that fits in
    a signed 64-bit value. Values less than or equal to 0 mean no expiry.

    Attributes:
        access_key_id (str): The AWS access key ID.
        secret_access_key (str): The AWS secret access key.
        session_token (Optional[str]): An optional AWS session token.
        expires_at_epoch_millis (Optional[int]): Optional expiration time as Unix
            epoch milliseconds. A nonpositive value is treated as no expiration
            by the core.
    """

    def __init__(
        self,
        access_key_id: str,
        secret_access_key: str,
        session_token: Optional[str] = None,
        expires_at_epoch_millis: Optional[int] = None,
    ):
        if not isinstance(access_key_id, str) or not access_key_id.strip():
            raise ValueError("access_key_id must be a nonblank string")
        if not isinstance(secret_access_key, str) or not secret_access_key.strip():
            raise ValueError("secret_access_key must be a nonblank string")
        if session_token is not None and not isinstance(session_token, str):
            raise ValueError("session_token must be a string or None")
        if expires_at_epoch_millis is not None and (
            not isinstance(expires_at_epoch_millis, int)
            or isinstance(expires_at_epoch_millis, bool)
            or expires_at_epoch_millis < -(2**63)
            or expires_at_epoch_millis > 2**63 - 1
        ):
            raise ValueError("expires_at_epoch_millis must be a signed 64-bit integer")

        self.access_key_id = access_key_id
        self.secret_access_key = secret_access_key
        self.session_token = session_token
        self.expires_at_epoch_millis = expires_at_epoch_millis

BackoffStrategy

Represents the strategy used to determine how and when to reconnect, in case of connection failures. The time between attempts grows exponentially, to the formula rand(0 .. factor * (exponentBase ^ N)), where N is the number of failed attempts, and rand(...) applies a jitter of up to jitter_percent% to introduce randomness and reduce retry storms. Once the maximum value is reached, that will remain the time between retry attempts until a reconnect attempt is successful. The client will attempt to reconnect indefinitely.

Attributes:

Name Type Description
num_of_retries int

Number of retry attempts that the client should perform when disconnected from the server, where the time between retries increases. Once the retries have reached the maximum value, the time between retries will remain constant until a reconnect attempt is succesful.

factor int

The multiplier that will be applied to the waiting time between each retry. This value is specified in milliseconds. A value of 0 means the default (100) is used.

exponent_base int

The exponent base configured for the strategy. A value of 0 means the default (2) is used.

jitter_percent Optional[int]

The Jitter percent on the calculated duration, between 0 and 100. A value above 100 is rejected when the client is created. If not set, a default value will be used.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
class BackoffStrategy:
    """
    Represents the strategy used to determine how and when to reconnect, in case of connection failures.
    The time between attempts grows exponentially, to the formula rand(0 .. factor * (exponentBase ^ N)), where N
    is the number of failed attempts, and rand(...) applies a jitter of up to jitter_percent% to introduce randomness and reduce retry storms.
    Once the maximum value is reached, that will remain the time between retry attempts until a reconnect attempt is
    successful.
    The client will attempt to reconnect indefinitely.

    Attributes:
        num_of_retries (int): Number of retry attempts that the client should perform when disconnected from the server,
            where the time between retries increases. Once the retries have reached the maximum value, the time between
            retries will remain constant until a reconnect attempt is succesful.
        factor (int): The multiplier that will be applied to the waiting time between each retry.
            This value is specified in milliseconds. A value of 0 means the default (100) is used.
        exponent_base (int): The exponent base configured for the strategy. A value of 0 means the
            default (2) is used.
        jitter_percent (Optional[int]): The Jitter percent on the calculated duration, between 0 and 100.
            A value above 100 is rejected when the client is created. If not set, a default value will be used.
    """

    def __init__(
        self,
        num_of_retries: int,
        factor: int,
        exponent_base: int,
        jitter_percent: Optional[int] = None,
    ):
        self.num_of_retries = num_of_retries
        self.factor = factor
        self.exponent_base = exponent_base
        self.jitter_percent = jitter_percent

ClientCircuitBreakerConfiguration

Configuration for the client-wide circuit breaker.

The circuit breaker detects when the GLIDE core is unhealthy (sustained error rate) and rejects requests at the FFI boundary before threads park. Disabled by default.

Attributes:

Name Type Description
window_size_ms int

Sliding window duration in milliseconds for error rate calculation. Default: 10000.

failure_rate_threshold float

Error rate (0.0-1.0) within the window to trip. Default: 0.5.

min_errors int

Minimum errors within window before rate is evaluated. Default: 50.

open_timeout_ms int

Time in milliseconds in Open state before allowing a probe. Default: 5000.

count_timeouts bool

Whether timeouts count toward tripping. Default: False.

consecutive_successes int

Successful probes needed before closing. Default: 3.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
class ClientCircuitBreakerConfiguration:
    """
    Configuration for the client-wide circuit breaker.

    The circuit breaker detects when the GLIDE core is unhealthy (sustained error rate)
    and rejects requests at the FFI boundary before threads park. Disabled by default.

    Attributes:
        window_size_ms (int): Sliding window duration in milliseconds for error rate calculation. Default: 10000.
        failure_rate_threshold (float): Error rate (0.0-1.0) within the window to trip. Default: 0.5.
        min_errors (int): Minimum errors within window before rate is evaluated. Default: 50.
        open_timeout_ms (int): Time in milliseconds in Open state before allowing a probe. Default: 5000.
        count_timeouts (bool): Whether timeouts count toward tripping. Default: False.
        consecutive_successes (int): Successful probes needed before closing. Default: 3.
    """

    def __init__(
        self,
        window_size_ms: int = 10000,
        failure_rate_threshold: float = 0.5,
        min_errors: int = 50,
        open_timeout_ms: int = 5000,
        count_timeouts: bool = False,
        consecutive_successes: int = 3,
    ):
        if window_size_ms <= 0:
            raise ValueError("window_size_ms must be positive")
        if not (0.0 < failure_rate_threshold <= 1.0):
            raise ValueError(
                "failure_rate_threshold must be between 0.0 (exclusive) and 1.0 (inclusive)"
            )
        if min_errors <= 0:
            raise ValueError("min_errors must be positive")
        if open_timeout_ms <= 0:
            raise ValueError("open_timeout_ms must be positive")
        if consecutive_successes <= 0:
            raise ValueError("consecutive_successes must be positive")
        self.window_size_ms = window_size_ms
        self.failure_rate_threshold = failure_rate_threshold
        self.min_errors = min_errors
        self.open_timeout_ms = open_timeout_ms
        self.count_timeouts = count_timeouts
        self.consecutive_successes = consecutive_successes

CompressionBackend

Bases: Enum

Represents the compression backend to use for automatic compression.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
184
185
186
187
188
189
190
191
192
193
194
195
196
class CompressionBackend(Enum):
    """
    Represents the compression backend to use for automatic compression.
    """

    ZSTD = ProtobufCompressionBackend.ZSTD
    """
    Use zstd compression backend.
    """
    LZ4 = ProtobufCompressionBackend.LZ4
    """
    Use lz4 compression backend.
    """

ZSTD = ProtobufCompressionBackend.ZSTD class-attribute instance-attribute

Use zstd compression backend.

LZ4 = ProtobufCompressionBackend.LZ4 class-attribute instance-attribute

Use lz4 compression backend.

CompressionConfiguration dataclass

Represents the compression configuration for automatic compression of values.

WARNING: This feature is experimental and not recommended for production use.

Compression is NOT compatible with commands that manipulate or compare string data on the server side: - APPEND, GETRANGE, SETRANGE, STRLEN, LCS, SUBSTR - DELIFEQ and SET with IFEQ or IFNE - INCR, INCRBY, INCRBYFLOAT, DECR, DECRBY - GETBIT, SETBIT, BITCOUNT, BITPOS, BITFIELD, BITFIELD_RO, BITOP

Using these commands with compressed values will result in incorrect behavior or errors.

Attributes:

Name Type Description
enabled bool

Whether compression is enabled. Defaults to False.

backend CompressionBackend

The compression backend to use. Defaults to CompressionBackend.ZSTD.

compression_level Optional[int]

The compression level to use. If not set, the backend's default level will be used. Valid ranges are backend-specific and validated by the Rust core. ZSTD default is 3 LZ4 default is 0

min_compression_size int

The minimum size in bytes for values to be compressed. Values smaller than this will not be compressed. Defaults to 64 bytes.

max_decompressed_size Optional[int]

Maximum allowed size in bytes for decompressed data. This limit prevents decompression bombs (maliciously crafted compressed data that expands to huge sizes). If not set, defaults to 512MB (matching Valkey's proto-max-bulk-len).

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
@dataclass
class CompressionConfiguration:
    """
    Represents the compression configuration for automatic compression of values.

    WARNING: This feature is experimental and not recommended for production use.

    Compression is NOT compatible with commands that manipulate or compare string data on the server side:
    - APPEND, GETRANGE, SETRANGE, STRLEN, LCS, SUBSTR
    - DELIFEQ and SET with IFEQ or IFNE
    - INCR, INCRBY, INCRBYFLOAT, DECR, DECRBY
    - GETBIT, SETBIT, BITCOUNT, BITPOS, BITFIELD, BITFIELD_RO, BITOP

    Using these commands with compressed values will result in incorrect behavior or errors.

    Attributes:
        enabled (bool): Whether compression is enabled. Defaults to False.
        backend (CompressionBackend): The compression backend to use. Defaults to CompressionBackend.ZSTD.
        compression_level (Optional[int]): The compression level to use. If not set, the backend's default level will be used.
            Valid ranges are backend-specific and validated by the Rust core.
            ZSTD default is 3
            LZ4 default is 0
        min_compression_size (int): The minimum size in bytes for values to be compressed. Values smaller than this will not be compressed. Defaults to 64 bytes.
        max_decompressed_size (Optional[int]): Maximum allowed size in bytes for decompressed data.
            This limit prevents decompression bombs (maliciously crafted compressed data that expands to huge sizes).
            If not set, defaults to 512MB (matching Valkey's proto-max-bulk-len).
    """

    enabled: bool = False
    backend: CompressionBackend = CompressionBackend.ZSTD
    compression_level: Optional[int] = None
    min_compression_size: int = 64
    max_decompressed_size: Optional[int] = None  # Use Rust default (512MB)

    def __post_init__(self) -> None:
        """Validate compression configuration parameters."""
        self._validate_configuration()

    def _validate_configuration(self) -> None:
        """
        Validates the compression configuration parameters.

        Raises:
            ConfigurationError: If any configuration parameter is invalid.
        """
        min_size = _get_min_compressed_size_cached()
        if self.min_compression_size < min_size:
            raise ConfigurationError(
                f"min_compression_size should be at least {min_size} bytes"
            )

        if self.max_decompressed_size is not None and self.max_decompressed_size <= 0:
            raise ConfigurationError("max_decompressed_size must be positive if set")

        # Note: compression_level validation is performed by the Rust core,
        # which uses the actual compression library's valid ranges.
        # This ensures the validation stays in sync with library updates.

    def _to_protobuf(self) -> ProtobufCompressionConfig:
        """
        Converts the compression configuration to protobuf format.

        Returns:
            ProtobufCompressionConfig: The protobuf compression configuration.

        Raises:
            ConfigurationError: If any configuration parameter is invalid.
        """
        # Validate configuration before converting to protobuf
        # This protects against modifications made after __post_init__
        self._validate_configuration()

        config = ProtobufCompressionConfig()
        config.enabled = self.enabled
        config.backend = self.backend.value
        config.min_compression_size = self.min_compression_size

        if self.compression_level is not None:
            config.compression_level = self.compression_level

        # Handle max_decompressed_size:
        # - None = don't set field, let Rust use its default (512MB)
        # - int > 0 = use that value
        if self.max_decompressed_size is not None:
            config.max_decompressed_size = self.max_decompressed_size

        return config

GlideClientConfiguration

Bases: BaseClientConfiguration

Represents the configuration settings for a Standalone Glide client.

Attributes:

Name Type Description
addresses List[NodeAddress]

DNS Addresses and ports of known nodes in the cluster. Only nodes whose addresses were provided will be used by the client. For example::

[
    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
    NodeAddress("sample-address-0002.use1.cache.amazonaws.com", 6379)
]
use_tls bool

True if communication with the cluster should use Transport Level Security. Please use AdvancedGlideClusterClientConfiguration.

credentials ServerCredentials

Credentials for authentication process. If none are set, the client will not authenticate itself with the server.

read_from ReadFrom

If not set, PRIMARY will be used.

request_timeout Optional[int]

The duration in milliseconds that the client should wait for a request to complete. This duration encompasses sending the request, awaiting for a response from the server, and any required reconnection or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, a default value of 250 milliseconds will be used.

reconnect_strategy Optional[BackoffStrategy]

Strategy used to determine how and when to reconnect, in case of connection failures. If not set, a default backoff strategy will be used.

database_id Optional[int]

Index of the logical database to connect to.

client_name Optional[str]

Client name to be used for the client. Will be used with CLIENT SETNAME command during connection establishment.

lib_name Optional[str]

Library name to be used for the client. Will be used with CLIENT SETINFO LIB-NAME command during connection establishment. Useful for identifying a wrapping library or framework in CLIENT INFO/CLIENT LIST output. Every character in a non-empty value must be printable ASCII from ! (U+0021) through ~ (U+007E), inclusive, excluding ( and ). An empty value is treated as unset. If not set, a client-specific default is used.

client_info_tag Optional[str]

Optional tag appended to the library name in parentheses (e.g. GlidePy(my-framework:1.2.3)), preserving the underlying GLIDE library identity while attributing a wrapping library or framework in CLIENT INFO/CLIENT LIST output. Applied on top of the default library name or a configured lib_name. Every character in a non-empty value must be printable ASCII from ! (U+0021) through ~ (U+007E), inclusive, excluding ( and ). An empty value is treated as unset.

protocol ProtocolVersion

The version of the RESP protocol to communicate with the server.

pubsub_subscriptions Optional[PubSubSubscriptions]

Pubsub subscriptions to be used for the client. Will be applied via SUBSCRIBE/PSUBSCRIBE commands during connection establishment.

inflight_requests_limit Optional[int]

The maximum number of concurrent requests allowed to be in-flight (sent but not yet completed). This limit is used to control the memory usage and prevent the client from overwhelming the server or getting stuck in case of a queue backlog. If not set, a default value will be used.

client_az Optional[str]

Availability Zone of the client. If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within the specified AZ if exits. If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to nodes (first replicas then primary) within the specified AZ if they exist. If ReadFrom strategy is AZAffinityAllNodes, this setting ensures that readonly commands are spread equally among all nodes (primary and replicas) within the specified AZ if they exist.

advanced_config Optional[AdvancedGlideClientConfiguration]

Advanced configuration settings for the client, see AdvancedGlideClientConfiguration.

compression Optional[CompressionConfiguration]

Configuration for automatic compression of values. When enabled, the client will automatically compress values for set-type commands and decompress values for get-type commands. This can reduce bandwidth usage and storage requirements. If not set, compression is disabled.

read_only bool

When True, enables read-only mode for the standalone client. In read-only mode: - The client skips primary node detection (INFO REPLICATION command) - Write commands are blocked and will return an error - All connected nodes are treated as valid read targets - If no ReadFrom strategy is specified, defaults to PreferReplica This is useful for connecting to replica-only deployments or when you want to prevent accidental write operations. Note: read_only mode is not compatible with AZAffinity, AZAffinityReplicasAndPrimary, or AZAffinityAllNodes read strategies. Defaults to False.

client_side_cache Optional[ClientSideCache]

Configuration for client-side caching. See ClientSideCache for caching behavior details, supported commands, and expiration semantics.

In order for 2 clients to share the same cache, they must be created with the same ClientSideCache instance.

  • Clients with different ClientSideCache instances will have separate caches, even if the configurations are identical.
  • Clients using different DBs cannot share the same cache.
  • Clients using different ACL users cannot share the same cache.
node_discovery_mode NodeDiscoveryMode

Controls how the client discovers node roles and topology in standalone mode. If not set, STANDARD will be used.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
class GlideClientConfiguration(BaseClientConfiguration):
    """
    Represents the configuration settings for a Standalone Glide client.

    Attributes:
        addresses (List[NodeAddress]): DNS Addresses and ports of known nodes in the cluster.
            Only nodes whose addresses were provided will be used by the client.
            For example::

                [
                    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
                    NodeAddress("sample-address-0002.use1.cache.amazonaws.com", 6379)
                ]

        use_tls (bool): True if communication with the cluster should use Transport Level Security.
                Please use `AdvancedGlideClusterClientConfiguration`.
        credentials (ServerCredentials): Credentials for authentication process.
                If none are set, the client will not authenticate itself with the server.
        read_from (ReadFrom): If not set, `PRIMARY` will be used.
        request_timeout (Optional[int]):  The duration in milliseconds that the client should wait for a request to complete.
                This duration encompasses sending the request, awaiting for a response from the server, and any required
                reconnection or retries.
                If the specified timeout is exceeded for a pending request, it will result in a timeout error.
                If not explicitly set, a default value of 250 milliseconds will be used.
        reconnect_strategy (Optional[BackoffStrategy]): Strategy used to determine how and when to reconnect, in case of
            connection failures.
            If not set, a default backoff strategy will be used.
        database_id (Optional[int]): Index of the logical database to connect to.
        client_name (Optional[str]): Client name to be used for the client. Will be used with CLIENT SETNAME command during
            connection establishment.
        lib_name (Optional[str]): Library name to be used for the client. Will be used with CLIENT SETINFO LIB-NAME command
            during connection establishment. Useful for identifying a wrapping library or framework in
            ``CLIENT INFO``/``CLIENT LIST`` output. Every character in a non-empty value must be printable ASCII
            from ``!`` (U+0021) through ``~`` (U+007E), inclusive, excluding ``(`` and ``)``.
            An empty value is treated as unset.
            If not set, a client-specific default is used.
        client_info_tag (Optional[str]): Optional tag appended to the library name in parentheses
            (e.g. ``GlidePy(my-framework:1.2.3)``), preserving the underlying GLIDE library identity while
            attributing a wrapping library or framework in ``CLIENT INFO``/``CLIENT LIST`` output. Applied on top of
            the default library name or a configured ``lib_name``. Every character in a non-empty value must be
            printable ASCII from ``!`` (U+0021) through ``~`` (U+007E), inclusive, excluding ``(`` and ``)``.
            An empty value is treated as unset.
        protocol (ProtocolVersion): The version of the RESP protocol to communicate with the server.
        pubsub_subscriptions (Optional[GlideClientConfiguration.PubSubSubscriptions]): Pubsub subscriptions to be used for the
                client.
                Will be applied via SUBSCRIBE/PSUBSCRIBE commands during connection establishment.
        inflight_requests_limit (Optional[int]): The maximum number of concurrent requests allowed to be in-flight
            (sent but not yet completed).
            This limit is used to control the memory usage and prevent the client from overwhelming the server or getting
            stuck in case of a queue backlog.
            If not set, a default value will be used.
        client_az (Optional[str]): Availability Zone of the client.
            If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within
            the specified AZ if exits.
            If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to
            nodes (first replicas then primary) within the specified AZ if they exist.
            If ReadFrom strategy is AZAffinityAllNodes, this setting ensures that readonly commands are spread equally
            among all nodes (primary and replicas) within the specified AZ if they exist.
        advanced_config (Optional[AdvancedGlideClientConfiguration]): Advanced configuration settings for the client,
            see `AdvancedGlideClientConfiguration`.
        compression (Optional[CompressionConfiguration]): Configuration for automatic compression of values.
            When enabled, the client will automatically compress values for set-type commands and decompress
            values for get-type commands. This can reduce bandwidth usage and storage requirements.
            If not set, compression is disabled.
        read_only (bool): When True, enables read-only mode for the standalone client.
            In read-only mode:
            - The client skips primary node detection (INFO REPLICATION command)
            - Write commands are blocked and will return an error
            - All connected nodes are treated as valid read targets
            - If no ReadFrom strategy is specified, defaults to PreferReplica
            This is useful for connecting to replica-only deployments or when you want to
            prevent accidental write operations.
            Note: read_only mode is not compatible with AZAffinity, AZAffinityReplicasAndPrimary, or
            AZAffinityAllNodes read strategies.
            Defaults to False.
        client_side_cache (Optional[ClientSideCache]): Configuration for client-side caching.
            See `ClientSideCache` for caching behavior details, supported commands, and expiration semantics.

            In order for 2 clients to share the same cache, they must be
            created with the same ``ClientSideCache`` instance.

            - Clients with different ``ClientSideCache`` instances will have separate caches,
              even if the configurations are identical.
            - Clients using different DBs cannot share the same cache.
            - Clients using different ACL users cannot share the same cache.
        node_discovery_mode (NodeDiscoveryMode): Controls how the client discovers node roles
            and topology in standalone mode. If not set, `STANDARD` will be used.
    """

    class PubSubChannelModes(IntEnum):
        """
        Describes pubsub subsciption modes.
        See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
        """

        Exact = 0
        """ Use exact channel names """
        Pattern = 1
        """ Use channel name patterns """

    @dataclass
    class PubSubSubscriptions:
        """Describes pubsub configuration for standalone mode client.

        Attributes:
            channels_and_patterns (Dict[GlideClientConfiguration.PubSubChannelModes, Set[str]]):
                Channels and patterns by modes.
            callback (Optional[Callable[[PubSubMsg, Any], None]]):
                Optional callback to accept the incomming messages.
            context (Any):
                Arbitrary context to pass to the callback.
        """

        channels_and_patterns: Dict[
            GlideClientConfiguration.PubSubChannelModes, Set[str]
        ]
        callback: Optional[Callable[[PubSubMsg, Any], None]]
        context: Any

    @dataclass
    class PubSubState:
        desired_subscriptions: Dict[
            GlideClientConfiguration.PubSubChannelModes, Set[str]
        ]
        actual_subscriptions: Dict[
            GlideClientConfiguration.PubSubChannelModes, Set[str]
        ]

    def __init__(
        self,
        addresses: List[NodeAddress],
        use_tls: bool = False,
        credentials: Optional[ServerCredentials] = None,
        read_from: ReadFrom = ReadFrom.PRIMARY,
        request_timeout: Optional[int] = None,
        reconnect_strategy: Optional[BackoffStrategy] = None,
        database_id: Optional[int] = None,
        client_name: Optional[str] = None,
        protocol: ProtocolVersion = ProtocolVersion.RESP3,
        pubsub_subscriptions: Optional[PubSubSubscriptions] = None,
        inflight_requests_limit: Optional[int] = None,
        client_az: Optional[str] = None,
        advanced_config: Optional[AdvancedGlideClientConfiguration] = None,
        lazy_connect: Optional[bool] = None,
        compression: Optional[CompressionConfiguration] = None,
        read_only: bool = False,
        client_side_cache: Optional[ClientSideCache] = None,
        node_discovery_mode: NodeDiscoveryMode = NodeDiscoveryMode.STANDARD,
        address_resolver: Optional[Callable[[str, int], Tuple[str, int]]] = None,
        client_circuit_breaker: Optional[ClientCircuitBreakerConfiguration] = None,
        lib_name: Optional[str] = None,
        client_info_tag: Optional[str] = None,
        rdma: Optional[RdmaConfiguration] = None,
    ):
        super().__init__(
            addresses=addresses,
            use_tls=use_tls,
            credentials=credentials,
            read_from=read_from,
            request_timeout=request_timeout,
            reconnect_strategy=reconnect_strategy,
            database_id=database_id,
            client_name=client_name,
            lib_name=lib_name,
            client_info_tag=client_info_tag,
            protocol=protocol,
            inflight_requests_limit=inflight_requests_limit,
            client_az=client_az,
            advanced_config=advanced_config,
            lazy_connect=lazy_connect,
            compression=compression,
            rdma=rdma,
            client_side_cache=client_side_cache,
            address_resolver=address_resolver,
            client_circuit_breaker=client_circuit_breaker,
        )
        self.pubsub_subscriptions = pubsub_subscriptions
        self.read_only = read_only
        self.node_discovery_mode = node_discovery_mode

    def _create_a_protobuf_conn_request(
        self, cluster_mode: bool = False
    ) -> ConnectionRequest:
        assert cluster_mode is False
        request = super()._create_a_protobuf_conn_request(cluster_mode)

        # Set read_only mode
        request.read_only = self.read_only

        # Set node discovery mode
        request.node_discovery_mode = self.node_discovery_mode.value

        if self.pubsub_subscriptions:
            if self.protocol == ProtocolVersion.RESP2:
                raise ConfigurationError(
                    "PubSub subscriptions require RESP3 protocol, but RESP2 was configured."
                )
            if (
                self.pubsub_subscriptions.context is not None
                and not self.pubsub_subscriptions.callback
            ):
                raise ConfigurationError(
                    "PubSub subscriptions with a context require a callback function to be configured."
                )
            for (
                channel_type,
                channels_patterns,
            ) in self.pubsub_subscriptions.channels_and_patterns.items():
                entry = request.pubsub_subscriptions.channels_or_patterns_by_type[
                    int(channel_type)
                ]
                for channel_pattern in channels_patterns:
                    entry.channels_or_patterns.append(str.encode(channel_pattern))

        return request

    def _get_pubsub_callback_and_context(
        self,
    ) -> Tuple[Optional[Callable[[PubSubMsg, Any], None]], Any]:
        if self.pubsub_subscriptions:
            return self.pubsub_subscriptions.callback, self.pubsub_subscriptions.context
        return None, None

PubSubChannelModes

Bases: IntEnum

Describes pubsub subsciption modes. See valkey.io for more details

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
class PubSubChannelModes(IntEnum):
    """
    Describes pubsub subsciption modes.
    See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
    """

    Exact = 0
    """ Use exact channel names """
    Pattern = 1
    """ Use channel name patterns """

Exact = 0 class-attribute instance-attribute

Use exact channel names

Pattern = 1 class-attribute instance-attribute

Use channel name patterns

PubSubSubscriptions dataclass

Describes pubsub configuration for standalone mode client.

Attributes:

Name Type Description
channels_and_patterns Dict[PubSubChannelModes, Set[str]]

Channels and patterns by modes.

callback Optional[Callable[[PubSubMsg, Any], None]]

Optional callback to accept the incomming messages.

context Any

Arbitrary context to pass to the callback.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
@dataclass
class PubSubSubscriptions:
    """Describes pubsub configuration for standalone mode client.

    Attributes:
        channels_and_patterns (Dict[GlideClientConfiguration.PubSubChannelModes, Set[str]]):
            Channels and patterns by modes.
        callback (Optional[Callable[[PubSubMsg, Any], None]]):
            Optional callback to accept the incomming messages.
        context (Any):
            Arbitrary context to pass to the callback.
    """

    channels_and_patterns: Dict[
        GlideClientConfiguration.PubSubChannelModes, Set[str]
    ]
    callback: Optional[Callable[[PubSubMsg, Any], None]]
    context: Any

GlideClusterClientConfiguration

Bases: BaseClientConfiguration

Represents the configuration settings for a Cluster Glide client.

Attributes:

Name Type Description
addresses List[NodeAddress]

DNS Addresses and ports of known nodes in the cluster. The list can be partial, as the client will attempt to map out the cluster and find all nodes. Unix domain socket addresses are not supported in cluster mode. For example::

[
    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
]
use_tls bool

True if communication with the cluster should use Transport Level Security. For advanced tls configuration, please use AdvancedGlideClusterClientConfiguration.

credentials ServerCredentials

Credentials for authentication process. If none are set, the client will not authenticate itself with the server.

read_from ReadFrom

If not set, PRIMARY will be used.

request_timeout Optional[int]

The duration in milliseconds that the client should wait for a request to complete. This duration encompasses sending the request, awaiting for a response from the server, and any required reconnection or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, a default value of 250 milliseconds will be used.

reconnect_strategy Optional[BackoffStrategy]

Strategy used to determine how and when to reconnect, in case of connection failures. If not set, a default backoff strategy will be used.

database_id Optional[int]

Index of the logical database to connect to.

client_name Optional[str]

Client name to be used for the client. Will be used with CLIENT SETNAME command during connection establishment.

lib_name Optional[str]

Library name to be used for the client. Will be used with CLIENT SETINFO LIB-NAME command during connection establishment. Useful for identifying a wrapping library or framework in CLIENT INFO/CLIENT LIST output. Every character in a non-empty value must be printable ASCII from ! (U+0021) through ~ (U+007E), inclusive, excluding ( and ). An empty value is treated as unset. If not set, a client-specific default is used.

client_info_tag Optional[str]

Optional tag appended to the library name in parentheses (e.g. GlidePy(my-framework:1.2.3)), preserving the underlying GLIDE library identity while attributing a wrapping library or framework in CLIENT INFO/CLIENT LIST output. Applied on top of the default library name or a configured lib_name. Every character in a non-empty value must be printable ASCII from ! (U+0021) through ~ (U+007E), inclusive, excluding ( and ). An empty value is treated as unset.

protocol ProtocolVersion

The version of the RESP protocol to communicate with the server.

periodic_checks Union[PeriodicChecksStatus, PeriodicChecksManualInterval]

Configure the periodic topology checks. These checks evaluate changes in the cluster's topology, triggering a slot refresh when detected. Periodic checks ensure a quick and efficient process by querying a limited number of nodes. Defaults to PeriodicChecksStatus.ENABLED_DEFAULT_CONFIGS.

pubsub_subscriptions Optional[PubSubSubscriptions]

Pubsub subscriptions to be used for the client. Will be applied via SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE commands during connection establishment.

inflight_requests_limit Optional[int]

The maximum number of concurrent requests allowed to be in-flight (sent but not yet completed). This limit is used to control the memory usage and prevent the client from overwhelming the server or getting stuck in case of a queue backlog. If not set, a default value will be used.

recovery_requests_queue_size Optional[int]

The maximum number of requests to buffer in the recovery queue when a cluster reconnect is in progress. Buffered requests are retried transparently after reconnection. Requests beyond this limit are failed immediately to provide bounded memory usage. Set to 0 to disable the recovery queue and use fail-fast behavior. If not set, a default value of 1000 will be used.

client_az Optional[str]

Availability Zone of the client. If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within the specified AZ if exits. If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to nodes (first replicas then primary) within the specified AZ if they exist. If ReadFrom strategy is AZAffinityAllNodes, this setting ensures that readonly commands are spread equally among all nodes (primary and replicas) within the specified AZ if they exist.

advanced_config Optional[AdvancedGlideClusterClientConfiguration])

Advanced configuration settings for the client, see AdvancedGlideClusterClientConfiguration.

compression Optional[CompressionConfiguration]

Configuration for automatic compression of values. When enabled, the client will automatically compress values for set-type commands and decompress values for get-type commands. This can reduce bandwidth usage and storage requirements. If not set, compression is disabled.

client_side_cache Optional[ClientSideCache]

Configuration for client-side caching. See ClientSideCache for caching behavior details, supported commands, and expiration semantics.

In order for 2 clients to share the same cache, they must be created with the same ClientSideCache instance.

  • Clients with different ClientSideCache instances will have separate caches, even if the configurations are identical.
  • Clients using different DBs cannot share the same cache.
  • Clients using different ACL users cannot share the same cache.
Note

Currently, the reconnection strategy in cluster mode is not configurable, and exponential backoff with fixed values is used.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
class GlideClusterClientConfiguration(BaseClientConfiguration):
    """
    Represents the configuration settings for a Cluster Glide client.

    Attributes:
        addresses (List[NodeAddress]): DNS Addresses and ports of known nodes in the cluster.
            The list can be partial, as the client will attempt to map out the cluster and find all nodes.
            Unix domain socket addresses are not supported in cluster mode.
            For example::

                [
                    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
                ]

        use_tls (bool): True if communication with the cluster should use Transport Level Security.
                For advanced tls configuration, please use `AdvancedGlideClusterClientConfiguration`.
        credentials (ServerCredentials): Credentials for authentication process.
                If none are set, the client will not authenticate itself with the server.
        read_from (ReadFrom): If not set, `PRIMARY` will be used.
        request_timeout (Optional[int]):  The duration in milliseconds that the client should wait for a request to complete.
            This duration encompasses sending the request, awaiting for a response from the server, and any required
            reconnection or retries.
            If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly
            set, a default value of 250 milliseconds will be used.
        reconnect_strategy (Optional[BackoffStrategy]): Strategy used to determine how and when to reconnect, in case of
            connection failures.
            If not set, a default backoff strategy will be used.
        database_id (Optional[int]): Index of the logical database to connect to.
        client_name (Optional[str]): Client name to be used for the client. Will be used with CLIENT SETNAME command during
            connection establishment.
        lib_name (Optional[str]): Library name to be used for the client. Will be used with CLIENT SETINFO LIB-NAME command
            during connection establishment. Useful for identifying a wrapping library or framework in
            ``CLIENT INFO``/``CLIENT LIST`` output. Every character in a non-empty value must be printable ASCII
            from ``!`` (U+0021) through ``~`` (U+007E), inclusive, excluding ``(`` and ``)``.
            An empty value is treated as unset.
            If not set, a client-specific default is used.
        client_info_tag (Optional[str]): Optional tag appended to the library name in parentheses
            (e.g. ``GlidePy(my-framework:1.2.3)``), preserving the underlying GLIDE library identity while
            attributing a wrapping library or framework in ``CLIENT INFO``/``CLIENT LIST`` output. Applied on top of
            the default library name or a configured ``lib_name``. Every character in a non-empty value must be
            printable ASCII from ``!`` (U+0021) through ``~`` (U+007E), inclusive, excluding ``(`` and ``)``.
            An empty value is treated as unset.
        protocol (ProtocolVersion): The version of the RESP protocol to communicate with the server.
        periodic_checks (Union[PeriodicChecksStatus, PeriodicChecksManualInterval]): Configure the periodic topology checks.
            These checks evaluate changes in the cluster's topology, triggering a slot refresh when detected.
            Periodic checks ensure a quick and efficient process by querying a limited number of nodes.
            Defaults to PeriodicChecksStatus.ENABLED_DEFAULT_CONFIGS.
        pubsub_subscriptions (Optional[GlideClusterClientConfiguration.PubSubSubscriptions]): Pubsub subscriptions to be used
            for the client.
            Will be applied via SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE commands during connection establishment.
        inflight_requests_limit (Optional[int]): The maximum number of concurrent requests allowed to be in-flight
            (sent but not yet completed).
            This limit is used to control the memory usage and prevent the client from overwhelming the server or getting
            stuck in case of a queue backlog.
            If not set, a default value will be used.
        recovery_requests_queue_size (Optional[int]): The maximum number of requests to buffer in the
            recovery queue when a cluster reconnect is in progress. Buffered requests are retried
            transparently after reconnection. Requests beyond this limit are failed immediately to
            provide bounded memory usage.
            Set to 0 to disable the recovery queue and use fail-fast behavior.
            If not set, a default value of 1000 will be used.
        client_az (Optional[str]): Availability Zone of the client.
            If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within
            the specified AZ if exits.
            If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to
            nodes (first replicas then primary) within the specified AZ if they exist.
            If ReadFrom strategy is AZAffinityAllNodes, this setting ensures that readonly commands are spread equally
            among all nodes (primary and replicas) within the specified AZ if they exist.
        advanced_config (Optional[AdvancedGlideClusterClientConfiguration]) : Advanced configuration settings for the client,
            see `AdvancedGlideClusterClientConfiguration`.
        compression (Optional[CompressionConfiguration]): Configuration for automatic compression of values.
            When enabled, the client will automatically compress values for set-type commands and decompress
            values for get-type commands. This can reduce bandwidth usage and storage requirements.
            If not set, compression is disabled.
        client_side_cache (Optional[ClientSideCache]): Configuration for client-side caching.
            See `ClientSideCache` for caching behavior details, supported commands, and expiration semantics.

            In order for 2 clients to share the same cache, they must be
            created with the same ``ClientSideCache`` instance.

            - Clients with different ``ClientSideCache`` instances will have separate caches,
              even if the configurations are identical.
            - Clients using different DBs cannot share the same cache.
            - Clients using different ACL users cannot share the same cache.

    Note:
        Currently, the reconnection strategy in cluster mode is not configurable, and exponential backoff
        with fixed values is used.
    """

    class PubSubChannelModes(IntEnum):
        """
        Describes pubsub subsciption modes.
        See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
        """

        Exact = 0
        """ Use exact channel names """
        Pattern = 1
        """ Use channel name patterns """
        Sharded = 2
        """ Use sharded pubsub. Available since Valkey 7.0.0. """

    @dataclass
    class PubSubSubscriptions:
        """Describes pubsub configuration for cluster mode client.

        Attributes:
            channels_and_patterns (Dict[GlideClusterClientConfiguration.PubSubChannelModes, Set[str]]):
                Channels and patterns by modes.
            callback (Optional[Callable[[PubSubMsg, Any], None]]):
                Optional callback to accept the incoming messages.
            context (Any):
                Arbitrary context to pass to the callback.
        """

        channels_and_patterns: Dict[
            GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
        ]
        callback: Optional[Callable[[PubSubMsg, Any], None]]
        context: Any

    @dataclass
    class PubSubState:
        desired_subscriptions: Dict[
            GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
        ]
        actual_subscriptions: Dict[
            GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
        ]

    def __init__(
        self,
        addresses: List[NodeAddress],
        use_tls: bool = False,
        credentials: Optional[ServerCredentials] = None,
        read_from: ReadFrom = ReadFrom.PRIMARY,
        request_timeout: Optional[int] = None,
        reconnect_strategy: Optional[BackoffStrategy] = None,
        database_id: Optional[int] = None,
        client_name: Optional[str] = None,
        protocol: ProtocolVersion = ProtocolVersion.RESP3,
        periodic_checks: Union[
            PeriodicChecksStatus, PeriodicChecksManualInterval
        ] = PeriodicChecksStatus.ENABLED_DEFAULT_CONFIGS,
        pubsub_subscriptions: Optional[PubSubSubscriptions] = None,
        inflight_requests_limit: Optional[int] = None,
        recovery_requests_queue_size: Optional[int] = None,
        client_az: Optional[str] = None,
        advanced_config: Optional[AdvancedGlideClusterClientConfiguration] = None,
        lazy_connect: Optional[bool] = None,
        compression: Optional[CompressionConfiguration] = None,
        client_side_cache: Optional[ClientSideCache] = None,
        address_resolver: Optional[Callable[[str, int], Tuple[str, int]]] = None,
        client_circuit_breaker: Optional[ClientCircuitBreakerConfiguration] = None,
        lib_name: Optional[str] = None,
        client_info_tag: Optional[str] = None,
        rdma: Optional[RdmaConfiguration] = None,
    ):
        super().__init__(
            addresses=addresses,
            use_tls=use_tls,
            credentials=credentials,
            read_from=read_from,
            request_timeout=request_timeout,
            reconnect_strategy=reconnect_strategy,
            database_id=database_id,
            client_name=client_name,
            lib_name=lib_name,
            client_info_tag=client_info_tag,
            protocol=protocol,
            inflight_requests_limit=inflight_requests_limit,
            client_az=client_az,
            advanced_config=advanced_config,
            lazy_connect=lazy_connect,
            compression=compression,
            rdma=rdma,
            client_side_cache=client_side_cache,
            address_resolver=address_resolver,
            client_circuit_breaker=client_circuit_breaker,
        )
        self.periodic_checks = periodic_checks
        self.pubsub_subscriptions = pubsub_subscriptions
        self.recovery_requests_queue_size = recovery_requests_queue_size

    def _create_a_protobuf_conn_request(
        self, cluster_mode: bool = False
    ) -> ConnectionRequest:
        assert cluster_mode is True
        request = super()._create_a_protobuf_conn_request(cluster_mode)
        if type(self.periodic_checks) is PeriodicChecksManualInterval:
            request.periodic_checks_manual_interval.duration_in_sec = (
                self.periodic_checks.duration_in_sec
            )
        elif self.periodic_checks == PeriodicChecksStatus.DISABLED:
            request.periodic_checks_disabled.SetInParent()

        if self.pubsub_subscriptions:
            if self.protocol == ProtocolVersion.RESP2:
                raise ConfigurationError(
                    "PubSub subscriptions require RESP3 protocol, but RESP2 was configured."
                )
            if (
                self.pubsub_subscriptions.context is not None
                and not self.pubsub_subscriptions.callback
            ):
                raise ConfigurationError(
                    "PubSub subscriptions with a context require a callback function to be configured."
                )
            for (
                channel_type,
                channels_patterns,
            ) in self.pubsub_subscriptions.channels_and_patterns.items():
                entry = request.pubsub_subscriptions.channels_or_patterns_by_type[
                    int(channel_type)
                ]
                for channel_pattern in channels_patterns:
                    entry.channels_or_patterns.append(str.encode(channel_pattern))

        if self.lazy_connect is not None:
            request.lazy_connect = self.lazy_connect
        if self.recovery_requests_queue_size is not None:
            request.recovery_requests_queue_size = self.recovery_requests_queue_size
        return request

    def _get_pubsub_callback_and_context(
        self,
    ) -> Tuple[Optional[Callable[[PubSubMsg, Any], None]], Any]:
        if self.pubsub_subscriptions:
            return self.pubsub_subscriptions.callback, self.pubsub_subscriptions.context
        return None, None

PubSubChannelModes

Bases: IntEnum

Describes pubsub subsciption modes. See valkey.io for more details

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
class PubSubChannelModes(IntEnum):
    """
    Describes pubsub subsciption modes.
    See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
    """

    Exact = 0
    """ Use exact channel names """
    Pattern = 1
    """ Use channel name patterns """
    Sharded = 2
    """ Use sharded pubsub. Available since Valkey 7.0.0. """

Exact = 0 class-attribute instance-attribute

Use exact channel names

Pattern = 1 class-attribute instance-attribute

Use channel name patterns

Sharded = 2 class-attribute instance-attribute

Use sharded pubsub. Available since Valkey 7.0.0.

PubSubSubscriptions dataclass

Describes pubsub configuration for cluster mode client.

Attributes:

Name Type Description
channels_and_patterns Dict[PubSubChannelModes, Set[str]]

Channels and patterns by modes.

callback Optional[Callable[[PubSubMsg, Any], None]]

Optional callback to accept the incoming messages.

context Any

Arbitrary context to pass to the callback.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
@dataclass
class PubSubSubscriptions:
    """Describes pubsub configuration for cluster mode client.

    Attributes:
        channels_and_patterns (Dict[GlideClusterClientConfiguration.PubSubChannelModes, Set[str]]):
            Channels and patterns by modes.
        callback (Optional[Callable[[PubSubMsg, Any], None]]):
            Optional callback to accept the incoming messages.
        context (Any):
            Arbitrary context to pass to the callback.
    """

    channels_and_patterns: Dict[
        GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
    ]
    callback: Optional[Callable[[PubSubMsg, Any], None]]
    context: Any

IamAuthConfig

Configuration settings for IAM authentication.

Attributes:

Name Type Description
cluster_name str

The name of the ElastiCache/MemoryDB cluster.

service ServiceType

The service type (ElastiCache or MemoryDB).

region str

The AWS region containing the cluster.

refresh_interval_seconds Optional[int]

Optional token refresh interval. If omitted, the core uses 300 seconds (5 minutes).

credential_provider Optional[GlideCredentialProvider]

Optional custom AWS credential source. Direct clients use it instead of the default AWS credential chain. Python client pools do not support custom providers.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
class IamAuthConfig:
    """Configuration settings for IAM authentication.

    Attributes:
        cluster_name (str): The name of the ElastiCache/MemoryDB cluster.
        service (ServiceType): The service type (ElastiCache or MemoryDB).
        region (str): The AWS region containing the cluster.
        refresh_interval_seconds (Optional[int]): Optional token refresh interval.
            If omitted, the core uses 300 seconds (5 minutes).
        credential_provider (Optional[GlideCredentialProvider]): Optional custom
            AWS credential source. Direct clients use it instead of the default
            AWS credential chain. Python client pools do not support custom
            providers.
    """

    def __init__(
        self,
        cluster_name: str,
        service: ServiceType,
        region: str,
        refresh_interval_seconds: Optional[int] = None,
        credential_provider: Optional[GlideCredentialProvider] = None,
    ):
        if credential_provider is not None and not callable(credential_provider):
            raise ValueError("credential_provider must be callable")

        self.cluster_name = cluster_name
        self.service = service
        self.region = region
        self.refresh_interval_seconds = refresh_interval_seconds
        self.credential_provider = credential_provider
        self._credential_provider_is_async = (
            credential_provider is not None and _is_async_callable(credential_provider)
        )

NodeAddress

Represents the address of a node, either a TCP host and port or a Unix domain socket.

Attributes:

Name Type Description
host str

The server host. Defaults to "localhost".

port int

The server port. Defaults to 6379.

unix_socket_path Optional[StrPath]

Absolute path of the server's Unix domain socket. When set, host and port are ignored. Standalone clients only, without TLS. For example::

NodeAddress(unix_socket_path="/run/valkey/valkey.sock")
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class NodeAddress:
    """
    Represents the address of a node, either a TCP host and port or a Unix domain socket.

    Attributes:
        host (str): The server host. Defaults to "localhost".
        port (int): The server port. Defaults to 6379.
        unix_socket_path (Optional[StrPath]): Absolute path of the server's Unix domain socket.
            When set, ``host`` and ``port`` are ignored. Standalone clients only, without TLS.
            For example::

                NodeAddress(unix_socket_path="/run/valkey/valkey.sock")
    """

    def __init__(
        self,
        host: str = "localhost",
        port: int = 6379,
        *,
        unix_socket_path: Optional[StrPath] = None,
    ):
        self.host = host
        self.port = port
        self.unix_socket_path = (
            None if unix_socket_path is None else os.fspath(unix_socket_path)
        )

NodeDiscoveryMode

Bases: Enum

Controls how the client discovers node roles and topology in standalone mode.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
class NodeDiscoveryMode(Enum):
    """
    Controls how the client discovers node roles and topology in standalone mode.
    """

    STANDARD = ProtobufNodeDiscoveryMode.Standard
    """
    Default: verify node roles via INFO REPLICATION, use only provided addresses.
    The client connects to all provided addresses and identifies which is the primary.
    """
    STATIC = ProtobufNodeDiscoveryMode.Static
    """
    Skip role detection entirely. Trust provided addresses as-is; first address is primary.
    Use when connecting through a proxy (e.g., Envoy) or when the topology is known and static.

    Note: Do not set ``client_name`` when using this mode with a proxy.
    """
    DISCOVER_ALL = ProtobufNodeDiscoveryMode.DiscoverAll
    """
    Discover full topology (primary + all replicas) from any starting node.
    Provide any single node address and the client will find and connect to all other nodes.
    """

STANDARD = ProtobufNodeDiscoveryMode.Standard class-attribute instance-attribute

Default: verify node roles via INFO REPLICATION, use only provided addresses. The client connects to all provided addresses and identifies which is the primary.

STATIC = ProtobufNodeDiscoveryMode.Static class-attribute instance-attribute

Skip role detection entirely. Trust provided addresses as-is; first address is primary. Use when connecting through a proxy (e.g., Envoy) or when the topology is known and static.

Note: Do not set client_name when using this mode with a proxy.

DISCOVER_ALL = ProtobufNodeDiscoveryMode.DiscoverAll class-attribute instance-attribute

Discover full topology (primary + all replicas) from any starting node. Provide any single node address and the client will find and connect to all other nodes.

PeriodicChecksManualInterval

Represents a manually configured interval for periodic checks.

Attributes:

Name Type Description
duration_in_sec int

The duration in seconds for the interval between periodic checks.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
684
685
686
687
688
689
690
691
692
693
class PeriodicChecksManualInterval:
    """
    Represents a manually configured interval for periodic checks.

    Attributes:
        duration_in_sec (int): The duration in seconds for the interval between periodic checks.
    """

    def __init__(self, duration_in_sec: int) -> None:
        self.duration_in_sec = duration_in_sec

PeriodicChecksStatus

Bases: Enum

Represents the cluster's periodic checks status. To configure specific interval, see PeriodicChecksManualInterval.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
696
697
698
699
700
701
702
703
704
705
706
707
708
709
class PeriodicChecksStatus(Enum):
    """
    Represents the cluster's periodic checks status.
    To configure specific interval, see PeriodicChecksManualInterval.
    """

    ENABLED_DEFAULT_CONFIGS = 0
    """
    Enables the periodic checks with the default configurations.
    """
    DISABLED = 1
    """
    Disables the periodic checks.
    """

ENABLED_DEFAULT_CONFIGS = 0 class-attribute instance-attribute

Enables the periodic checks with the default configurations.

DISABLED = 1 class-attribute instance-attribute

Disables the periodic checks.

ProtocolVersion

Bases: Enum

Represents the communication protocol with the server.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
169
170
171
172
173
174
175
176
177
178
179
180
181
class ProtocolVersion(Enum):
    """
    Represents the communication protocol with the server.
    """

    RESP2 = SentProtocolVersion.RESP2
    """
    Communicate using RESP2.
    """
    RESP3 = SentProtocolVersion.RESP3
    """
    Communicate using RESP3.
    """

RESP2 = SentProtocolVersion.RESP2 class-attribute instance-attribute

Communicate using RESP2.

RESP3 = SentProtocolVersion.RESP3 class-attribute instance-attribute

Communicate using RESP3.

RdmaConfiguration dataclass

The configuration for enabling remote direct memory access (RDMA) transfers.

RDMA moves values straight between server memory and host memory the caller registered instead of through the RESP reply. Only the synchronous client supports it and only on a machine with libfabric installed — check :meth:BaseClient.rdma_usable first. Leaving this unset means that no fabric is opened and libfabric is never loaded.

Creating a client fails if RDMA is combined with enabled compression, lazy_connect, read-only mode, or static node discovery.

Attributes:

Name Type Description
provider Union[EfaDirect, Tcp]

The fabric provider to open, RdmaProvider.EfaDirect() or RdmaProvider.Tcp().

interface Optional[str]

Fabric domain to pin to when a host has more than one card. If not set, the first domain the provider returns is used.

Example::

config = GlideClientConfiguration(
    addresses=[NodeAddress("localhost", 6379)],
    rdma=RdmaConfiguration(provider=RdmaProvider.EfaDirect()),
)
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
@dataclass
class RdmaConfiguration:
    """
    The configuration for enabling remote direct memory access (RDMA) transfers.

    RDMA moves values straight between server memory and host memory the caller
    registered instead of through the RESP reply. Only the synchronous client
    supports it and only on a machine with libfabric installed — check
    :meth:`BaseClient.rdma_usable` first. Leaving this unset means that
    no fabric is opened and libfabric is never loaded.

    Creating a client fails if RDMA is combined with enabled compression,
    ``lazy_connect``, read-only mode, or static node discovery.

    Attributes:
        provider (Union[RdmaProvider.EfaDirect, RdmaProvider.Tcp]): The fabric
            provider to open, ``RdmaProvider.EfaDirect()`` or ``RdmaProvider.Tcp()``.
        interface (Optional[str]): Fabric domain to pin to when a host has more
            than one card. If not set, the first domain the provider returns is
            used.

    Example::

        config = GlideClientConfiguration(
            addresses=[NodeAddress("localhost", 6379)],
            rdma=RdmaConfiguration(provider=RdmaProvider.EfaDirect()),
        )
    """

    provider: Union["RdmaProvider.EfaDirect", "RdmaProvider.Tcp"]
    interface: Optional[str] = None

    def __post_init__(self) -> None:
        """Validate the RDMA configuration parameters."""
        if not isinstance(self.provider, (RdmaProvider.EfaDirect, RdmaProvider.Tcp)):
            raise ConfigurationError(
                "provider must be RdmaProvider.EfaDirect() or RdmaProvider.Tcp(), got "
                f"{type(self.provider).__name__}"
            )

        if (
            isinstance(self.provider, RdmaProvider.Tcp)
            and self.provider.bind is not None
        ):
            if not self.provider.bind:
                raise ConfigurationError("bind must not be empty if set")

        if self.interface is not None and not self.interface:
            raise ConfigurationError("interface must not be empty if set")

    def _to_protobuf(self) -> ProtobufRdmaConfig:
        """
        Converts the RDMA configuration to protobuf format.

        Returns:
            ProtobufRdmaConfig: The protobuf RDMA configuration.

        Raises:
            ConfigurationError: If any configuration parameter is invalid.
        """
        # Re-validate, in case the fields were reassigned after __post_init__.
        self.__post_init__()

        config = ProtobufRdmaConfig()
        if isinstance(self.provider, RdmaProvider.Tcp):
            # Reached through the field so the oneof is marked set even when
            # there is no bind address to carry.
            config.tcp.SetInParent()
            if self.provider.bind is not None:
                config.tcp.bind = self.provider.bind
        else:
            config.efa_direct.SetInParent()

        if self.interface is not None:
            config.interface = self.interface

        return config

RdmaProvider

The fabric providers that can carry RDMA transfers. Pass one to RdmaConfiguration.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
class RdmaProvider:
    """
    The fabric providers that can carry RDMA transfers.
    Pass one to ``RdmaConfiguration``.
    """

    @dataclass(frozen=True)
    class EfaDirect:
        """
        AWS Elastic Fabric Adapter, the provider RDMA is built for.
        Needs EFA hardware and libfabric on both the client and the server.
        """

    @dataclass(frozen=True)
    class Tcp:
        """
        Software-emulated RDMA transfers over TCP, for development and tests.

        Needs no hardware and offers no performance benefit over a normal ``GET`` or
        ``SET``: it exists so the RDMA path can be exercised on an ordinary machine.
        Only a client built with the ``rdma-tcp-dev`` feature (``dev.py build --rdma``
        in debug mode) honors it; release wheels refuse it when the client is created.

        Attributes:
            bind (Optional[str]): Source address to bind to. TCP binds an IP address
                where ``RdmaProvider.EfaDirect`` has none, so this has no counterpart there. If
                not set, the provider chooses.
        """

        bind: Optional[str] = None

EfaDirect dataclass

AWS Elastic Fabric Adapter, the provider RDMA is built for. Needs EFA hardware and libfabric on both the client and the server.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
340
341
342
343
344
345
@dataclass(frozen=True)
class EfaDirect:
    """
    AWS Elastic Fabric Adapter, the provider RDMA is built for.
    Needs EFA hardware and libfabric on both the client and the server.
    """

Tcp dataclass

Software-emulated RDMA transfers over TCP, for development and tests.

Needs no hardware and offers no performance benefit over a normal GET or SET: it exists so the RDMA path can be exercised on an ordinary machine. Only a client built with the rdma-tcp-dev feature (dev.py build --rdma in debug mode) honors it; release wheels refuse it when the client is created.

Attributes:

Name Type Description
bind Optional[str]

Source address to bind to. TCP binds an IP address where RdmaProvider.EfaDirect has none, so this has no counterpart there. If not set, the provider chooses.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
@dataclass(frozen=True)
class Tcp:
    """
    Software-emulated RDMA transfers over TCP, for development and tests.

    Needs no hardware and offers no performance benefit over a normal ``GET`` or
    ``SET``: it exists so the RDMA path can be exercised on an ordinary machine.
    Only a client built with the ``rdma-tcp-dev`` feature (``dev.py build --rdma``
    in debug mode) honors it; release wheels refuse it when the client is created.

    Attributes:
        bind (Optional[str]): Source address to bind to. TCP binds an IP address
            where ``RdmaProvider.EfaDirect`` has none, so this has no counterpart there. If
            not set, the provider chooses.
    """

    bind: Optional[str] = None

RdmaSetChecksum

Whether rdma_set asks the server to check the bytes it read against a CRC-32c before storing them. With a checksum, the server refuses to store bytes whose CRC-32c differs, and the write raises RdmaError.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
class RdmaSetChecksum:
    """
    Whether ``rdma_set`` asks the server to check the bytes it read against a
    CRC-32c before storing them. With a checksum, the server refuses to store
    bytes whose CRC-32c differs, and the write raises ``RdmaError``.
    """

    @dataclass(frozen=True)
    class Skip:
        """Send no checksum. The server stores whatever it read."""

    @dataclass(frozen=True)
    class Compute:
        """
        Compute the CRC-32c of the window before sending. This reads every byte
        of the window once.
        """

    @dataclass(frozen=True)
    class Known:
        """
        Send a CRC-32c the caller already has for the window's bytes, for
        example from ``GlideClient.rdma_checksum``, so the window is not read
        again.

        Attributes:
            value (int): The CRC-32c, an unsigned 32-bit integer.
        """

        value: int

Skip dataclass

Send no checksum. The server stores whatever it read.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
373
374
375
@dataclass(frozen=True)
class Skip:
    """Send no checksum. The server stores whatever it read."""

Compute dataclass

Compute the CRC-32c of the window before sending. This reads every byte of the window once.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
377
378
379
380
381
382
@dataclass(frozen=True)
class Compute:
    """
    Compute the CRC-32c of the window before sending. This reads every byte
    of the window once.
    """

Known dataclass

Send a CRC-32c the caller already has for the window's bytes, for example from GlideClient.rdma_checksum, so the window is not read again.

Attributes:

Name Type Description
value int

The CRC-32c, an unsigned 32-bit integer.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
384
385
386
387
388
389
390
391
392
393
394
395
@dataclass(frozen=True)
class Known:
    """
    Send a CRC-32c the caller already has for the window's bytes, for
    example from ``GlideClient.rdma_checksum``, so the window is not read
    again.

    Attributes:
        value (int): The CRC-32c, an unsigned 32-bit integer.
    """

    value: int

ReadFrom

Bases: Enum

Represents the client's read from strategy.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class ReadFrom(Enum):
    """
    Represents the client's read from strategy.
    """

    PRIMARY = ProtobufReadFrom.Primary
    """
    Always get from primary, in order to get the freshest data.
    """
    PREFER_REPLICA = ProtobufReadFrom.PreferReplica
    """
    Spread the requests between all replicas in a round robin manner.
    If no replica is available, route the requests to the primary.
    """
    AZ_AFFINITY = ProtobufReadFrom.AZAffinity
    """
    Spread the read requests between replicas in the same client's AZ (Aviliablity zone) in a round robin manner,
    falling back to other replicas or the primary if needed
    """
    AZ_AFFINITY_REPLICAS_AND_PRIMARY = ProtobufReadFrom.AZAffinityReplicasAndPrimary
    """
    Spread the read requests among nodes within the client's Availability Zone (AZ) in a round robin manner,
    prioritizing local replicas, then the local primary, and falling back to any replica or the primary if needed.
    """
    ALL_NODES = ProtobufReadFrom.AllNodes
    """
    Spread the read requests between all nodes (primary and replicas) in a round robin manner.
    """
    AZ_AFFINITY_ALL_NODES = ProtobufReadFrom.AZAffinityAllNodes
    """
    Spread the read requests equally among all nodes (primary and replicas) within the client's
    Availability Zone (AZ) in a round robin manner, falling back to a round robin across all
    nodes if no node in the client's AZ is available.
    """

PRIMARY = ProtobufReadFrom.Primary class-attribute instance-attribute

Always get from primary, in order to get the freshest data.

PREFER_REPLICA = ProtobufReadFrom.PreferReplica class-attribute instance-attribute

Spread the requests between all replicas in a round robin manner. If no replica is available, route the requests to the primary.

AZ_AFFINITY = ProtobufReadFrom.AZAffinity class-attribute instance-attribute

Spread the read requests between replicas in the same client's AZ (Aviliablity zone) in a round robin manner, falling back to other replicas or the primary if needed

AZ_AFFINITY_REPLICAS_AND_PRIMARY = ProtobufReadFrom.AZAffinityReplicasAndPrimary class-attribute instance-attribute

Spread the read requests among nodes within the client's Availability Zone (AZ) in a round robin manner, prioritizing local replicas, then the local primary, and falling back to any replica or the primary if needed.

ALL_NODES = ProtobufReadFrom.AllNodes class-attribute instance-attribute

Spread the read requests between all nodes (primary and replicas) in a round robin manner.

AZ_AFFINITY_ALL_NODES = ProtobufReadFrom.AZAffinityAllNodes class-attribute instance-attribute

Spread the read requests equally among all nodes (primary and replicas) within the client's Availability Zone (AZ) in a round robin manner, falling back to a round robin across all nodes if no node in the client's AZ is available.

ServerCredentials

Represents the credentials for connecting to a server.

Exactly one of the following authentication modes must be provided
  • Password-based authentication: Use password (and optionally username)
  • IAM authentication: Use username (required) and iam_config

These modes are mutually exclusive - you cannot use both simultaneously.

Attributes:

Name Type Description
password Optional[str]

The password that will be used for authenticating connections to the servers. Mutually exclusive with iam_config. Either password or iam_config must be provided.

username Optional[str]

The username that will be used for authenticating connections to the servers. If not supplied for password-based authentication, "default" will be used. Required for IAM authentication.

iam_config Optional[IamAuthConfig]

IAM authentication configuration. Mutually exclusive with password. Either password or iam_config must be provided. The client will automatically generate and refresh the authentication token based on the provided configuration.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
class ServerCredentials:
    """
    Represents the credentials for connecting to a server.

    Exactly one of the following authentication modes must be provided:
        - Password-based authentication: Use password (and optionally username)
        - IAM authentication: Use username (required) and iam_config

    These modes are mutually exclusive - you cannot use both simultaneously.

    Attributes:
        password (Optional[str]): The password that will be used for authenticating connections to the servers.
            Mutually exclusive with iam_config. Either password or iam_config must be provided.
        username (Optional[str]): The username that will be used for authenticating connections to the servers.
            If not supplied for password-based authentication, "default" will be used.
            Required for IAM authentication.
        iam_config (Optional[IamAuthConfig]): IAM authentication configuration. Mutually exclusive with password.
            Either password or iam_config must be provided.
            The client will automatically generate and refresh the authentication token based on the provided configuration.
    """

    def __init__(
        self,
        password: Optional[str] = None,
        username: Optional[str] = None,
        iam_config: Optional[IamAuthConfig] = None,
    ):
        # Validate mutual exclusivity
        if password is not None and iam_config is not None:
            raise ConfigurationError(
                "password and iam_config are mutually exclusive. Use either password-based or IAM authentication, not both."
            )

        # Validate IAM requires username
        if iam_config is not None and not username:
            raise ConfigurationError("username is required for IAM authentication.")

        # At least one authentication method must be provided
        if password is None and iam_config is None:
            raise ConfigurationError(
                "Either password or iam_config must be provided for authentication."
            )

        self.password = password
        self.username = username
        self.iam_config = iam_config

    def is_iam_auth(self) -> bool:
        """Returns True if this credential is configured for IAM authentication."""
        return self.iam_config is not None

is_iam_auth()

Returns True if this credential is configured for IAM authentication.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
679
680
681
def is_iam_auth(self) -> bool:
    """Returns True if this credential is configured for IAM authentication."""
    return self.iam_config is not None

ServiceType

Bases: Enum

Represents the types of AWS services that can be used for IAM authentication.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
511
512
513
514
515
516
517
518
519
class ServiceType(Enum):
    """
    Represents the types of AWS services that can be used for IAM authentication.
    """

    ELASTICACHE = 0
    """Amazon ElastiCache service."""
    MEMORYDB = 1
    """Amazon MemoryDB service."""

ELASTICACHE = 0 class-attribute instance-attribute

Amazon ElastiCache service.

MEMORYDB = 1 class-attribute instance-attribute

Amazon MemoryDB service.

TlsAdvancedConfiguration

Advanced TLS configuration for standalone and cluster clients.

Mutual TLS (mTLS) is configured through the keyword-only constructor parameters in one of two mutually-exclusive modes: static bytes (client_cert_pem + client_key_pem) or path-based with automatic reload (client_cert_path + client_key_path).

Attributes:

Name Type Description
use_insecure_tls Optional[bool]

Whether to bypass TLS certificate verification.

  • When set to True, the client skips certificate validation. This is useful when connecting to servers or clusters using self-signed certificates, or when DNS entries (e.g., CNAMEs) don't match certificate hostnames.

  • This setting is typically used in development or testing environments. It is strongly discouraged in production, as it introduces security risks such as man-in-the-middle attacks.

  • Only valid if TLS is already enabled in the base client configuration. Enabling it without TLS will result in a ConfigurationError.

  • Default: False (verification is enforced).

root_pem_cacerts Optional[bytes]

Custom root certificate data for TLS connections in PEM format.

  • When provided, these certificates will be used instead of the system's default trust store. This is useful for connecting to servers with self-signed certificates or corporate certificate authorities.

  • If set to an empty bytes object (non-None but length 0), a ConfigurationError will be raised.

  • If None (default), the system's default certificate trust store will be used (platform verifier).

  • The certificate data should be in PEM format as a bytes object.

  • Multiple certificates can be provided by concatenating them in PEM format.

Example usage::

# Load from file
with open('/path/to/ca-cert.pem', 'rb') as f:
    cert_data = f.read()
tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)

# Or provide directly
cert_data = b"-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"
tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)
client_cert_pem Optional[bytes]

Client certificate data for mutual TLS authentication in PEM format.

  • When provided along with client_key_pem, enables mutual TLS (mTLS) authentication so that the client presents its certificate to the server.

  • This is to be used when the server requires client certificate authentication.

  • If set to an empty bytes object (non-None but length 0), a ConfigurationError will be raised.

  • If None (default), no client certificate will be presented.

  • The certificate data should be in PEM format as a bytes object.

  • Must be used together with client_key_pem.

Example usage::

# Load from file
with open('/path/to/client-cert.pem', 'rb') as f:
    client_cert = f.read()
with open('/path/to/client-key.pem', 'rb') as f:
    client_key = f.read()
tls_config = TlsAdvancedConfiguration(
    client_cert_pem=client_cert,
    client_key_pem=client_key
)
client_key_pem Optional[bytes]

Client private key data for mutual TLS authentication in PEM format.

  • When provided along with client_cert_pem, enables mutual TLS (mTLS) authentication.

  • This private key corresponds to the certificate provided in client_cert_pem.

  • If set to an empty bytes object (non-None but length 0), a ConfigurationError will be raised.

  • If None (default), no client key will be used.

  • The key data should be in PEM format as a bytes object.

  • Must be used together with client_cert_pem.

client_cert_path Optional[StrPath]

Path to the PEM-encoded client certificate for mutual TLS authentication.

  • When provided along with client_key_path, enables path-based mutual TLS (mTLS) with automatic reload: the GLIDE core re-reads both files on a cadence, so a rotated certificate is adopted on the next reconnect while existing open connections keep their current material. A read failure keeps the last-known-good material with no application-level exception.

  • Must be used together with client_key_path, and cannot be combined with byte-based mTLS (client_cert_pem / client_key_pem). Invalid combinations raise ConfigurationError when the connection request is built.

  • Accepts a str or any os.PathLike (including pathlib.Path). The file is read and validated by the GLIDE core when the connection is established; a missing, empty, or unreadable file surfaces as a connection error at that point.

  • If None (default), no path-based client certificate is used.

client_key_path Optional[StrPath]

Path to the PEM-encoded client private key for mutual TLS authentication.

  • When provided along with client_cert_path, completes the path-based mTLS pair and participates in the same automatic reload described above.

  • Same rules as client_cert_path: must be paired with it, cannot be combined with byte-based mTLS, and accepts a str or any os.PathLike. The file is read and validated by the GLIDE core at connection time.

  • If None (default), no path-based client key is used.

cert_reload_interval_seconds Optional[int]

Override for the path-based mTLS reload cadence, in seconds.

  • Only meaningful with path-based mTLS. Setting it without both client_cert_path and client_key_path raises ConfigurationError when the connection request is built.

  • Must be a positive integer no greater than MAX_UINT32. Values outside that range raise ConfigurationError when the connection request is built.

  • If None (default), the GLIDE core applies its default reload cadence (see DEFAULT_RELOAD_INTERVAL_SECONDS in glide-core's tls_reload module for the authoritative value).

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
class TlsAdvancedConfiguration:
    """
    Advanced TLS configuration for standalone and cluster clients.

    Mutual TLS (mTLS) is configured through the keyword-only constructor
    parameters in one of two mutually-exclusive modes: static bytes
    (``client_cert_pem`` + ``client_key_pem``) or path-based with automatic
    reload (``client_cert_path`` + ``client_key_path``).

    Attributes:
        use_insecure_tls (Optional[bool]): Whether to bypass TLS certificate verification.

            - When set to True, the client skips certificate validation.
              This is useful when connecting to servers or clusters using self-signed certificates,
              or when DNS entries (e.g., CNAMEs) don't match certificate hostnames.

            - This setting is typically used in development or testing environments. **It is
              strongly discouraged in production**, as it introduces security risks such as man-in-the-middle attacks.

            - Only valid if TLS is already enabled in the base client configuration.
              Enabling it without TLS will result in a `ConfigurationError`.

            - Default: False (verification is enforced).

        root_pem_cacerts (Optional[bytes]): Custom root certificate data for TLS connections in PEM format.

            - When provided, these certificates will be used instead of the system's default trust store.
              This is useful for connecting to servers with self-signed certificates or corporate
              certificate authorities.

            - If set to an empty bytes object (non-None but length 0), a `ConfigurationError` will be raised.

            - If None (default), the system's default certificate trust store will be used (platform verifier).

            - The certificate data should be in PEM format as a bytes object.

            - Multiple certificates can be provided by concatenating them in PEM format.

            Example usage::

                # Load from file
                with open('/path/to/ca-cert.pem', 'rb') as f:
                    cert_data = f.read()
                tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)

                # Or provide directly
                cert_data = b"-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----"
                tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)

        client_cert_pem (Optional[bytes]): Client certificate data for mutual TLS authentication in PEM format.

            - When provided along with client_key_pem, enables mutual TLS (mTLS) authentication
              so that the client presents its certificate to the server.

            - This is to be used when the server requires client certificate authentication.

            - If set to an empty bytes object (non-None but length 0), a `ConfigurationError` will be raised.

            - If None (default), no client certificate will be presented.

            - The certificate data should be in PEM format as a bytes object.

            - Must be used together with client_key_pem.

            Example usage::

                # Load from file
                with open('/path/to/client-cert.pem', 'rb') as f:
                    client_cert = f.read()
                with open('/path/to/client-key.pem', 'rb') as f:
                    client_key = f.read()
                tls_config = TlsAdvancedConfiguration(
                    client_cert_pem=client_cert,
                    client_key_pem=client_key
                )

        client_key_pem (Optional[bytes]): Client private key data for mutual TLS authentication in PEM format.

            - When provided along with client_cert_pem, enables mutual TLS (mTLS) authentication.

            - This private key corresponds to the certificate provided in client_cert_pem.

            - If set to an empty bytes object (non-None but length 0), a `ConfigurationError` will be raised.

            - If None (default), no client key will be used.

            - The key data should be in PEM format as a bytes object.

            - Must be used together with client_cert_pem.

        client_cert_path (Optional[StrPath]): Path to the PEM-encoded client certificate for mutual TLS authentication.

            - When provided along with ``client_key_path``, enables path-based mutual TLS (mTLS)
              with automatic reload: the GLIDE core re-reads both files on a cadence, so a rotated
              certificate is adopted on the next reconnect while existing open connections keep
              their current material. A read failure keeps the last-known-good material with no
              application-level exception.

            - Must be used together with ``client_key_path``, and cannot be combined with
              byte-based mTLS (``client_cert_pem`` / ``client_key_pem``). Invalid combinations
              raise ``ConfigurationError`` when the connection request is built.

            - Accepts a ``str`` or any ``os.PathLike`` (including ``pathlib.Path``). The file is
              read and validated by the GLIDE core when the connection is established; a missing,
              empty, or unreadable file surfaces as a connection error at that point.

            - If None (default), no path-based client certificate is used.

        client_key_path (Optional[StrPath]): Path to the PEM-encoded client private key for mutual TLS authentication.

            - When provided along with ``client_cert_path``, completes the path-based mTLS pair
              and participates in the same automatic reload described above.

            - Same rules as ``client_cert_path``: must be paired with it, cannot be combined with
              byte-based mTLS, and accepts a ``str`` or any ``os.PathLike``. The file is read and
              validated by the GLIDE core at connection time.

            - If None (default), no path-based client key is used.

        cert_reload_interval_seconds (Optional[int]): Override for the path-based mTLS reload cadence, in seconds.

            - Only meaningful with path-based mTLS. Setting it without both ``client_cert_path``
              and ``client_key_path`` raises ``ConfigurationError`` when the connection request
              is built.

            - Must be a positive integer no greater than ``MAX_UINT32``.
              Values outside that range raise ``ConfigurationError`` when the connection
              request is built.

            - If None (default), the GLIDE core applies its default reload cadence (see
              ``DEFAULT_RELOAD_INTERVAL_SECONDS`` in glide-core's ``tls_reload`` module for the
              authoritative value).
    """

    def __init__(
        self,
        use_insecure_tls: Optional[bool] = None,
        root_pem_cacerts: Optional[bytes] = None,
        client_cert_pem: Optional[bytes] = None,
        client_key_pem: Optional[bytes] = None,
        *,
        client_cert_path: Optional[StrPath] = None,
        client_key_path: Optional[StrPath] = None,
        cert_reload_interval_seconds: Optional[int] = None,
    ):
        self.use_insecure_tls = use_insecure_tls
        self.root_pem_cacerts = root_pem_cacerts
        self.client_cert_pem = client_cert_pem
        self.client_key_pem = client_key_pem
        # Store the paths as provided; normalization to ``str`` is deferred to
        # protobuf creation so these public attributes reflect the user's input.
        self.client_cert_path = client_cert_path
        self.client_key_path = client_key_path
        self.cert_reload_interval_seconds = cert_reload_interval_seconds

CircuitBreakerError

Bases: RequestError

Thrown when a request is rejected because the client circuit breaker is open.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
69
70
71
72
73
74
class CircuitBreakerError(RequestError):
    """
    Thrown when a request is rejected because the client circuit breaker is open.
    """

    pass

ClosingError

Bases: GlideError

Errors that report that the client has closed and is no longer usable.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
20
21
22
23
24
25
class ClosingError(GlideError):
    """
    Errors that report that the client has closed and is no longer usable.
    """

    pass

ConfigurationError

Bases: RequestError

Errors that are thrown when a request cannot be completed in current configuration settings.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
61
62
63
64
65
66
class ConfigurationError(RequestError):
    """
    Errors that are thrown when a request cannot be completed in current configuration settings.
    """

    pass

ConnectionError

Bases: RequestError

Errors that are thrown when a connection disconnects. These errors can be temporary, as the client will attempt to reconnect.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
52
53
54
55
56
57
58
class ConnectionError(RequestError):
    """
    Errors that are thrown when a connection disconnects.
    These errors can be temporary, as the client will attempt to reconnect.
    """

    pass

ExecAbortError

Bases: RequestError

Errors that are thrown when a transaction is aborted.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
44
45
46
47
48
49
class ExecAbortError(RequestError):
    """
    Errors that are thrown when a transaction is aborted.
    """

    pass

GlideError

Bases: Exception

Base class for errors.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
 8
 9
10
11
12
13
14
15
16
17
class GlideError(Exception):
    """
    Base class for errors.
    """

    def __init__(self, message: Optional[str] = None):
        super().__init__(message or "No error message provided")

    def name(self):
        return self.__class__.__name__

LoggerError

Bases: GlideError

Errors that are thrown when the logger has an error initializing.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
85
86
87
88
89
90
class LoggerError(GlideError):
    """
    Errors that are thrown when the logger has an error initializing.
    """

    pass

RdmaError

Bases: RequestError

Thrown when an RDMA transfer cannot be completed or RDMA is not supported.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
77
78
79
80
81
82
class RdmaError(RequestError):
    """
    Thrown when an RDMA transfer cannot be completed or RDMA is not supported.
    """

    pass

RequestError

Bases: GlideError

Errors that were reported during a request.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
28
29
30
31
32
33
class RequestError(GlideError):
    """
    Errors that were reported during a request.
    """

    pass

TimeoutError

Bases: RequestError

Errors that are thrown when a request times out.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
36
37
38
39
40
41
class TimeoutError(RequestError):
    """
    Errors that are thrown when a request times out.
    """

    pass

OpenTelemetryConfig

Configuration for OpenTelemetry integration.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/opentelemetry.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
class OpenTelemetryConfig:
    """Configuration for OpenTelemetry integration."""

    def __init__(
        self,
        traces: Optional[OpenTelemetryTracesConfig] = None,
        metrics: Optional[OpenTelemetryMetricsConfig] = None,
        flush_interval_ms: Optional[int] = None,
    ) -> None:
        self.traces = traces
        self.metrics = metrics
        self.flush_interval_ms = flush_interval_ms

    def get_traces(self) -> Optional[OpenTelemetryTracesConfig]:
        return self.traces

    def set_traces(self, traces: OpenTelemetryTracesConfig) -> None:
        self.traces = traces

    def get_metrics(self) -> Optional[OpenTelemetryMetricsConfig]:
        return self.metrics

    def get_flush_interval_ms(self) -> Optional[int]:
        return self.flush_interval_ms

OpenTelemetryMetricsConfig

Configuration for exporting OpenTelemetry metrics.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/opentelemetry.py
185
186
187
188
189
190
191
192
class OpenTelemetryMetricsConfig:
    """Configuration for exporting OpenTelemetry metrics."""

    def __init__(self, endpoint: str) -> None:
        self.endpoint = endpoint

    def get_endpoint(self) -> str:
        return self.endpoint

OpenTelemetryTracesConfig

Configuration for exporting OpenTelemetry traces.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/opentelemetry.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class OpenTelemetryTracesConfig:
    """Configuration for exporting OpenTelemetry traces."""

    def __init__(
        self,
        endpoint: str,
        sample_percentage: Optional[int] = None,
        enable_trace_context_propagation: bool = False,
    ) -> None:
        self.endpoint = endpoint
        self.sample_percentage = (
            sample_percentage if sample_percentage is not None else 1
        )
        self.enable_trace_context_propagation = enable_trace_context_propagation

    def get_endpoint(self) -> str:
        return self.endpoint

    def get_sample_percentage(self) -> int:
        return self.sample_percentage

AllNodes

Bases: Route

Route request to all nodes.

Warning

Don't use it with write commands, they could be routed to a replica (RO) node and fail.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
38
39
40
41
42
43
44
45
46
class AllNodes(Route):
    """
    Route request to all nodes.

    Warning:
        Don't use it with write commands, they could be routed to a replica (RO) node and fail.
    """

    pass

AllPrimaries

Bases: Route

Route request to all primary nodes.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
49
50
51
52
53
54
class AllPrimaries(Route):
    """
    Route request to all primary nodes.
    """

    pass

ByAddressRoute

Bases: Route

Routes a request to a node by its address

Attributes:

Name Type Description
host str

The endpoint of the node. If port is not provided, should be in the f"{address}:{port}" format, where address is the preferred endpoint as shown in the output of the CLUSTER SLOTS command.

port Optional[int]

The port to access on the node. If port is not provided, host is assumed to be in the format f"{address}:{port}".

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class ByAddressRoute(Route):
    """Routes a request to a node by its address

    Attributes:
        host (str): The endpoint of the node. If `port` is not provided, should be in the f"{address}:{port}" format,
            where `address` is the preferred endpoint as shown in the output of the `CLUSTER SLOTS` command.
        port (Optional[int]): The port to access on the node. If port is not provided, `host` is assumed to be in
            the format f"{address}:{port}".
    """

    def __init__(self, host: str, port: Optional[int] = None) -> None:
        super().__init__()
        if port is None:
            split = host.split(":")
            if len(split) < 2:
                raise RequestError(
                    "No port provided, expected host to be formatted as {hostname}:{port}`. Received "
                    + host
                )
            self.host = split[0]
            self.port = int(split[1])
        else:
            self.host = host
            self.port = port

RandomNode

Bases: Route

Route request to a random node.

Warning

Don't use it with write commands, because they could be randomly routed to a replica (RO) node and fail.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
57
58
59
60
61
62
63
64
65
class RandomNode(Route):
    """
    Route request to a random node.

    Warning:
        Don't use it with write commands, because they could be randomly routed to a replica (RO) node and fail.
    """

    pass

SlotIdRoute

Bases: Route

Routes a request to a node by its slot ID

Attributes:

Name Type Description
slot_type SlotType

Defines type of the node being addressed.

slot_id int

Slot number. There are 16384 slots in a Valkey cluster, and each shard manages a slot range. Unless the slot is known, it's better to route using SlotType.PRIMARY

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class SlotIdRoute(Route):
    """Routes a request to a node by its slot ID

    Attributes:
        slot_type (SlotType): Defines type of the node being addressed.
        slot_id (int): Slot number. There are 16384 slots in a Valkey cluster, and each shard
            manages a slot range. Unless the slot is known, it's better to route using
            `SlotType.PRIMARY`
    """

    def __init__(self, slot_type: SlotType, slot_id: int) -> None:
        super().__init__()
        self.slot_type = slot_type
        self.slot_id = slot_id

SlotKeyRoute

Bases: Route

Routes a request to a node by its slot key

Attributes:

Name Type Description
slot_type SlotType

Defines type of the node being addressed.

slot_key str

The request will be sent to nodes managing this key.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
68
69
70
71
72
73
74
75
76
77
78
79
class SlotKeyRoute(Route):
    """Routes a request to a node by its slot key

    Attributes:
        slot_type (SlotType): Defines type of the node being addressed.
        slot_key (str): The request will be sent to nodes managing this key.
    """

    def __init__(self, slot_type: SlotType, slot_key: str) -> None:
        super().__init__()
        self.slot_type = slot_type
        self.slot_key = slot_key

SlotType

Bases: Enum

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
15
16
17
18
19
20
21
22
23
24
25
26
27
class SlotType(Enum):
    PRIMARY = 1
    """
    Address a primary node.
    """

    REPLICA = 2
    """
    Address a replica node.

    `REPLICA` overrides the `read_from_replica` configuration. If it's used the request
    will be routed to a replica, even if the strategy is `ALWAYS_FROM_MASTER`.
    """

PRIMARY = 1 class-attribute instance-attribute

Address a primary node.

REPLICA = 2 class-attribute instance-attribute

Address a replica node.

REPLICA overrides the read_from_replica configuration. If it's used the request will be routed to a replica, even if the strategy is ALWAYS_FROM_MASTER.

load_client_certificate_and_key_from_file(cert_path, key_path)

Load a PEM-encoded client certificate and its private key from disk for byte-based mutual TLS (mTLS).

Both paths must exist and be non-empty. Use this helper when static, byte-based mTLS is desired; for automatic reload from disk, pass client_cert_path / client_key_path to TlsAdvancedConfiguration instead.

Parameters:

Name Type Description Default
cert_path StrPath

Path to the PEM-encoded client certificate file.

required
key_path StrPath

Path to the PEM-encoded client private key file.

required

Returns:

Type Description
Tuple[bytes, bytes]

Tuple of (cert_bytes, key_bytes) in PEM format.

Raises:

Type Description
FileNotFoundError

If either file does not exist.

ConfigurationError

If either file is empty or unreadable.

Example::

from glide import (
    TlsAdvancedConfiguration,
    load_client_certificate_and_key_from_file,
)

cert, key = load_client_certificate_and_key_from_file(
    "/etc/mtls/client-cert.pem",
    "/etc/mtls/client-key.pem",
)
tls_config = TlsAdvancedConfiguration(
    client_cert_pem=cert,
    client_key_pem=key,
)
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
def load_client_certificate_and_key_from_file(
    cert_path: StrPath,
    key_path: StrPath,
) -> Tuple[bytes, bytes]:
    """
    Load a PEM-encoded client certificate and its private key from disk
    for byte-based mutual TLS (mTLS).

    Both paths must exist and be non-empty. Use this helper when static,
    byte-based mTLS is desired; for automatic reload from disk, pass
    ``client_cert_path`` / ``client_key_path`` to
    ``TlsAdvancedConfiguration`` instead.

    Args:
        cert_path: Path to the PEM-encoded client certificate file.
        key_path: Path to the PEM-encoded client private key file.

    Returns:
        Tuple of ``(cert_bytes, key_bytes)`` in PEM format.

    Raises:
        FileNotFoundError: If either file does not exist.
        ConfigurationError: If either file is empty or unreadable.

    Example::

        from glide import (
            TlsAdvancedConfiguration,
            load_client_certificate_and_key_from_file,
        )

        cert, key = load_client_certificate_and_key_from_file(
            "/etc/mtls/client-cert.pem",
            "/etc/mtls/client-key.pem",
        )
        tls_config = TlsAdvancedConfiguration(
            client_cert_pem=cert,
            client_key_pem=key,
        )
    """
    cert = load_client_certificate_from_file(os.fspath(cert_path))
    key = load_client_key_from_file(os.fspath(key_path))
    return cert, key

load_client_certificate_from_file(path)

Load PEM-encoded client certificate from a file for mTLS authentication.

This is a convenience function for loading client certificates from disk to be used with TlsAdvancedConfiguration for mutual TLS (mTLS).

Parameters:

Name Type Description Default
path str

The file path to the PEM-encoded client certificate file.

required

Returns:

Name Type Description
bytes bytes

The client certificate data in PEM format.

Raises:

Type Description
FileNotFoundError

If the certificate file does not exist.

ConfigurationError

If the certificate file is empty.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
def load_client_certificate_from_file(path: str) -> bytes:
    """
    Load PEM-encoded client certificate from a file for mTLS authentication.

    This is a convenience function for loading client certificates from disk
    to be used with TlsAdvancedConfiguration for mutual TLS (mTLS).

    Args:
        path (str): The file path to the PEM-encoded client certificate file.

    Returns:
        bytes: The client certificate data in PEM format.

    Raises:
        FileNotFoundError: If the certificate file does not exist.
        ConfigurationError: If the certificate file is empty.
    """
    return _load_pem_file(path, "Client certificate")

load_client_key_from_file(path)

Load PEM-encoded client private key from a file for mutual TLS authentication.

This is a convenience function for loading client private keys from disk to be used with TlsAdvancedConfiguration for mutual TLS (mTLS).

Parameters:

Name Type Description Default
path str

The file path to the PEM-encoded client private key file.

required

Returns:

Name Type Description
bytes bytes

The client private key data in PEM format.

Raises:

Type Description
FileNotFoundError

If the key file does not exist.

ConfigurationError

If the key file is empty.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
def load_client_key_from_file(path: str) -> bytes:
    """
    Load PEM-encoded client private key from a file for mutual TLS authentication.

    This is a convenience function for loading client private keys from disk
    to be used with TlsAdvancedConfiguration for mutual TLS (mTLS).

    Args:
        path (str): The file path to the PEM-encoded client private key file.

    Returns:
        bytes: The client private key data in PEM format.

    Raises:
        FileNotFoundError: If the key file does not exist.
        ConfigurationError: If the key file is empty.
    """
    return _load_pem_file(path, "Client key")

load_root_certificates_from_file(path)

Load PEM-encoded root certificates from a file.

This is a convenience function for loading custom root certificates from disk to be used with TlsAdvancedConfiguration.

Parameters:

Name Type Description Default
path str

The file path to the PEM-encoded certificate file.

required

Returns:

Name Type Description
bytes bytes

The certificate data in PEM format.

Raises:

Type Description
FileNotFoundError

If the certificate file does not exist.

ConfigurationError

If the certificate file is empty.

Example usage::

from glide import load_root_certificates_from_file, TlsAdvancedConfiguration

certs = load_root_certificates_from_file('/path/to/ca-cert.pem')
tls_config = TlsAdvancedConfiguration(root_pem_cacerts=certs)
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
def load_root_certificates_from_file(path: str) -> bytes:
    """
    Load PEM-encoded root certificates from a file.

    This is a convenience function for loading custom root certificates from disk
    to be used with TlsAdvancedConfiguration.

    Args:
        path (str): The file path to the PEM-encoded certificate file.

    Returns:
        bytes: The certificate data in PEM format.

    Raises:
        FileNotFoundError: If the certificate file does not exist.
        ConfigurationError: If the certificate file is empty.

    Example usage::

        from glide import load_root_certificates_from_file, TlsAdvancedConfiguration

        certs = load_root_certificates_from_file('/path/to/ca-cert.pem')
        tls_config = TlsAdvancedConfiguration(root_pem_cacerts=certs)
    """
    return _load_pem_file(path, "Certificate")