668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
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
866
867
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
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 | class BaseClient(CoreCommands):
# Class default: ClientPool builds its adapters without __init__ and owns their lifetime.
_core_client_finalizer: Optional["weakref.finalize"] = None
def __init__(self, config: BaseClientConfiguration):
"""To create a new client, use the `create` classmethod"""
if getattr(config, "rdma", None) is not None:
raise ConfigurationError(
"RDMA is only available on the synchronous client; create a "
"glide_sync client to use RdmaConfiguration"
)
_glide_ffi = _ASYNC_FFI
self._ffi = _glide_ffi.ffi
self._lib = _glide_ffi.lib
self.config: BaseClientConfiguration = config
self._is_closed: bool = False
self._core_client = None
self._conn_req_bytes: bytes = b""
self._pubsub_callback_ref = None
self._loop: Optional[asyncio.AbstractEventLoop] = None # set in create()
self._pending_futures: Dict[int, "TFuture"] = {}
self._callback_id_gen = itertools.count(1)
self._lock = threading.Lock()
self._address_resolver_callback_ref = None
self._credential_provider_callback_ref = None
self._credential_provider_callback_owner = None
self._pubsub_futures: List["TFuture"] = []
self._pubsub_lock = threading.Lock()
self._pending_push_notifications: List[PubSubMsg] = []
self._pipe_client_id: int = 0
self._create_pid: int = 0
self._is_asyncio: bool = True
@classmethod
async def create(cls, config: BaseClientConfiguration) -> Self:
"""Creates a Glide client.
Args:
config (ClientConfiguration): The configuration options for the client.
Returns:
Self: A promise that resolves to a connected client instance.
"""
self = cls(config)
try:
self._is_asyncio = sniffio.current_async_library() == "asyncio"
except sniffio.AsyncLibraryNotFoundError:
self._is_asyncio = True
self._loop = asyncio.get_running_loop() if self._is_asyncio else None
# Build connection request
conn_req = _create_async_connection_request(config)
conn_req_bytes = conn_req.SerializeToString()
# Store for scoped_connection
self._conn_req_bytes = conn_req_bytes
# Create AsyncClient type
client_type = self._ffi.new(
"ClientType*",
{
"_type": self._ffi.cast("ClientTypeEnum", FFIClientTypeEnum.Async),
"async_client": {
"success_callback": self._lib.noop_success_callback,
"failure_callback": self._lib.noop_failure_callback,
"allow_stack_response": False,
},
},
)
# Pubsub messages are delivered via the shared pipe — no callback needed.
pubsub_callback = self._ffi.cast("PubSubCallback", 0)
# Create address resolver callback if configured
from glide_shared.ffi_helpers import create_address_resolver_callback
address_resolver_callback = create_address_resolver_callback(
self._ffi, self.config.address_resolver
)
if self.config.address_resolver is not None:
self._address_resolver_callback_ref = address_resolver_callback
# Record the creation process before entering provider-backed native creation.
self._create_pid = os.getpid()
iam_config = (
self.config.credentials.iam_config
if self.config.credentials is not None
else None
)
credential_provider = (
iam_config.credential_provider if iam_config is not None else None
)
if credential_provider is None:
self._pipe_client_id = self._lib.glide_allocate_client_id()
client_response_ptr = self._lib.create_client(
conn_req_bytes,
len(conn_req_bytes),
client_type,
pubsub_callback,
address_resolver_callback,
self._pipe_client_id,
)
ClientLogger.log(
LogLevel.INFO, "connection info", "new connection established"
)
if client_response_ptr == self._ffi.NULL:
raise ClosingError("Failed to create client, response pointer is NULL.")
client_response = self._ffi.cast("ConnectionResponse*", client_response_ptr)
if client_response.conn_ptr != self._ffi.NULL:
self._core_client = client_response.conn_ptr
else:
error_msg = (
self._ffi.string(client_response.connection_error_message).decode(
ENCODING
)
if client_response.connection_error_message != self._ffi.NULL
else "Unknown error"
)
error_class = get_connection_error_class(
client_response.connection_error_type
)
self._lib.free_connection_response(client_response_ptr)
raise error_class(error_msg)
self._lib.free_connection_response(client_response_ptr)
else:
import anyio
trio_token = None
if not self._is_asyncio:
import trio
trio_token = trio.lowlevel.current_trio_token()
credential_callback, credential_owner = create_credential_provider_callback(
self._ffi,
credential_provider,
event_loop=self._loop,
trio_token=trio_token,
allow_async=True,
provider_owner=self,
)
# The C ABI has one client_id baton for provider callbacks and async
# pipe routing, so provider-backed async clients use their reserved
# high-half provider ID for both roles.
self._pipe_client_id = credential_owner.callback_id
state = _ProviderNativeCreate(
self._ffi,
self._lib,
(
conn_req_bytes,
len(conn_req_bytes),
client_type,
pubsub_callback,
address_resolver_callback,
self._pipe_client_id,
credential_callback,
),
)
try:
await anyio.to_thread.run_sync(state._run, abandon_on_cancel=True)
core_client = state._adopt()
with self._lock:
if self._is_closed:
adopt_client = False
else:
self._core_client = core_client
self._credential_provider_callback_ref = credential_callback
self._credential_provider_callback_owner = credential_owner
adopt_client = True
if not adopt_client:
self._lib.close_client(core_client)
raise ClosingError("Client was closed during native creation.")
except BaseException:
state._abandon()
credential_owner.close()
raise
ClientLogger.log(
LogLevel.INFO, "connection info", "new connection established"
)
# Close the connection if the client is dropped without close(); holds no ref to self.
self._core_client_finalizer = weakref.finalize(
self, _release_core_client, self._lib, self._core_client, self._create_pid
)
# typeshed gives finalize empty __slots__; atexit is settable at runtime.
self._core_client_finalizer.atexit = False # type: ignore[misc]
self._setup_pipe_after_creation(credential_provider is not None)
return self
def _setup_pipe_after_creation(self, provider_backed: bool) -> None:
"""Set up delivery and roll back only provider-backed direct failures."""
try:
pipe_setup_error = self._setup_pipe()
if provider_backed and pipe_setup_error is not None:
raise pipe_setup_error
except BaseException:
if provider_backed:
self._cleanup_provider_after_setup_failure()
raise
def _cleanup_provider_after_setup_failure(self) -> None:
"""Release a provider-backed direct client after final pipe setup fails."""
_client_registry.pop(self._pipe_client_id, None)
with self._lock:
self._is_closed = True
core_client, self._core_client = self._core_client, None
owner = self._credential_provider_callback_owner
self._credential_provider_callback_owner = None
self._credential_provider_callback_ref = None
if self._core_client_finalizer is not None:
self._core_client_finalizer.detach()
if core_client is not None and self._create_pid == os.getpid():
self._lib.close_client(core_client)
if owner is not None:
owner.close()
def _setup_pipe(self) -> Optional[OSError]:
"""Initialize and register the shared response pipe."""
global _async_pipe_read_fd, _async_pipe_write_fd
global _async_pipe_registered, _async_pipe_loop
global _pipe_remainder, _trio_pipe_token, _async_pipe_init_pid
pipe_setup_error = None
# Identify the current trio.run() up front (outside the lock). The
# token uniquely names this run, so it both makes registration
# idempotent within a run and tells a fresh run that a prior run's
# registration is stale.
trio_token = None
if not self._is_asyncio:
import trio
trio_token = trio.lowlevel.current_trio_token()
with _async_pipe_lock:
_detect_fork_and_reset()
current_pid = os.getpid()
if _async_pipe_read_fd < 0:
created_read_fd = -1
created_write_fd = -1
try:
created_read_fd, created_write_fd = os.pipe()
os.set_blocking(created_read_fd, False)
if _async_pipe_init_pid > 0 and current_pid != _async_pipe_init_pid:
self._lib.reinit_async_pipe(created_write_fd)
else:
self._lib.init_async_pipe(created_write_fd)
_async_pipe_read_fd = created_read_fd
_async_pipe_write_fd = created_write_fd
_async_pipe_init_pid = current_pid
except OSError as error:
_close_file_descriptors(created_read_fd, created_write_fd)
_async_pipe_read_fd = -1
_async_pipe_write_fd = -1
_async_pipe_init_pid = 0
self._pipe_client_id = 0
pipe_setup_error = error
# Detect stale registration: the loop that originally called
# add_reader has been closed/destroyed (e.g. between anyio.run()
# calls in benchmarks). Reset so we re-register below.
if _async_pipe_registered and _async_pipe_loop is not None:
if _async_pipe_loop.is_closed():
_async_pipe_registered = False
_async_pipe_loop = None
_pipe_remainder = b""
_drain_stale_pipe_frames()
# Trio: registration belongs to exactly one trio.run(). If the
# recorded token differs from this run's, the previous run's reader
# is gone (trio.run() cancels its system tasks before returning), so
# re-register for this run. Keying on the token instead of a
# lazily-set liveness flag prevents a second client in the same run
# from spawning a duplicate reader on the shared fd, which is what
# triggered BusyResourceError.
if (
not self._is_asyncio
and _async_pipe_registered
and _async_pipe_loop is None
and _trio_pipe_token is not trio_token
):
_async_pipe_registered = False
_trio_pipe_token = None
_pipe_remainder = b""
_drain_stale_pipe_frames()
if _async_pipe_read_fd >= 0 and self._pipe_client_id:
_client_registry[self._pipe_client_id] = self
if not _async_pipe_registered:
if self._is_asyncio:
assert self._loop is not None
self._loop.add_reader(
_async_pipe_read_fd, _on_async_pipe_readable
)
_async_pipe_loop = self._loop
else:
# For trio: spawn a background task that polls the pipe.
# Record the token before spawning (still under the
# lock) so a concurrent _setup_pipe in this same run
# sees us as registered and does not spawn a second
# reader on the same fd.
import trio
_trio_pipe_token = trio_token
trio.lowlevel.spawn_system_task(
_trio_pipe_reader, _async_pipe_read_fd, trio_token
)
_async_pipe_registered = True
return pipe_setup_error
# ==================== Callback Handling ====================
def _get_callback_id(self) -> int:
return next(self._callback_id_gen)
def _register_future(self, callback_id: int, fut: "TFuture") -> None:
"""Register a pending future (thread-safe for free-threading)."""
if _FREE_THREADED:
with self._lock:
self._pending_futures[callback_id] = fut
else:
self._pending_futures[callback_id] = fut
def _replace_pending_future(
self, callback_id: int, expected: "TFuture", replacement: Any
) -> None:
"""The pipe reader may already have popped and resolved this entry;
swapping only while it is still ``expected`` leaves that result where
its awaiter will find it. ``None`` removes the entry."""
lock = self._lock if _FREE_THREADED else contextlib.nullcontext()
with lock:
if self._pending_futures.get(callback_id) is not expected:
return
if replacement is None:
del self._pending_futures[callback_id]
else:
self._pending_futures[callback_id] = replacement
def _complete_pubsub_futures_safe(self):
"""Complete pending pubsub futures with available messages. Must hold _pubsub_lock."""
loop = self._loop
while self._pending_push_notifications and self._pubsub_futures:
fut = self._pubsub_futures[0]
if fut.done():
self._pubsub_futures.pop(0)
continue
msg = self._pending_push_notifications.pop(0)
self._pubsub_futures.pop(0)
if isinstance(fut, _CompatFuture):
fut.set_result(msg)
elif loop and not loop.is_closed():
loop.call_soon_threadsafe(fut.set_result, msg)
async def get_pubsub_message(self) -> PubSubMsg:
if self._is_closed:
raise ClosingError("Client is closed.")
self._check_same_process()
if self.config._get_pubsub_callback_and_context()[0] is not None:
raise ConfigurationError(
"The operation will never complete since messages will be passed to the configured callback."
)
fut: "TFuture" = _get_new_future_instance()
with self._pubsub_lock:
self._pubsub_futures.append(fut)
self._complete_pubsub_futures_safe()
return await fut
def try_get_pubsub_message(self) -> Optional[PubSubMsg]:
if self._is_closed:
raise ClosingError("Client is closed.")
self._check_same_process()
if self.config._get_pubsub_callback_and_context()[0] is not None:
raise ConfigurationError(
"The operation will never complete since messages will be passed to the configured callback."
)
with self._pubsub_lock:
if self._pending_push_notifications:
return self._pending_push_notifications.pop(0)
return None
# ==================== Response Parsing ====================
def _handle_response(self, message):
"""Parse a CommandResponse pointer into a Python object.
For the async client, NULL means no response (returns None) and the arena
is freed here since responses arrive via the pipe path without automatic
cleanup. The sync client's _handle_response raises on NULL and relies on
free_command_result to free the arena.
"""
if message == self._ffi.NULL:
return None
addr = int(self._ffi.cast("uintptr_t", message))
result, _arena_ptr = _c_parse_response(addr)
# Arena is freed by the caller (free_command_result for sync path,
# explicit free_response_arena for pipe path)
return result
# ==================== FFI Helpers ====================
def _to_c_strings(self, args):
return to_c_strings(self._ffi, args)
def _to_c_route_ptr_and_len(self, route):
return to_c_route_ptr_and_len(self._ffi, route)
# ==================== Command Execution ====================
def _check_same_process(self) -> None:
"""Raise if this client is used from a forked child process."""
if self._create_pid and self._create_pid != os.getpid():
raise ClosingError(
"Cannot use a client created before fork(). "
"Create a new client in the child process."
)
async def _execute_command(
self,
request_type: int,
args: List[TEncodable],
route: Optional[Route] = None,
) -> TResult:
if self._is_closed:
raise ClosingError(
"Unable to execute requests; the client is closed. Please create a new client."
)
self._check_same_process()
callback_id = self._get_callback_id()
fut = _get_new_future_instance()
self._register_future(callback_id, fut)
c_args, c_lengths, buffers = self._to_c_strings(args)
# Sample before reading the caller's context. A sampled command span uses
# the active OTel span as its parent when one is available.
span = 0
if OpenTelemetry.is_tracing_enabled() and OpenTelemetry.should_sample():
parent_ctx = OpenTelemetry._get_parent_span_context()
span_name_cstr = self._ffi.new(
"char[]", RequestType.Name(request_type).encode()
)
span = _create_command_span(
self._ffi, self._lib, span_name_cstr, parent_ctx
)
try:
if route is None:
self._lib.command(
self._core_client,
callback_id,
request_type,
len(args),
c_args,
c_lengths,
self._ffi.NULL,
0,
span,
)
else:
route_ptr, route_len, route_bytes = self._to_c_route_ptr_and_len(route)
self._lib.command(
self._core_client,
callback_id,
request_type,
len(args),
c_args,
c_lengths,
route_ptr,
route_len,
span,
)
return await fut
finally:
if span:
self._lib.drop_otel_span(span)
async def _execute_batch(
self,
commands: List[Tuple[int, List[TEncodable]]],
is_atomic: bool,
raise_on_error: bool = False,
retry_server_error: bool = False,
retry_connection_error: bool = False,
route: Optional[Route] = None,
timeout: Optional[int] = None,
) -> List[TResult]:
if self._is_closed:
raise ClosingError(
"Unable to execute requests; the client is closed. Please create a new client."
)
self._check_same_process()
callback_id = self._get_callback_id()
fut = _get_new_future_instance()
self._register_future(callback_id, fut)
span = 0
if OpenTelemetry.is_tracing_enabled() and OpenTelemetry.should_sample():
parent_ctx = OpenTelemetry._get_parent_span_context()
span = _create_batch_span(self._ffi, self._lib, parent_ctx)
try:
batch_info, batch_refs = convert_commands_to_c_batch_info(
self._ffi, commands, is_atomic
)
batch_options, opts_refs = create_c_batch_options(
self._ffi,
route,
retry_server_error=retry_server_error,
retry_connection_error=retry_connection_error,
timeout=timeout,
)
_refs = batch_refs + opts_refs # noqa: F841 prevent GC
self._lib.batch(
self._core_client,
callback_id,
batch_info,
raise_on_error,
batch_options,
span,
)
return await fut
finally:
if span != 0:
self._lib.drop_otel_span(span)
async def _execute_script(
self,
hash: str,
keys: Optional[List[TEncodable]] = None,
args: Optional[List[TEncodable]] = None,
route: Optional[Route] = None,
) -> TResult:
if self._is_closed:
raise ClosingError(
"Unable to execute requests; the client is closed. Please create a new client."
)
self._check_same_process()
callback_id = self._get_callback_id()
fut = _get_new_future_instance()
self._register_future(callback_id, fut)
if keys is None:
keys = []
if args is None:
args = []
keys_c_args, keys_c_lengths, keys_buffers = self._to_c_strings(keys)
args_c_args, args_c_lengths, args_buffers = self._to_c_strings(args)
hash_bytes = hash.encode(ENCODING) + b"\0"
hash_buffer = self._ffi.from_buffer(hash_bytes)
route_ptr, route_len, route_bytes = self._to_c_route_ptr_and_len(route)
# OTel span creation only when initialized (rare). The core attaches the
# EVALSHA DB semantic convention attributes to the span via invoke_script.
span = 0
if OpenTelemetry.is_tracing_enabled() and OpenTelemetry.should_sample():
parent_ctx = OpenTelemetry._get_parent_span_context()
span = _create_command_span(
self._ffi, self._lib, _EVALSHA_SPAN_NAME, parent_ctx
)
try:
self._lib.invoke_script(
self._core_client,
callback_id,
hash_buffer,
len(keys),
keys_c_args,
keys_c_lengths,
len(args),
args_c_args,
args_c_lengths,
route_ptr,
route_len,
span,
)
return await fut
finally:
if span != 0:
self._lib.drop_otel_span(span)
# ==================== Cache Metrics ====================
def _get_cache_metrics(self, metrics_type: int) -> "TResult":
"""
Get cache metrics via FFI.
Args:
metrics_type: Type of metric to retrieve.
Returns:
The requested cache metric.
Raises:
RequestError: If client-side caching is not enabled or metrics tracking is disabled.
"""
if self._is_closed:
raise ClosingError("Client is closed.")
self._check_same_process()
if self._core_client == self._ffi.NULL:
raise ValueError("Invalid client pointer.")
from glide_shared.ffi_helpers import handle_command_result
command_result = self._lib.get_cache_metrics(self._core_client, 0, metrics_type)
return handle_command_result(
self._ffi, self._lib, command_result, self._handle_response
)
# ==================== Connection Management ====================
async def _update_connection_password(
self, password: Optional[str], immediate_auth: bool
) -> TResult:
if self._is_closed:
raise ClosingError("Client is closed.")
self._check_same_process()
callback_id = self._get_callback_id()
fut = _get_new_future_instance()
self._register_future(callback_id, fut)
c_password = (
self._ffi.new("char[]", password.encode(ENCODING))
if password is not None
else self._ffi.new("char[]", b"")
)
self._lib.update_connection_password(
self._core_client,
callback_id,
c_password,
immediate_auth,
)
result = await fut
if result is OK:
if self.config.credentials is None:
self.config.credentials = ServerCredentials(password=password or "")
self.config.credentials.password = password or ""
return result
async def _refresh_iam_token(self) -> TResult:
if self._is_closed:
raise ClosingError("Client is closed.")
self._check_same_process()
callback_id = self._get_callback_id()
fut = _get_new_future_instance()
self._register_future(callback_id, fut)
self._lib.refresh_iam_token(
self._core_client,
callback_id,
)
return await fut
async def get_statistics(self) -> dict:
stats = self._lib.get_statistics()
return {
"total_connections": stats.total_connections,
"total_clients": stats.total_clients,
"total_values_compressed": stats.total_values_compressed,
"total_values_decompressed": stats.total_values_decompressed,
"total_original_bytes": stats.total_original_bytes,
"total_bytes_compressed": stats.total_bytes_compressed,
"total_bytes_decompressed": stats.total_bytes_decompressed,
"compression_skipped_count": stats.compression_skipped_count,
"subscription_out_of_sync_count": stats.subscription_out_of_sync_count,
"subscription_last_sync_timestamp": stats.subscription_last_sync_timestamp,
}
def _parse_pubsub_state(self, result: TResult, is_cluster: bool):
if not isinstance(result, list) or len(result) != 4:
raise RequestError("Invalid response format from GetSubscriptions")
desired_dict = result[1]
actual_dict = result[3]
if is_cluster:
PubSubChannelModes = GlideClusterClientConfiguration.PubSubChannelModes
StateClass = GlideClusterClientConfiguration.PubSubState
mode_map = {
"Exact": PubSubChannelModes.Exact,
"Pattern": PubSubChannelModes.Pattern,
"Sharded": PubSubChannelModes.Sharded,
}
else:
PubSubChannelModes = GlideClientConfiguration.PubSubChannelModes # type: ignore[assignment]
StateClass = GlideClientConfiguration.PubSubState # type: ignore[assignment]
mode_map = {
"Exact": PubSubChannelModes.Exact,
"Pattern": PubSubChannelModes.Pattern,
}
desired_subscriptions = {}
actual_subscriptions = {}
for key_bytes, value_list in desired_dict.items(): # type: ignore[union-attr]
key = key_bytes.decode() if isinstance(key_bytes, bytes) else key_bytes
if key in mode_map:
values = {v.decode() if isinstance(v, bytes) else v for v in value_list}
desired_subscriptions[mode_map[key]] = values
for key_bytes, value_list in actual_dict.items(): # type: ignore[union-attr]
key = key_bytes.decode() if isinstance(key_bytes, bytes) else key_bytes
if key in mode_map:
values = {v.decode() if isinstance(v, bytes) else v for v in value_list}
actual_subscriptions[mode_map[key]] = values
return StateClass(
desired_subscriptions=desired_subscriptions,
actual_subscriptions=actual_subscriptions,
)
async def close(self, err_message: Optional[str] = None) -> None:
if _is_credential_provider_executing(self):
raise RuntimeError(
"Cannot close a client from its own credential provider callback"
)
with self._lock:
if self._is_closed:
return
self._is_closed = True
err_message = "" if err_message is None else err_message
with self._lock:
for fut in self._pending_futures.values():
if not fut.done():
fut.set_exception(ClosingError(err_message))
self._pending_futures.clear()
with self._pubsub_lock:
for fut in self._pubsub_futures:
if not fut.done():
fut.set_exception(ClosingError(err_message))
self._pubsub_futures.clear()
_client_registry.pop(getattr(self, "_pipe_client_id", 0), None)
if self._core_client_finalizer is not None:
self._core_client_finalizer.detach()
# Skip FFI call if this client was created in a different process
# (the tokio Runtime doesn't survive fork; dropping it would hang).
if self._core_client is not None and self._create_pid == os.getpid():
self._lib.close_client(self._core_client)
self._core_client = None
owner = getattr(self, "_credential_provider_callback_owner", None)
if owner is not None:
owner.close()
self._credential_provider_callback_owner = None
self._credential_provider_callback_ref = None
async def aclose(self, err_message: Optional[str] = None) -> None:
"""Alias for close() for compatibility with async context managers."""
await self.close(err_message)
async def __aenter__(self) -> Self:
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.close()
async def scoped_connection(
self, timeout: float = 5.0, routing_key: Optional[str] = None
) -> "AsyncIsolatedScope":
"""
Acquire an isolated execution scope — a dedicated connection for operations
requiring per-connection state (WATCH/MULTI/EXEC, CLIENT TRACKING, blocking
commands).
The scope bypasses the multiplexer, executing commands on its own TCP
connection. Use as an async context manager for automatic release:
async with await client.scoped_connection(routing_key="my-key") as scope:
await scope.watch("my-key")
val = await scope.get("my-key")
await scope.multi()
await scope.set("my-key", str(int(val or "0") + 1))
result = await scope.exec()
Args:
timeout: Maximum seconds to wait for a scope connection (default 5.0).
routing_key: In cluster mode, the key whose hash slot determines which
node the scope connects to, and against which the scope's first
keyed command is validated (a command for a different slot is
rejected locally with CROSSSLOT). If None, the scope starts
unconstrained (slot 0 selects only the initial connection target):
the first keyed command may target any slot and pins the scope to
it, after which later keyed commands for a different slot receive
CROSSSLOT. In standalone mode this argument is ignored.
Returns:
An AsyncIsolatedScope instance.
Raises:
TimeoutError: If no scope is available within the timeout.
ConnectionError: If the client is closed while waiting.
RequestError: If the client's configuration cannot produce a
scoped connection.
ClosingError: If the client is already closed.
"""
from .isolated_scope import AsyncIsolatedScope
if self._is_closed:
raise ClosingError("Client is closed.")
client_id = int(self._ffi.cast("uintptr_t", self._core_client))
conn_req_bytes = self._conn_req_bytes
# Compute routing slot from key (CRC16 mod 16384). Presence is carried
# separately so a cluster scope with no routing key stays unconstrained
# (any primary) rather than being pinned to slot 0, which is a real slot.
has_routing_slot = routing_key is not None
routing_slot = (
_slot_for_key(routing_key.encode("utf-8")) if routing_key is not None else 0
)
callback_id = self._get_callback_id()
fut = _get_new_future_instance()
self._register_future(callback_id, fut)
buf = self._ffi.from_buffer(conn_req_bytes)
rc = self._lib.glide_scope_acquire_pipe(
client_id,
self._ffi.cast("const uint8_t*", buf),
len(conn_req_bytes),
has_routing_slot,
routing_slot,
# uint64_t on the FFI side: a negative value would raise
# OverflowError instead of the documented TimeoutError.
# Negative means no wait.
max(0, int(timeout * 1000)),
callback_id,
self._pipe_client_id,
)
if rc != 0:
self._replace_pending_future(callback_id, fut, None)
raise RuntimeError(f"Failed to queue scope acquire: error code {rc}")
try:
scope_id = await fut
except ClosingError as e:
# close() fails every pending future before core's Disconnect
# frame can arrive; keep the documented class.
raise ConnectionError(str(e) or "Client closed while waiting") from e
except BaseException:
# Cancellation (asyncio.CancelledError, trio.Cancelled) leaves the
# core wait running, or lands after the grant resolved the future
# but before this task saw it.
self._replace_pending_future(
callback_id, fut, _ReleaseLateScope(self._lib, client_id)
)
delivered = _delivered_result(fut)
if delivered is not None:
self._lib.glide_scope_release(delivered, client_id)
raise
return AsyncIsolatedScope(
scope_id,
client_id,
_ASYNC_FFI,
self._parse_scope_response,
)
def _parse_scope_response(self, response_ptr) -> Optional[str]: # noqa: C901
"""Parse a CommandResponse pointer from a scope execution into a Python string."""
if response_ptr == self._ffi.NULL:
return None
resp = response_ptr
resp_type = resp.response_type
if resp_type == 0: # Null
return None
elif resp_type == 1: # Int
return str(resp.int_value)
elif resp_type == 2: # Float
return str(resp.float_value)
elif resp_type == 3: # Bool
return str(resp.bool_value)
elif resp_type == 4: # String
if resp.string_value == self._ffi.NULL:
return None
return self._ffi.buffer(resp.string_value, resp.string_value_len)[:].decode(
"utf-8"
)
elif resp_type == 5: # Array
if resp.array_value == self._ffi.NULL or resp.array_value_len == 0:
return None
results = []
for i in range(resp.array_value_len):
elem = self._parse_scope_response(resp.array_value + i)
results.append(elem)
return str(results)
elif resp_type == 8: # Ok
return "OK"
elif resp_type == 9: # Error
if resp.string_value != self._ffi.NULL:
msg = self._ffi.string(resp.string_value).decode("utf-8")
raise RuntimeError(f"Server error: {msg}")
raise RuntimeError("Server error (unknown)")
else:
return None
|