Skip to content

Config

Home / python / sync / config

glide_sync.config.GlideClientConfiguration

Bases: GlideClientConfiguration

Represents the configuration settings for a Standalone Sync 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.

protocol ProtocolVersion

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

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.

advanced_config Optional[AdvancedGlideClientConfiguration]

Advanced configuration settings for the client, see AdvancedGlideClientConfiguration.

pubsub_subscriptions Optional[PubSubSubscriptions]

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

Note Optional[PubSubSubscriptions]

PubSub and inflight_requests_limit are not yet supported for the sync client.

Source code in glide_sync/config.py
 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
101
102
103
104
105
class GlideClientConfiguration(SharedGlideClientConfiguration):
    """
    Represents the configuration settings for a Standalone Sync 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.
        protocol (ProtocolVersion): The version of the RESP protocol to communicate with the server.
        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.
        advanced_config (Optional[AdvancedGlideClientConfiguration]): Advanced configuration settings for the client,
            see `AdvancedGlideClientConfiguration`.
        pubsub_subscriptions (Optional[GlideClientConfiguration.PubSubSubscriptions]): Pubsub subscriptions to be used for the
            client.
            Will be applied via SUBSCRIBE/PSUBSCRIBE commands during connection establishment.

        Note:
            PubSub and inflight_requests_limit are not yet supported for the sync client.
    """

    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,
        client_az: Optional[str] = None,
        advanced_config: Optional[AdvancedGlideClientConfiguration] = None,
        lazy_connect: Optional[bool] = None,
        pubsub_subscriptions: Optional[
            GlideClientConfiguration.PubSubSubscriptions
        ] = 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,
            protocol=protocol,
            pubsub_subscriptions=pubsub_subscriptions,
            inflight_requests_limit=None,
            client_az=client_az,
            advanced_config=advanced_config,
            lazy_connect=lazy_connect,
        )

glide_sync.config.GlideClusterClientConfiguration

Bases: GlideClusterClientConfiguration

Represents the configuration settings for a Cluster Sync 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. 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. If not set, the client will connect to database 0.

client_name Optional[str]

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

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.

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.

advanced_config Optional[AdvancedGlideClusterClientConfiguration])

Advanced configuration settings for the client, see AdvancedGlideClusterClientConfiguration.

pubsub_subscriptions Optional[PubSubSubscriptions]

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

Notes

Currently, the reconnection strategy in cluster mode is not configurable, and exponential backoff with fixed values is used. In addition, PubSub and inflight_requests_limit are not yet supported for the sync client.

Source code in glide_sync/config.py
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
146
147
148
149
150
151
152
153
154
155
156
157
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
class GlideClusterClientConfiguration(SharedGlideClusterClientConfiguration):
    """
    Represents the configuration settings for a Cluster Sync 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.
            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.
            If not set, the client will connect to database 0.
        client_name (Optional[str]): Client name to be used for the client. Will be used with CLIENT SETNAME command during
            connection establishment.
        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.
        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.
        advanced_config (Optional[AdvancedGlideClusterClientConfiguration]) : Advanced configuration settings for the client,
            see `AdvancedGlideClusterClientConfiguration`.
        pubsub_subscriptions (Optional[GlideClusterClientConfiguration.PubSubSubscriptions]): Pubsub subscriptions to be used
            for the client.
            Will be applied via SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE commands during connection establishment.


    Notes:
        Currently, the reconnection strategy in cluster mode is not configurable, and exponential backoff
        with fixed values is used.
        In addition, PubSub and inflight_requests_limit are not yet supported for the sync client.
    """

    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,
        client_az: Optional[str] = None,
        advanced_config: Optional[AdvancedGlideClusterClientConfiguration] = None,
        lazy_connect: Optional[bool] = None,
        pubsub_subscriptions: Optional[
            GlideClusterClientConfiguration.PubSubSubscriptions
        ] = 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,
            periodic_checks=periodic_checks,
            pubsub_subscriptions=pubsub_subscriptions,
            client_name=client_name,
            protocol=protocol,
            inflight_requests_limit=None,
            client_az=client_az,
            advanced_config=advanced_config,
            lazy_connect=lazy_connect,
        )

glide_shared.config.NodeAddress

Represents the address and port of a node in the cluster.

Attributes:

Name Type Description
host str

The server host. Defaults to "localhost".

port int

The server port. Defaults to 6379.

Source code in glide_shared/config.py
23
24
25
26
27
28
29
30
31
32
33
34
class NodeAddress:
    """
    Represents the address and port of a node in the cluster.

    Attributes:
        host (str, optional): The server host. Defaults to "localhost".
        port (int, optional): The server port. Defaults to 6379.
    """

    def __init__(self, host: str = "localhost", port: int = 6379):
        self.host = host
        self.port = port

glide_shared.config.ReadFrom

Bases: Enum

Represents the client's read from strategy.

Source code in glide_shared/config.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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.
    """

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.

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.

PRIMARY = ProtobufReadFrom.Primary class-attribute instance-attribute

Always get from primary, in order to get the freshest data.

glide_shared.config.ProtocolVersion

Bases: Enum

Represents the communication protocol with the server.

Source code in glide_shared/config.py
63
64
65
66
67
68
69
70
71
72
73
74
75
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.

glide_shared.config.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.

exponent_base int

The exponent base configured for the strategy.

jitter_percent Optional[int]

The Jitter percent on the calculated duration. If not set, a default value will be used.

Source code in glide_shared/config.py
 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
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.
        exponent_base (int): The exponent base configured for the strategy.
        jitter_percent (Optional[int]): The Jitter percent on the calculated duration. 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

glide_shared.config.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 glide_shared/config.py
146
147
148
149
150
151
152
153
154
155
156
157
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
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 glide_shared/config.py
193
194
195
def is_iam_auth(self) -> bool:
    """Returns True if this credential is configured for IAM authentication."""
    return self.iam_config is not None

glide_shared.config.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 glide_shared/config.py
198
199
200
201
202
203
204
205
206
207
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

glide_shared.config.PeriodicChecksStatus

Bases: Enum

Represents the cluster's periodic checks status. To configure specific interval, see PeriodicChecksManualInterval.

Source code in glide_shared/config.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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.
    """

DISABLED = 1 class-attribute instance-attribute

Disables the periodic checks.

ENABLED_DEFAULT_CONFIGS = 0 class-attribute instance-attribute

Enables the periodic checks with the default configurations.

glide_shared.config.BaseClientConfiguration

Represents the configuration settings for a Glide client.

Attributes:

Name Type Description
addresses List[NodeAddress]

DNS Addresses and ports of known nodes in the cluster. If the server is in cluster mode the list can be partial, as the client will attempt to map out the cluster and find all nodes. If the server is in standalone mode, 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. Should match the TLS configuration of the server/cluster, otherwise the connection attempt will fail. For advanced tls configuration, please use AdvancedBaseClientConfiguration.

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. Must be a non-negative integer.If not set, the client will connect to database 0.

client_name Optional[str]

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

protocol ProtocolVersion

Serialization protocol to be used. If not set, RESP3 will be used.

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.

advanced_config Optional[AdvancedBaseClientConfiguration]

Advanced configuration settings for the client.

lazy_connect Optional[bool]

Enables lazy connection mode, where physical connections to the server(s) are deferred until the first command is sent. This can reduce startup latency and allow for client creation in disconnected environments.

When set to True, the client will not attempt to connect to the specified nodes during initialization. Instead, connections will be established only when a command is actually executed.

Note that the first command executed with lazy connections may experience additional latency as it needs to establish the connection first. During this initial connection, the standard request timeout does not apply yet - instead, the connection establishment is governed by AdvancedBaseClientConfiguration.connection_timeout. The request timeout (request_timeout) only begins counting after the connection has been successfully established. This behavior can effectively increase the total time needed for the first command to complete.

This setting applies to both standalone and cluster modes. Note that if an operation is attempted and connection fails (e.g., unreachable nodes), errors will surface at that point.

If not set, connections are established immediately during client creation (equivalent to False).

Source code in glide_shared/config.py
330
331
332
333
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
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
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
475
476
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
509
510
511
512
513
514
515
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
class BaseClientConfiguration:
    """
    Represents the configuration settings for a Glide client.

    Attributes:
        addresses (List[NodeAddress]): DNS Addresses and ports of known nodes in the cluster.
            If the server is in cluster mode the list can be partial, as the client will attempt to map out
            the cluster and find all nodes.
            If the server is in standalone mode, 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.
            Should match the TLS configuration of the server/cluster, otherwise the connection attempt will fail.
            For advanced tls configuration, please use `AdvancedBaseClientConfiguration`.
        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.
            Must be a non-negative integer.If not set, the client will connect to database 0.
        client_name (Optional[str]): Client name to be used for the client. Will be used with CLIENT SETNAME command
            during connection establishment.
        protocol (ProtocolVersion): Serialization protocol to be used. If not set, `RESP3` will be used.
        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.
        advanced_config (Optional[AdvancedBaseClientConfiguration]): Advanced configuration settings for the client.

        lazy_connect (Optional[bool]): Enables lazy connection mode, where physical connections to the server(s)
            are deferred until the first command is sent. This can reduce startup latency and allow for client
            creation in disconnected environments.

            When set to `True`, the client will not attempt to connect to the specified nodes during
            initialization. Instead, connections will be established only when a command is actually executed.

            Note that the first command executed with lazy connections may experience additional latency
            as it needs to establish the connection first. During this initial connection, the standard
            request timeout does not apply yet - instead, the connection establishment is governed by
            `AdvancedBaseClientConfiguration.connection_timeout`. The request timeout (`request_timeout`)
            only begins counting after the connection has been successfully established. This behavior
            can effectively increase the total time needed for the first command to complete.

            This setting applies to both standalone and cluster modes. Note that if an operation is
            attempted and connection fails (e.g., unreachable nodes), errors will surface at that point.

            If not set, connections are established immediately during client creation (equivalent to `False`).
    """

    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,
        inflight_requests_limit: Optional[int] = None,
        client_az: Optional[str] = None,
        advanced_config: Optional[AdvancedBaseClientConfiguration] = None,
        lazy_connect: Optional[bool] = None,
    ):
        self.addresses = addresses
        self.use_tls = use_tls
        self.credentials = credentials
        self.read_from = read_from
        self.request_timeout = request_timeout
        self.reconnect_strategy = reconnect_strategy
        self.database_id = database_id
        self.client_name = client_name
        self.protocol = protocol
        self.inflight_requests_limit = inflight_requests_limit
        self.client_az = client_az
        self.advanced_config = advanced_config
        self.lazy_connect = lazy_connect

        if read_from == ReadFrom.AZ_AFFINITY and not client_az:
            raise ValueError(
                "client_az must be set when read_from is set to AZ_AFFINITY"
            )

        if read_from == ReadFrom.AZ_AFFINITY_REPLICAS_AND_PRIMARY and not client_az:
            raise ValueError(
                "client_az must be set when read_from is set to AZ_AFFINITY_REPLICAS_AND_PRIMARY"
            )

    def _set_addresses_in_request(self, request: ConnectionRequest) -> None:
        """Set addresses in the protobuf request."""
        for address in self.addresses:
            address_info = request.addresses.add()
            address_info.host = address.host
            address_info.port = address.port

    def _set_reconnect_strategy_in_request(self, request: ConnectionRequest) -> None:
        """Set reconnect strategy in the protobuf request."""
        if not self.reconnect_strategy:
            return

        request.connection_retry_strategy.number_of_retries = (
            self.reconnect_strategy.num_of_retries
        )
        request.connection_retry_strategy.factor = self.reconnect_strategy.factor
        request.connection_retry_strategy.exponent_base = (
            self.reconnect_strategy.exponent_base
        )
        if self.reconnect_strategy.jitter_percent is not None:
            request.connection_retry_strategy.jitter_percent = (
                self.reconnect_strategy.jitter_percent
            )

    def _set_credentials_in_request(self, request: ConnectionRequest) -> None:
        """Set credentials in the protobuf request."""
        if not self.credentials:
            return

        if self.credentials.username:
            request.authentication_info.username = self.credentials.username

        if self.credentials.password:
            request.authentication_info.password = self.credentials.password

        # Set IAM credentials if present
        if self.credentials.iam_config:
            iam_config = self.credentials.iam_config
            request.authentication_info.iam_credentials.cluster_name = (
                iam_config.cluster_name
            )
            request.authentication_info.iam_credentials.region = iam_config.region

            # Map ServiceType enum to protobuf ServiceType
            if iam_config.service == ServiceType.ELASTICACHE:
                from glide_shared.protobuf.connection_request_pb2 import (
                    ServiceType as ProtobufServiceType,
                )

                request.authentication_info.iam_credentials.service_type = (
                    ProtobufServiceType.ELASTICACHE
                )
            elif iam_config.service == ServiceType.MEMORYDB:
                from glide_shared.protobuf.connection_request_pb2 import (
                    ServiceType as ProtobufServiceType,
                )

                request.authentication_info.iam_credentials.service_type = (
                    ProtobufServiceType.MEMORYDB
                )

            # Set optional refresh interval
            if iam_config.refresh_interval_seconds is not None:
                request.authentication_info.iam_credentials.refresh_interval_seconds = (
                    iam_config.refresh_interval_seconds
                )

    def _create_a_protobuf_conn_request(
        self, cluster_mode: bool = False
    ) -> ConnectionRequest:
        """
        Generates a Protobuf ConnectionRequest using the values from this ClientConfiguration.

        Args:
            cluster_mode (bool, optional): The cluster mode of the client. Defaults to False.

        Returns:
            ConnectionRequest: Protobuf ConnectionRequest.
        """
        request = ConnectionRequest()

        # Set basic configuration
        self._set_addresses_in_request(request)
        request.tls_mode = TlsMode.SecureTls if self.use_tls else TlsMode.NoTls
        request.read_from = self.read_from.value
        request.cluster_mode_enabled = cluster_mode
        request.protocol = self.protocol.value

        # Set optional configuration
        if self.request_timeout:
            request.request_timeout = self.request_timeout

        self._set_reconnect_strategy_in_request(request)
        self._set_credentials_in_request(request)

        if self.client_name:
            request.client_name = self.client_name
        if self.inflight_requests_limit:
            request.inflight_requests_limit = self.inflight_requests_limit
        if self.client_az:
            request.client_az = self.client_az
        if self.database_id is not None:
            request.database_id = self.database_id
        if self.advanced_config:
            self.advanced_config._create_a_protobuf_conn_request(request)
        if self.lazy_connect is not None:
            request.lazy_connect = self.lazy_connect

        return request

    def _is_pubsub_configured(self) -> bool:
        return False

    def _get_pubsub_callback_and_context(
        self,
    ) -> Tuple[Optional[Callable[[PubSubMsg, Any], None]], Any]:
        return None, None