valkey-glide 2.0.0rc3__cp310-cp310-macosx_11_0_arm64.whl → 2.2.1rc3__cp310-cp310-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. glide/__init__.py +160 -106
  2. glide/async_commands/cluster_commands.py +108 -105
  3. glide/async_commands/core.py +637 -444
  4. glide/async_commands/{server_modules/ft.py → ft.py} +8 -7
  5. glide/async_commands/{server_modules/glide_json.py → glide_json.py} +15 -92
  6. glide/async_commands/standalone_commands.py +27 -58
  7. glide/glide.cpython-310-darwin.so +0 -0
  8. glide/glide.pyi +26 -1
  9. glide/glide_client.py +269 -125
  10. glide/logger.py +33 -21
  11. glide/opentelemetry.py +185 -0
  12. glide_shared/__init__.py +330 -0
  13. glide_shared/commands/__init__.py +0 -0
  14. {glide/async_commands → glide_shared/commands}/batch.py +476 -64
  15. glide_shared/commands/batch_options.py +261 -0
  16. glide_shared/commands/core_options.py +407 -0
  17. {glide/async_commands → glide_shared/commands}/server_modules/ft_options/ft_aggregate_options.py +3 -3
  18. {glide/async_commands → glide_shared/commands}/server_modules/ft_options/ft_create_options.py +4 -2
  19. {glide/async_commands → glide_shared/commands}/server_modules/ft_options/ft_profile_options.py +4 -4
  20. {glide/async_commands → glide_shared/commands}/server_modules/ft_options/ft_search_options.py +4 -2
  21. {glide/async_commands → glide_shared/commands}/server_modules/json_batch.py +4 -4
  22. glide_shared/commands/server_modules/json_options.py +93 -0
  23. {glide/async_commands → glide_shared/commands}/sorted_set.py +2 -2
  24. {glide/async_commands → glide_shared/commands}/stream.py +1 -1
  25. {glide → glide_shared}/config.py +386 -61
  26. {glide → glide_shared}/constants.py +3 -3
  27. {glide → glide_shared}/exceptions.py +27 -1
  28. glide_shared/protobuf/command_request_pb2.py +56 -0
  29. glide_shared/protobuf/connection_request_pb2.py +56 -0
  30. {glide → glide_shared}/protobuf/response_pb2.py +6 -6
  31. {glide → glide_shared}/routes.py +54 -15
  32. valkey_glide-2.2.1rc3.dist-info/METADATA +210 -0
  33. valkey_glide-2.2.1rc3.dist-info/RECORD +40 -0
  34. glide/protobuf/command_request_pb2.py +0 -54
  35. glide/protobuf/command_request_pb2.pyi +0 -1187
  36. glide/protobuf/connection_request_pb2.py +0 -54
  37. glide/protobuf/connection_request_pb2.pyi +0 -320
  38. glide/protobuf/response_pb2.pyi +0 -100
  39. valkey_glide-2.0.0rc3.dist-info/METADATA +0 -127
  40. valkey_glide-2.0.0rc3.dist-info/RECORD +0 -37
  41. {glide/async_commands → glide_shared/commands}/bitmap.py +0 -0
  42. {glide/async_commands → glide_shared/commands}/command_args.py +0 -0
  43. {glide/async_commands → glide_shared/commands}/server_modules/ft_options/ft_constants.py +0 -0
  44. {glide → glide_shared}/protobuf_codec.py +0 -0
  45. {valkey_glide-2.0.0rc3.dist-info → valkey_glide-2.2.1rc3.dist-info}/WHEEL +0 -0
@@ -0,0 +1,261 @@
1
+ # Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
2
+
3
+ from typing import Optional
4
+
5
+ from glide_shared.constants import TSingleNodeRoute
6
+
7
+
8
+ class BatchRetryStrategy:
9
+ """
10
+ Defines a retry strategy for cluster batch requests, allowing control over retries in case of
11
+ server or connection errors.
12
+
13
+ This strategy determines whether failed commands should be retried, impacting execution order
14
+ and potential side effects.
15
+
16
+ Behavior:
17
+ - If `retry_server_error` is `True`, failed commands with a retriable error (e.g.,
18
+ `TRYAGAIN`) will be retried.
19
+ - If `retry_connection_error` is `True`, batch requests will be retried on
20
+ connection failures.
21
+
22
+ Cautions:
23
+ - **Server Errors:** Retrying may cause commands targeting the same slot to be executed
24
+ out of order.
25
+ - **Connection Errors:** Retrying may lead to duplicate executions, since the server might
26
+ have already received and processed the request before the error occurred.
27
+
28
+ Example Scenario:
29
+ ```
30
+ MGET key {key}:1
31
+ SET key "value"
32
+ ```
33
+
34
+ Expected response when keys are empty:
35
+ ```
36
+ [None, None]
37
+ "OK"
38
+ ```
39
+
40
+ However, if the slot is migrating, both commands may return an `ASK` error and be
41
+ redirected. Upon `ASK` redirection, a multi-key command may return a `TRYAGAIN`
42
+ error (triggering a retry), while the `SET` command succeeds immediately. This
43
+ can result in an unintended reordering of commands if the first command is retried
44
+ after the slot stabilizes:
45
+ ```
46
+ ["value", None]
47
+ "OK"
48
+ ```
49
+
50
+ Note:
51
+ Currently, retry strategies are supported only for non-atomic batches.
52
+
53
+ Default:
54
+ Both `retry_server_error` and `retry_connection_error` are set to `False`.
55
+
56
+ Args:
57
+ retry_server_error (bool): If `True`, failed commands with a retriable error (e.g., `TRYAGAIN`)
58
+ will be automatically retried.
59
+
60
+ ⚠️ **Warning:** Enabling this flag may cause commands targeting the same slot to execute
61
+ out of order.
62
+
63
+ By default, this is set to `False`.
64
+
65
+ retry_connection_error (bool): If `True`, batch requests will be retried in case of connection errors.
66
+
67
+ ⚠️ **Warning:** Retrying after a connection error may lead to duplicate executions, since
68
+ the server might have already received and processed the request before the error occurred.
69
+
70
+ By default, this is set to `False`.
71
+
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ retry_server_error: bool = False,
77
+ retry_connection_error: bool = False,
78
+ ):
79
+ """
80
+ Initialize a BatchRetryStrategy.
81
+
82
+ Args:
83
+ retry_server_error (bool): If `True`, failed commands with a retriable error (e.g., `TRYAGAIN`)
84
+ will be automatically retried.
85
+
86
+ ⚠️ **Warning:** Enabling this flag may cause commands targeting the same slot to execute
87
+ out of order.
88
+
89
+ By default, this is set to `False`.
90
+
91
+ retry_connection_error (bool): If `True`, batch requests will be retried in case of connection errors.
92
+
93
+ ⚠️ **Warning:** Retrying after a connection error may lead to duplicate executions, since
94
+ the server might have already received and processed the request before the error occurred.
95
+
96
+ By default, this is set to `False`.
97
+
98
+ """
99
+ self.retry_server_error = retry_server_error
100
+ self.retry_connection_error = retry_connection_error
101
+
102
+
103
+ class BaseBatchOptions:
104
+ """
105
+ Base options settings class for sending a batch request. Shared settings for standalone and
106
+ cluster batch requests.
107
+
108
+ Args:
109
+ timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
110
+ to complete. This duration encompasses sending the request, awaiting a response from the server,
111
+ and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
112
+ it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
113
+ """
114
+
115
+ def __init__(
116
+ self,
117
+ timeout: Optional[int] = None,
118
+ ):
119
+ """
120
+ Initialize BaseBatchOptions.
121
+
122
+ Args:
123
+ timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
124
+ to complete. This duration encompasses sending the request, awaiting a response from the server,
125
+ and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
126
+ it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
127
+ """
128
+ self.timeout = timeout
129
+
130
+
131
+ class BatchOptions(BaseBatchOptions):
132
+ """
133
+ Options for a batch request for a standalone client.
134
+
135
+ Args:
136
+ timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
137
+ to complete. This duration encompasses sending the request, awaiting a response from the server,
138
+ and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
139
+ it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ timeout: Optional[int] = None,
145
+ ):
146
+ """
147
+ Options for a batch request for a standalone client
148
+
149
+ Args:
150
+ timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
151
+ to complete. This duration encompasses sending the request, awaiting a response from the server,
152
+ and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
153
+ it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
154
+ """
155
+ super().__init__(timeout)
156
+
157
+
158
+ class ClusterBatchOptions(BaseBatchOptions):
159
+ """
160
+ Options for cluster batch operations.
161
+
162
+ Args:
163
+ timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
164
+ to complete. This duration encompasses sending the request, awaiting a response from the server,
165
+ and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
166
+ it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
167
+
168
+ route (Optional[TSingleNodeRoute]): Configures single-node routing for the batch request. The client
169
+ will send the batch to the specified node defined by `route`.
170
+
171
+ If a redirection error occurs:
172
+
173
+ - For Atomic Batches (Transactions), the entire transaction will be redirected.
174
+ - For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors
175
+ will be redirected.
176
+
177
+ retry_strategy (Optional[BatchRetryStrategy]): ⚠️ **Please see `BatchRetryStrategy` and read carefully before enabling these
178
+ options.**
179
+
180
+ Defines the retry strategy for handling cluster batch request failures.
181
+
182
+ This strategy determines whether failed commands should be retried, potentially impacting
183
+ execution order.
184
+
185
+ - If `retry_server_error` is `True`, retriable errors (e.g., TRYAGAIN) will
186
+ trigger a retry.
187
+ - If `retry_connection_error` is `True`, connection failures will trigger a
188
+ retry.
189
+
190
+ **Warnings:**
191
+
192
+ - Retrying server errors may cause commands targeting the same slot to execute out of
193
+ order.
194
+ - Retrying connection errors may lead to duplicate executions, as it is unclear which
195
+ commands have already been processed.
196
+
197
+ **Note:** Currently, retry strategies are supported only for non-atomic batches.
198
+
199
+ **Recommendation:** It is recommended to increase the timeout in `timeout`
200
+ when enabling these strategies.
201
+
202
+ **Default:** Both `retry_server_error` and `retry_connection_error` are set to
203
+ `False`.
204
+
205
+ """
206
+
207
+ def __init__(
208
+ self,
209
+ timeout: Optional[int] = None,
210
+ route: Optional[TSingleNodeRoute] = None,
211
+ retry_strategy: Optional[BatchRetryStrategy] = None,
212
+ ):
213
+ """
214
+ Initialize ClusterBatchOptions.
215
+
216
+ Args:
217
+ timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
218
+ to complete. This duration encompasses sending the request, awaiting a response from the server,
219
+ and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
220
+ it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
221
+
222
+ route (Optional[TSingleNodeRoute]): Configures single-node routing for the batch request. The client
223
+ will send the batch to the specified node defined by `route`.
224
+
225
+ If a redirection error occurs:
226
+
227
+ - For Atomic Batches (Transactions), the entire transaction will be redirected.
228
+ - For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors
229
+ will be redirected.
230
+
231
+ retry_strategy (Optional[BatchRetryStrategy]): ⚠️ **Please see `BatchRetryStrategy` and read carefully before enabling these
232
+ options.**
233
+
234
+ Defines the retry strategy for handling cluster batch request failures.
235
+
236
+ This strategy determines whether failed commands should be retried, potentially impacting
237
+ execution order.
238
+
239
+ - If `retry_server_error` is `True`, retriable errors (e.g., TRYAGAIN) will
240
+ trigger a retry.
241
+ - If `retry_connection_error` is `True`, connection failures will trigger a
242
+ retry.
243
+
244
+ **Warnings:**
245
+
246
+ - Retrying server errors may cause commands targeting the same slot to execute out of
247
+ order.
248
+ - Retrying connection errors may lead to duplicate executions, as it is unclear which
249
+ commands have already been processed.
250
+
251
+ **Note:** Currently, retry strategies are supported only for non-atomic batches.
252
+
253
+ **Recommendation:** It is recommended to increase the timeout in `timeout`
254
+ when enabling these strategies.
255
+
256
+ **Default:** Both `retry_server_error` and `retry_connection_error` are set to
257
+ `False`.
258
+ """
259
+ super().__init__(timeout)
260
+ self.retry_strategy = retry_strategy
261
+ self.route = route
@@ -0,0 +1,407 @@
1
+ # Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
2
+ from dataclasses import dataclass
3
+ from datetime import datetime, timedelta
4
+ from enum import Enum
5
+ from typing import List, Optional, Type, Union, get_args
6
+
7
+ from glide_shared.commands.command_args import Limit, OrderBy
8
+ from glide_shared.constants import TEncodable
9
+
10
+
11
+ @dataclass
12
+ class PubSubMsg:
13
+ """
14
+ Describes the incoming pubsub message
15
+
16
+ Attributes:
17
+ message (TEncodable): Incoming message.
18
+ channel (TEncodable): Name of an channel that triggered the message.
19
+ pattern (Optional[TEncodable]): Pattern that triggered the message.
20
+ """
21
+
22
+ message: TEncodable
23
+ channel: TEncodable
24
+ pattern: Optional[TEncodable]
25
+
26
+
27
+ class ConditionalChange(Enum):
28
+ """
29
+ A condition to the `SET`, `ZADD` and `GEOADD` commands.
30
+ """
31
+
32
+ ONLY_IF_EXISTS = "XX"
33
+ """ Only update key / elements that already exist. Equivalent to `XX` in the Valkey API. """
34
+
35
+ ONLY_IF_DOES_NOT_EXIST = "NX"
36
+ """ Only set key / add elements that does not already exist. Equivalent to `NX` in the Valkey API. """
37
+
38
+
39
+ class HashFieldConditionalChange(Enum):
40
+ """
41
+ Field conditional change options for HSETEX command.
42
+ """
43
+
44
+ ONLY_IF_ALL_EXIST = "FXX"
45
+ """ Only set fields if all of them already exist. Equivalent to `FXX` in the Valkey API. """
46
+
47
+ ONLY_IF_NONE_EXIST = "FNX"
48
+ """ Only set fields if none of them already exist. Equivalent to `FNX` in the Valkey API. """
49
+
50
+
51
+ @dataclass
52
+ class OnlyIfEqual:
53
+ """
54
+ Change condition to the `SET` command,
55
+ For additional conditonal options see ConditionalChange
56
+
57
+ - comparison_value - value to compare to the current value of a key.
58
+
59
+ If comparison_value is equal to the key, it will overwrite the value of key to the new provided value
60
+ Equivalent to the IFEQ comparison-value in the Valkey API
61
+ """
62
+
63
+ comparison_value: TEncodable
64
+
65
+
66
+ class ExpiryType(Enum):
67
+ """
68
+ SET option: The type of the expiry.
69
+ """
70
+
71
+ SEC = 0, Union[int, timedelta]
72
+ """
73
+ Set the specified expire time, in seconds. Equivalent to `EX` in the Valkey API.
74
+ """
75
+
76
+ MILLSEC = 1, Union[int, timedelta]
77
+ """
78
+ Set the specified expire time, in milliseconds. Equivalent to `PX` in the Valkey API.
79
+ """
80
+
81
+ UNIX_SEC = 2, Union[int, datetime]
82
+ """
83
+ Set the specified Unix time at which the key will expire, in seconds. Equivalent to `EXAT` in the Valkey API.
84
+ """
85
+
86
+ UNIX_MILLSEC = 3, Union[int, datetime]
87
+ """
88
+ Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to `PXAT` in the Valkey API.
89
+ """
90
+
91
+ KEEP_TTL = 4, Type[None]
92
+ """
93
+ Retain the time to live associated with the key. Equivalent to `KEEPTTL` in the Valkey API.
94
+ """
95
+
96
+
97
+ class ExpiryTypeGetEx(Enum):
98
+ """
99
+ GetEx option: The type of the expiry.
100
+ """
101
+
102
+ SEC = 0, Union[int, timedelta]
103
+ """ Set the specified expire time, in seconds. Equivalent to `EX` in the Valkey API. """
104
+
105
+ MILLSEC = 1, Union[int, timedelta]
106
+ """ Set the specified expire time, in milliseconds. Equivalent to `PX` in the Valkey API. """
107
+
108
+ UNIX_SEC = 2, Union[int, datetime]
109
+ """ Set the specified Unix time at which the key will expire, in seconds. Equivalent to `EXAT` in the Valkey API. """
110
+
111
+ UNIX_MILLSEC = 3, Union[int, datetime]
112
+ """ Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to `PXAT` in the Valkey API. """
113
+
114
+ PERSIST = 4, Type[None]
115
+ """ Remove the time to live associated with the key. Equivalent to `PERSIST` in the Valkey API. """
116
+
117
+
118
+ class InfoSection(Enum):
119
+ """
120
+ INFO option: a specific section of information:
121
+
122
+ When no parameter is provided, the default option is assumed.
123
+ """
124
+
125
+ SERVER = "server"
126
+ """ General information about the server """
127
+
128
+ CLIENTS = "clients"
129
+ """ Client connections section """
130
+
131
+ MEMORY = "memory"
132
+ """ Memory consumption related information """
133
+
134
+ PERSISTENCE = "persistence"
135
+ """ RDB and AOF related information """
136
+
137
+ STATS = "stats"
138
+ """ General statistics """
139
+
140
+ REPLICATION = "replication"
141
+ """ Master/replica replication information """
142
+
143
+ CPU = "cpu"
144
+ """ CPU consumption statistics """
145
+
146
+ COMMAND_STATS = "commandstats"
147
+ """ Valkey command statistics """
148
+
149
+ LATENCY_STATS = "latencystats"
150
+ """ Valkey command latency percentile distribution statistics """
151
+
152
+ SENTINEL = "sentinel"
153
+ """ Valkey Sentinel section (only applicable to Sentinel instances) """
154
+
155
+ CLUSTER = "cluster"
156
+ """ Valkey Cluster section """
157
+
158
+ MODULES = "modules"
159
+ """ Modules section """
160
+
161
+ KEYSPACE = "keyspace"
162
+ """ Database related statistics """
163
+
164
+ ERROR_STATS = "errorstats"
165
+ """ Valkey error statistics """
166
+
167
+ ALL = "all"
168
+ """ Return all sections (excluding module generated ones) """
169
+
170
+ DEFAULT = "default"
171
+ """ Return only the default set of sections """
172
+
173
+ EVERYTHING = "everything"
174
+ """ Includes all and modules """
175
+
176
+
177
+ class ExpireOptions(Enum):
178
+ """
179
+ EXPIRE option: options for setting key expiry.
180
+ """
181
+
182
+ HasNoExpiry = "NX"
183
+ """ Set expiry only when the key has no expiry (Equivalent to "NX" in Valkey). """
184
+
185
+ HasExistingExpiry = "XX"
186
+ """ Set expiry only when the key has an existing expiry (Equivalent to "XX" in Valkey). """
187
+
188
+ NewExpiryGreaterThanCurrent = "GT"
189
+ """
190
+ Set expiry only when the new expiry is greater than the current one (Equivalent to "GT" in Valkey).
191
+ """
192
+
193
+ NewExpiryLessThanCurrent = "LT"
194
+ """
195
+ Set expiry only when the new expiry is less than the current one (Equivalent to "LT" in Valkey).
196
+ """
197
+
198
+
199
+ class UpdateOptions(Enum):
200
+ """
201
+ Options for updating elements of a sorted set key.
202
+ """
203
+
204
+ LESS_THAN = "LT"
205
+ """ Only update existing elements if the new score is less than the current score. """
206
+
207
+ GREATER_THAN = "GT"
208
+ """ Only update existing elements if the new score is greater than the current score. """
209
+
210
+
211
+ class ExpirySet:
212
+ """
213
+ SET option: Represents the expiry type and value to be executed with "SET" command.
214
+
215
+ Attributes:
216
+ cmd_arg (str): The expiry type.
217
+ value (str): The value for the expiry type.
218
+ """
219
+
220
+ def __init__(
221
+ self,
222
+ expiry_type: ExpiryType,
223
+ value: Optional[Union[int, datetime, timedelta]],
224
+ ) -> None:
225
+ self.set_expiry_type_and_value(expiry_type, value)
226
+
227
+ def __eq__(self, other: "object") -> bool:
228
+ if not isinstance(other, ExpirySet):
229
+ return NotImplemented
230
+ return self.expiry_type == other.expiry_type and self.value == other.value
231
+
232
+ def set_expiry_type_and_value(
233
+ self, expiry_type: ExpiryType, value: Optional[Union[int, datetime, timedelta]]
234
+ ):
235
+ """
236
+ Args:
237
+ expiry_type (ExpiryType): The expiry type.
238
+ value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
239
+ determines the type of expiration value:
240
+
241
+ - SEC: Union[int, timedelta]
242
+ - MILLSEC: Union[int, timedelta]
243
+ - UNIX_SEC: Union[int, datetime]
244
+ - UNIX_MILLSEC: Union[int, datetime]
245
+ - KEEP_TTL: Type[None]
246
+ """
247
+ if not isinstance(value, get_args(expiry_type.value[1])):
248
+ raise ValueError(
249
+ f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
250
+ )
251
+ self.expiry_type = expiry_type
252
+ if self.expiry_type == ExpiryType.SEC:
253
+ self.cmd_arg = "EX"
254
+ if isinstance(value, timedelta):
255
+ value = int(value.total_seconds())
256
+ elif self.expiry_type == ExpiryType.MILLSEC:
257
+ self.cmd_arg = "PX"
258
+ if isinstance(value, timedelta):
259
+ value = int(value.total_seconds() * 1000)
260
+ elif self.expiry_type == ExpiryType.UNIX_SEC:
261
+ self.cmd_arg = "EXAT"
262
+ if isinstance(value, datetime):
263
+ value = int(value.timestamp())
264
+ elif self.expiry_type == ExpiryType.UNIX_MILLSEC:
265
+ self.cmd_arg = "PXAT"
266
+ if isinstance(value, datetime):
267
+ value = int(value.timestamp() * 1000)
268
+ elif self.expiry_type == ExpiryType.KEEP_TTL:
269
+ self.cmd_arg = "KEEPTTL"
270
+ self.value = str(value) if value else None
271
+
272
+ def get_cmd_args(self) -> List[str]:
273
+ return [self.cmd_arg] if self.value is None else [self.cmd_arg, self.value]
274
+
275
+
276
+ class ExpiryGetEx:
277
+ """
278
+ GetEx option: Represents the expiry type and value to be executed with "GetEx" command.
279
+
280
+ Attributes:
281
+ cmd_arg (str): The expiry type.
282
+ value (str): The value for the expiry type.
283
+ """
284
+
285
+ def __init__(
286
+ self,
287
+ expiry_type: ExpiryTypeGetEx,
288
+ value: Optional[Union[int, datetime, timedelta]],
289
+ ) -> None:
290
+ self.set_expiry_type_and_value(expiry_type, value)
291
+
292
+ def set_expiry_type_and_value(
293
+ self,
294
+ expiry_type: ExpiryTypeGetEx,
295
+ value: Optional[Union[int, datetime, timedelta]],
296
+ ):
297
+ """
298
+ Args:
299
+ expiry_type (ExpiryType): The expiry type.
300
+ value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
301
+ determines the type of expiration value:
302
+
303
+ - SEC: Union[int, timedelta]
304
+ - MILLSEC: Union[int, timedelta]
305
+ - UNIX_SEC: Union[int, datetime]
306
+ - UNIX_MILLSEC: Union[int, datetime]
307
+ - PERSIST: Type[None]
308
+ """
309
+ if not isinstance(value, get_args(expiry_type.value[1])):
310
+ raise ValueError(
311
+ f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
312
+ )
313
+ self.expiry_type = expiry_type
314
+ if self.expiry_type == ExpiryTypeGetEx.SEC:
315
+ self.cmd_arg = "EX"
316
+ if isinstance(value, timedelta):
317
+ value = int(value.total_seconds())
318
+ elif self.expiry_type == ExpiryTypeGetEx.MILLSEC:
319
+ self.cmd_arg = "PX"
320
+ if isinstance(value, timedelta):
321
+ value = int(value.total_seconds() * 1000)
322
+ elif self.expiry_type == ExpiryTypeGetEx.UNIX_SEC:
323
+ self.cmd_arg = "EXAT"
324
+ if isinstance(value, datetime):
325
+ value = int(value.timestamp())
326
+ elif self.expiry_type == ExpiryTypeGetEx.UNIX_MILLSEC:
327
+ self.cmd_arg = "PXAT"
328
+ if isinstance(value, datetime):
329
+ value = int(value.timestamp() * 1000)
330
+ elif self.expiry_type == ExpiryTypeGetEx.PERSIST:
331
+ self.cmd_arg = "PERSIST"
332
+ self.value = str(value) if value else None
333
+
334
+ def get_cmd_args(self) -> List[str]:
335
+ return [self.cmd_arg] if self.value is None else [self.cmd_arg, self.value]
336
+
337
+
338
+ class InsertPosition(Enum):
339
+ BEFORE = "BEFORE"
340
+ AFTER = "AFTER"
341
+
342
+
343
+ class FlushMode(Enum):
344
+ """
345
+ Defines flushing mode for:
346
+
347
+ `FLUSHALL` command and `FUNCTION FLUSH` command.
348
+
349
+ See [FLUSHAL](https://valkey.io/commands/flushall/) and [FUNCTION-FLUSH](https://valkey.io/commands/function-flush/)
350
+ for details
351
+
352
+ SYNC was introduced in version 6.2.0.
353
+ """
354
+
355
+ ASYNC = "ASYNC"
356
+ SYNC = "SYNC"
357
+
358
+
359
+ class FunctionRestorePolicy(Enum):
360
+ """
361
+ Options for the FUNCTION RESTORE command.
362
+ """
363
+
364
+ APPEND = "APPEND"
365
+ """ Appends the restored libraries to the existing libraries and aborts on collision. This is the default policy. """
366
+
367
+ FLUSH = "FLUSH"
368
+ """ Deletes all existing libraries before restoring the payload. """
369
+
370
+ REPLACE = "REPLACE"
371
+ """
372
+ Appends the restored libraries to the existing libraries, replacing any existing ones in case
373
+ of name collisions. Note that this policy doesn't prevent function name collisions, only libraries.
374
+ """
375
+
376
+
377
+ def _build_sort_args(
378
+ key: TEncodable,
379
+ by_pattern: Optional[TEncodable] = None,
380
+ limit: Optional[Limit] = None,
381
+ get_patterns: Optional[List[TEncodable]] = None,
382
+ order: Optional[OrderBy] = None,
383
+ alpha: Optional[bool] = None,
384
+ store: Optional[TEncodable] = None,
385
+ ) -> List[TEncodable]:
386
+ args = [key]
387
+
388
+ if by_pattern:
389
+ args.extend(["BY", by_pattern])
390
+
391
+ if limit:
392
+ args.extend(["LIMIT", str(limit.offset), str(limit.count)])
393
+
394
+ if get_patterns:
395
+ for pattern in get_patterns:
396
+ args.extend(["GET", pattern])
397
+
398
+ if order:
399
+ args.append(order.value)
400
+
401
+ if alpha:
402
+ args.append("ALPHA")
403
+
404
+ if store:
405
+ args.extend(["STORE", store])
406
+
407
+ return args
@@ -2,11 +2,11 @@
2
2
  from abc import ABC, abstractmethod
3
3
  from typing import List, Mapping, Optional
4
4
 
5
- from glide.async_commands.command_args import OrderBy
6
- from glide.async_commands.server_modules.ft_options.ft_constants import (
5
+ from glide_shared.commands.command_args import OrderBy
6
+ from glide_shared.commands.server_modules.ft_options.ft_constants import (
7
7
  FtAggregateKeywords,
8
8
  )
9
- from glide.constants import TEncodable
9
+ from glide_shared.constants import TEncodable
10
10
 
11
11
 
12
12
  class FtAggregateClause(ABC):
@@ -3,8 +3,10 @@ from abc import ABC, abstractmethod
3
3
  from enum import Enum
4
4
  from typing import List, Optional
5
5
 
6
- from glide.async_commands.server_modules.ft_options.ft_constants import FtCreateKeywords
7
- from glide.constants import TEncodable
6
+ from glide_shared.commands.server_modules.ft_options.ft_constants import (
7
+ FtCreateKeywords,
8
+ )
9
+ from glide_shared.constants import TEncodable
8
10
 
9
11
 
10
12
  class FieldType(Enum):