Skip to content

glide

ClusterScanCursor

Bases: ClusterScanCursor

ClusterScanCursor using the async package's FFI instance.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/_ffi_wrappers.py
19
20
21
22
23
class ClusterScanCursor(_ClusterScanCursorBase):
    """ClusterScanCursor using the async package's FFI instance."""

    def __init__(self, new_cursor=None):
        super().__init__(new_cursor, _ffi=_ASYNC_FFI.ffi, _lib=_ASYNC_FFI.lib)

Script

Bases: Script

Script using the async package's FFI instance.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/_ffi_wrappers.py
12
13
14
15
16
class Script(_ScriptBase):
    """Script using the async package's FFI instance."""

    def __init__(self, code):
        super().__init__(code, _ffi=_ASYNC_FFI.ffi, _lib=_ASYNC_FFI.lib)

AsyncClientPool

FFI-based async client pool. Same Rust pool as all other languages.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/client_pool.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
class AsyncClientPool:
    """FFI-based async client pool. Same Rust pool as all other languages."""

    __slots__ = (
        "_ffi",
        "_lib",
        "_client_config",
        "_pool_config",
        "_closed",
        "_client_cache",
        "_conn_req_bytes",
        "_pool_id",
        "_cache_lock",
        "_is_cluster",
    )

    @classmethod
    async def create(
        cls,
        client_config: BaseClientConfiguration,
        pool_config: Optional[PoolConfig] = None,
    ) -> "AsyncClientPool":
        """Create a pool and validate connectivity with a probe client.

        Creates the pool infrastructure, then attempts to connect a single
        probe client using the same config. If the probe fails, the pool is
        destroyed and the actual connection error is propagated (not a timeout).

        Args:
            client_config: Client configuration (standalone or cluster).
            pool_config: Optional pool sizing/timeout configuration.

        Returns:
            A ready-to-use AsyncClientPool instance.

        Raises:
            The same exception that GlideClient.create() / GlideClusterClient.create()
            would raise on connection failure.
        """
        pool = cls(client_config, pool_config)
        try:
            ClientClass = GlideClusterClient if pool._is_cluster else GlideClient
            probe = await ClientClass.create(client_config)
            await probe.close()
        except Exception:
            pool.close()
            raise
        return pool

    def __init__(
        self,
        client_config: BaseClientConfiguration,
        pool_config: Optional[PoolConfig] = None,
    ):
        # Custom providers are direct-client-only; pools may use the default AWS chain.
        credentials = getattr(client_config, "credentials", None)
        iam_config = getattr(credentials, "iam_config", None)
        if iam_config is not None and iam_config.credential_provider is not None:
            raise ValueError(
                "Pool clients cannot use a custom IAM credentials provider. "
                "Configure IAM without a credential_provider to use the default AWS credential chain."
            )

        # Reject pubsub subscriptions — pool state reset doesn't UNSUBSCRIBE
        if (
            hasattr(client_config, "pubsub_subscriptions")
            and client_config.pubsub_subscriptions
        ):
            raise ValueError(
                "Pool clients cannot have pubsub subscriptions configured. "
                "Use the main client's pubsub API for subscriptions."
            )

        ffi_instance = _ASYNC_FFI
        self._ffi = ffi_instance.ffi
        self._lib = ffi_instance.lib
        self._client_config = client_config
        self._pool_config = pool_config or PoolConfig()
        self._closed = False
        self._client_cache: dict = {}
        self._cache_lock = threading.Lock()
        self._is_cluster = isinstance(client_config, GlideClusterClientConfiguration)

        # Serialize connection request. Route through the shared helper so
        # pooled clients honour lib_name / client_info_tag exactly like direct
        # GlideClient.create() clients do (default "GlidePy", user-configured
        # lib_name, and the "(client_info_tag)" suffix).
        conn_req = _create_async_connection_request(client_config)
        self._conn_req_bytes = conn_req.SerializeToString()

        # Initialize the shared async pipe BEFORE creating pool clients.
        # This ensures ASYNC_PIPE is set so pooled AsyncClient adapters
        # write responses to the pipe (not the callback path).
        import glide.glide_client as _gc

        with _async_pipe_lock:
            _gc._detect_fork_and_reset()
            current_pid = os.getpid()

            if _gc._async_pipe_read_fd < 0:
                try:
                    r, w = os.pipe()
                    os.set_blocking(r, False)
                    if (
                        _gc._async_pipe_init_pid > 0
                        and current_pid != _gc._async_pipe_init_pid
                    ):
                        self._lib.reinit_async_pipe(w)
                    else:
                        self._lib.init_async_pipe(w)
                    _gc._async_pipe_read_fd = r
                    _gc._async_pipe_write_fd = w
                    _gc._async_pipe_init_pid = current_pid
                except OSError:
                    pass

        # Create pool with AsyncClient type (no-op callbacks — pipe handles responses)
        client_type = self._ffi.new("ClientType*")
        client_type._type = 0  # AsyncClient
        client_type.async_client.success_callback = self._lib.noop_success_callback
        client_type.async_client.failure_callback = self._lib.noop_failure_callback
        client_type.async_client.allow_stack_response = False

        buf = self._ffi.from_buffer(self._conn_req_bytes)
        pool_id = self._lib.glide_pool_create(
            self._pool_config.max_size,
            self._pool_config.min_idle,
            self._pool_config.idle_timeout_ms,
            self._pool_config.request_timeout_ms,
            self._pool_config.abandon_timeout_ms,
            self._ffi.cast("const uint8_t*", buf),
            len(self._conn_req_bytes),
            client_type,
        )
        if pool_id < 0:
            raise RuntimeError(f"Failed to create pool: error code {pool_id}")
        self._pool_id = pool_id

    async def acquire(self, timeout: Optional[float] = None) -> int:
        """Acquire a client_id using non-blocking try_acquire with async backoff.

        Uses glide_pool_try_acquire (non-blocking) instead of
        glide_pool_acquire_blocking to avoid blocking thread pool threads.
        Blocking threads prevents the event loop from draining the async pipe,
        which deadlocks the pool's release state-reset (DISCARD + SELECT).
        """
        if self._closed:
            raise RuntimeError("Pool is closed")
        timeout = (
            timeout if timeout is not None else self._pool_config.acquire_timeout_s
        )

        import time

        deadline = time.monotonic() + timeout
        backoff = 0.005  # Start at 5ms

        while True:
            client_id = self._lib.glide_pool_try_acquire(self._pool_id)
            if client_id >= 0:
                return client_id
            if client_id == -2:
                raise RuntimeError("Invalid pool_id — pool was destroyed")

            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise TimeoutError(
                    f"Pool exhausted: could not acquire client within {timeout}s"
                )

            # Yield to event loop — allows pipe reader to process release responses
            await asyncio.sleep(min(backoff, remaining))
            backoff = min(backoff * 2, 0.05)  # Cap at 50ms

    def release(self, client_id: int) -> None:
        """Release a borrowed client back to the pool."""
        self._lib.glide_pool_release(self._pool_id, client_id)

    def borrow(self, timeout: Optional[float] = None):
        """Async context manager."""
        return _AsyncBorrowContext(self, timeout)

    def _get_or_create_client(self, client_id: int) -> BaseClient:
        """Get/create a client wrapper with pipe registration."""
        cached = self._client_cache.get(client_id)
        if cached is not None:
            return cached

        with self._cache_lock:
            cached = self._client_cache.get(client_id)
            if cached is not None:
                return cached

            adapter_ptr = self._lib.glide_pool_get_client_ptr(client_id)
            if adapter_ptr == 0:
                raise RuntimeError(
                    f"Pool client_id {client_id} has no associated ClientAdapter"
                )

            ClientClass = GlideClusterClient if self._is_cluster else GlideClient
            client = object.__new__(ClientClass)
            client.config = self._client_config
            client._is_closed = False
            client._ffi = self._ffi
            client._lib = self._lib
            client._pending_futures = {}
            client._pending_push_notifications = []
            client._pubsub_futures = []
            client._pubsub_lock = threading.Lock()
            client._pubsub_callback_ref = None
            client._callback_id_gen = __import__("itertools").count(1)
            client._lock = threading.Lock()
            client._is_asyncio = True
            client._core_client = self._ffi.cast("void*", adapter_ptr)
            client._conn_req_bytes = self._conn_req_bytes
            client._create_pid = os.getpid()

            # The pool created this client with pipe_client_id = client_id
            # (set in create_client_internal via the pre-assigned ID).
            # Register so the pipe reader routes responses here.
            client._pipe_client_id = client_id
            try:
                client._loop = asyncio.get_running_loop()
            except RuntimeError:
                client._loop = None

            _client_registry[client_id] = client
            client._setup_pipe()

            self._client_cache[client_id] = client
            return client

    @property
    def is_closed(self) -> bool:
        return self._closed

    @property
    def pool_id(self) -> int:
        return self._pool_id

    def metrics(self) -> dict:
        """Get pool metrics: idle, active, total counts.

        Zeros when the pool was destroyed.
        """
        m = self._lib.glide_pool_metrics(self._pool_id)
        return {"idle": m.idle, "active": m.active, "total": m.total}

    @property
    def idle_count(self) -> int:
        return self.metrics()["idle"]

    @property
    def active_count(self) -> int:
        return self.metrics()["active"]

    @property
    def total_count(self) -> int:
        return self.metrics()["total"]

    def close(self):
        if not self._closed:
            self._closed = True
            for cid in list(self._client_cache.keys()):
                _client_registry.pop(cid, None)
            self._lib.glide_pool_destroy(self._pool_id)
            self._client_cache.clear()

    async def aclose(self):
        self.close()

    async def __aenter__(self):
        return self

    async def __aexit__(self, *_):
        self.close()
        return False

    def __del__(self):
        # Do NOT call close() from __del__. The FFI glide_pool_destroy call
        # can race with active callbacks from the Rust side, causing segfaults.
        # Users must call close() explicitly or use async context manager.
        pass

create(client_config, pool_config=None) async classmethod

Create a pool and validate connectivity with a probe client.

Creates the pool infrastructure, then attempts to connect a single probe client using the same config. If the probe fails, the pool is destroyed and the actual connection error is propagated (not a timeout).

Parameters:

Name Type Description Default
client_config BaseClientConfiguration

Client configuration (standalone or cluster).

required
pool_config Optional[PoolConfig]

Optional pool sizing/timeout configuration.

None

Returns:

Type Description
AsyncClientPool

A ready-to-use AsyncClientPool instance.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/client_pool.py
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
@classmethod
async def create(
    cls,
    client_config: BaseClientConfiguration,
    pool_config: Optional[PoolConfig] = None,
) -> "AsyncClientPool":
    """Create a pool and validate connectivity with a probe client.

    Creates the pool infrastructure, then attempts to connect a single
    probe client using the same config. If the probe fails, the pool is
    destroyed and the actual connection error is propagated (not a timeout).

    Args:
        client_config: Client configuration (standalone or cluster).
        pool_config: Optional pool sizing/timeout configuration.

    Returns:
        A ready-to-use AsyncClientPool instance.

    Raises:
        The same exception that GlideClient.create() / GlideClusterClient.create()
        would raise on connection failure.
    """
    pool = cls(client_config, pool_config)
    try:
        ClientClass = GlideClusterClient if pool._is_cluster else GlideClient
        probe = await ClientClass.create(client_config)
        await probe.close()
    except Exception:
        pool.close()
        raise
    return pool

acquire(timeout=None) async

Acquire a client_id using non-blocking try_acquire with async backoff.

Uses glide_pool_try_acquire (non-blocking) instead of glide_pool_acquire_blocking to avoid blocking thread pool threads. Blocking threads prevents the event loop from draining the async pipe, which deadlocks the pool's release state-reset (DISCARD + SELECT).

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/client_pool.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
async def acquire(self, timeout: Optional[float] = None) -> int:
    """Acquire a client_id using non-blocking try_acquire with async backoff.

    Uses glide_pool_try_acquire (non-blocking) instead of
    glide_pool_acquire_blocking to avoid blocking thread pool threads.
    Blocking threads prevents the event loop from draining the async pipe,
    which deadlocks the pool's release state-reset (DISCARD + SELECT).
    """
    if self._closed:
        raise RuntimeError("Pool is closed")
    timeout = (
        timeout if timeout is not None else self._pool_config.acquire_timeout_s
    )

    import time

    deadline = time.monotonic() + timeout
    backoff = 0.005  # Start at 5ms

    while True:
        client_id = self._lib.glide_pool_try_acquire(self._pool_id)
        if client_id >= 0:
            return client_id
        if client_id == -2:
            raise RuntimeError("Invalid pool_id — pool was destroyed")

        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError(
                f"Pool exhausted: could not acquire client within {timeout}s"
            )

        # Yield to event loop — allows pipe reader to process release responses
        await asyncio.sleep(min(backoff, remaining))
        backoff = min(backoff * 2, 0.05)  # Cap at 50ms

release(client_id)

Release a borrowed client back to the pool.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/client_pool.py
224
225
226
def release(self, client_id: int) -> None:
    """Release a borrowed client back to the pool."""
    self._lib.glide_pool_release(self._pool_id, client_id)

borrow(timeout=None)

Async context manager.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/client_pool.py
228
229
230
def borrow(self, timeout: Optional[float] = None):
    """Async context manager."""
    return _AsyncBorrowContext(self, timeout)

metrics()

Get pool metrics: idle, active, total counts.

Zeros when the pool was destroyed.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/client_pool.py
290
291
292
293
294
295
296
def metrics(self) -> dict:
    """Get pool metrics: idle, active, total counts.

    Zeros when the pool was destroyed.
    """
    m = self._lib.glide_pool_metrics(self._pool_id)
    return {"idle": m.idle, "active": m.active, "total": m.total}

PoolConfig dataclass

Configuration for the async client-instance pool.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/client_pool.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@dataclass
class PoolConfig:
    """Configuration for the async client-instance pool."""

    max_size: int = 10
    min_idle: int = 1
    idle_timeout_ms: int = 300_000
    request_timeout_ms: int = 5_000
    acquire_timeout_s: float = 5.0
    abandon_timeout_ms: int = 300_000
    """Maximum inactivity time for a borrowed client before the pool reclaims it (ms).
    The timer resets on every command sent. The abandon monitor skips clients
    executing blocking commands (BLPOP, XREAD BLOCK, etc.).
    Set to 0 to disable abandon detection. Default: 5 minutes."""
    test_on_borrow: bool = False

abandon_timeout_ms = 300000 class-attribute instance-attribute

Maximum inactivity time for a borrowed client before the pool reclaims it (ms). The timer resets on every command sent. The abandon monitor skips clients executing blocking commands (BLPOP, XREAD BLOCK, etc.). Set to 0 to disable abandon detection. Default: 5 minutes.

GlideClient

Bases: BaseClient, StandaloneCommands

Client used for connection to standalone servers. Use :func:~BaseClient.create to request a client. For full documentation, see Valkey GLIDE Documentation

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/glide_client.py
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
class GlideClient(BaseClient, StandaloneCommands):
    """
    Client used for connection to standalone servers.
    Use :func:`~BaseClient.create` to request a client.
    For full documentation, see
    [Valkey GLIDE Documentation](https://glide.valkey.io/how-to/client-initialization/#standalone)
    """

    async def get_subscriptions(
        self,
    ) -> GlideClientConfiguration.PubSubState:
        result = await self._execute_command(RequestType.GetSubscriptions, [])
        return cast(
            GlideClientConfiguration.PubSubState,
            self._parse_pubsub_state(result, is_cluster=False),
        )

GlideClusterClient

Bases: BaseClient, ClusterCommands

Client used for connection to cluster servers. Use :func:~BaseClient.create to request a client. For full documentation, see Valkey GLIDE Documentation

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/glide_client.py
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
class GlideClusterClient(BaseClient, ClusterCommands):
    """
    Client used for connection to cluster servers.
    Use :func:`~BaseClient.create` to request a client.
    For full documentation, see
    [Valkey GLIDE Documentation](https://glide.valkey.io/how-to/client-initialization/#cluster)
    """

    async def _cluster_scan(
        self,
        cursor: ClusterScanCursor,
        match: Optional[TEncodable] = None,
        count: Optional[int] = None,
        type: Optional[ObjectType] = None,
        allow_non_covered_slots: bool = False,
    ) -> List[Union[ClusterScanCursor, List[bytes]]]:
        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)

        # Build scan args
        args = []
        if match is not None:
            encoded_match = match.encode(ENCODING) if isinstance(match, str) else match
            args.extend([b"MATCH", encoded_match])
        if count is not None:
            args.extend([b"COUNT", str(count).encode(ENCODING)])
        if type is not None:
            args.extend([b"TYPE", type.value.encode(ENCODING)])
        if allow_non_covered_slots:
            args.extend([b"ALLOW_NON_COVERED_SLOTS"])

        cursor_string = cursor.get_cursor()
        cursor_bytes = cursor_string.encode(ENCODING) + b"\0"
        cursor_buffer = self._ffi.from_buffer(cursor_bytes)

        if args:
            args_array, args_len_array, arg_buffers = self._to_c_strings(args)
            arg_count = len(args)
        else:
            args_array = self._ffi.NULL
            args_len_array = self._ffi.NULL
            arg_count = 0

        self._lib.request_cluster_scan(
            self._core_client,
            callback_id,
            cursor_buffer,
            arg_count,
            args_array,
            args_len_array,
        )

        response_data = await fut

        if not isinstance(response_data, list) or len(response_data) != 2:
            raise RequestError("Unexpected cluster scan response format")

        new_cursor = response_data[0]
        if isinstance(new_cursor, bytes):
            new_cursor = new_cursor.decode(ENCODING)

        keys_list = response_data[1] if response_data[1] is not None else []
        return [ClusterScanCursor(new_cursor), keys_list]

    async def get_subscriptions(
        self,
    ) -> GlideClusterClientConfiguration.PubSubState:
        result = await self._execute_command(RequestType.GetSubscriptions, [])
        return cast(
            GlideClusterClientConfiguration.PubSubState,
            self._parse_pubsub_state(result, is_cluster=True),
        )

AsyncIsolatedScope

Async wrapper around a dedicated scoped connection.

Commands are dispatched to a thread pool executor (since the underlying FFI call blocks on Tokio), keeping the asyncio event loop free.

Thread Safety: A single AsyncIsolatedScope should only be used from one coroutine at a time. Multiple coroutines should each acquire their own scope.

Use as an async context manager

async with client.scoped_connection() as scope: await scope.watch("key") ...

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class AsyncIsolatedScope:
    """
    Async wrapper around a dedicated scoped connection.

    Commands are dispatched to a thread pool executor (since the underlying
    FFI call blocks on Tokio), keeping the asyncio event loop free.

    Thread Safety: A single AsyncIsolatedScope should only be used from one
    coroutine at a time. Multiple coroutines should each acquire their own scope.

    Use as an async context manager:
        async with client.scoped_connection() as scope:
            await scope.watch("key")
            ...
    """

    __slots__ = (
        "_scope_id",
        "_client_id",
        "_ffi",
        "_lib",
        "_released",
        "_response_parser",
        "_executor",
    )

    def __init__(
        self,
        scope_id: int,
        client_id: int,
        ffi_instance: _GlideFFI,
        response_parser,
        executor=None,
    ):
        self._scope_id = scope_id
        self._client_id = client_id
        self._ffi = ffi_instance.ffi
        self._lib = ffi_instance.lib
        self._released = False
        self._response_parser = response_parser
        self._executor = executor  # ThreadPoolExecutor or None (uses default)

    @property
    def scope_id(self) -> int:
        if self._released:
            raise RuntimeError("Scope already released")
        return self._scope_id

    @property
    def is_released(self) -> bool:
        return self._released

    # ═══════════════════════════════════════════════════════════════════════════
    # COMMANDS (all async)
    # ═══════════════════════════════════════════════════════════════════════════

    async def watch(self, *keys: str) -> Optional[str]:
        """WATCH one or more keys for optimistic locking."""
        return await self._cmd("WATCH", *keys)

    async def unwatch(self) -> Optional[str]:
        """Discard all watched keys."""
        return await self._cmd("UNWATCH")

    async def multi(self) -> Optional[str]:
        """Begin a transaction block."""
        return await self._cmd("MULTI")

    async def exec(self) -> Optional[str]:
        """Execute the transaction (returns None if WATCH detected a conflict)."""
        return await self._cmd("EXEC")

    async def discard(self) -> Optional[str]:
        """Discard the transaction."""
        return await self._cmd("DISCARD")

    async def get(self, key: str) -> Optional[str]:
        """GET a key value."""
        return await self._cmd("GET", key)

    async def set(self, key: str, value: str) -> Optional[str]:
        """SET a key to a value."""
        return await self._cmd("SET", key, value)

    async def incr(self, key: str) -> Optional[str]:
        """Increment a key's integer value by 1."""
        return await self._cmd("INCR", key)

    async def ping(self, message: Optional[str] = None) -> Optional[str]:
        """PING the server."""
        if message:
            return await self._cmd("PING", message)
        return await self._cmd("PING")

    async def select(self, db: int) -> Optional[str]:
        """SELECT a database by index."""
        return await self._cmd("SELECT", str(db))

    async def execute_command(self, command: str, *args: str) -> Optional[str]:
        """Execute an arbitrary command on this scope."""
        return await self._cmd(command, *args)

    # ═══════════════════════════════════════════════════════════════════════════
    # INTERNAL
    # ═══════════════════════════════════════════════════════════════════════════

    async def _cmd(self, command: str, *args: str) -> Optional[str]:
        """Serialize and execute a command on the scoped connection (async)."""
        if self._released:
            raise RuntimeError("Scope already released")

        # Serialize in wire format
        cmd_bytes = command.encode("utf-8")
        parts = [
            struct.pack("<I", len(cmd_bytes)),
            cmd_bytes,
            struct.pack("<I", len(args)),
        ]
        for arg in args:
            arg_bytes = arg.encode("utf-8")
            parts.append(struct.pack("<I", len(arg_bytes)))
            parts.append(arg_bytes)
        payload = b"".join(parts)

        # Execute in thread pool to avoid blocking the event loop
        loop = asyncio.get_running_loop()
        result_ptr = await loop.run_in_executor(
            self._executor, self._execute_sync, payload
        )

        if result_ptr == self._ffi.NULL:
            raise RuntimeError(f"Scope execute failed: invalid scope {self._scope_id}")

        try:
            return self._parse_result(result_ptr)
        finally:
            self._lib.free_command_result(result_ptr)

    def _execute_sync(self, payload: bytes):
        """Synchronous FFI call (runs in executor thread)."""
        buf = self._ffi.from_buffer(payload)
        return self._lib.glide_scope_execute(
            self._scope_id,
            self._ffi.cast("const uint8_t*", buf),
            len(payload),
        )

    def _parse_result(self, result_ptr) -> Optional[str]:
        """Parse a CommandResult pointer into a Python value."""
        result = result_ptr

        if result.command_error != self._ffi.NULL:
            err = result.command_error
            msg = self._ffi.string(err.command_error_message).decode("utf-8")
            raise RuntimeError(f"Scope command error: {msg}")

        if result.response == self._ffi.NULL:
            return None

        return self._response_parser(result.response)

    # ═══════════════════════════════════════════════════════════════════════════
    # ASYNC CONTEXT MANAGER
    # ═══════════════════════════════════════════════════════════════════════════

    async def close(self):
        """Release the scope back to the pool."""
        if not self._released:
            self._released = True
            self._lib.glide_scope_release(self._scope_id, self._client_id)

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()
        return False

    def __del__(self):
        """Safety net — release on GC if not explicitly closed."""
        if not self._released:
            try:
                self._released = True
                self._lib.glide_scope_release(self._scope_id, self._client_id)
            except Exception:
                pass

watch(*keys) async

WATCH one or more keys for optimistic locking.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
87
88
89
async def watch(self, *keys: str) -> Optional[str]:
    """WATCH one or more keys for optimistic locking."""
    return await self._cmd("WATCH", *keys)

unwatch() async

Discard all watched keys.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
91
92
93
async def unwatch(self) -> Optional[str]:
    """Discard all watched keys."""
    return await self._cmd("UNWATCH")

multi() async

Begin a transaction block.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
95
96
97
async def multi(self) -> Optional[str]:
    """Begin a transaction block."""
    return await self._cmd("MULTI")

exec() async

Execute the transaction (returns None if WATCH detected a conflict).

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
 99
100
101
async def exec(self) -> Optional[str]:
    """Execute the transaction (returns None if WATCH detected a conflict)."""
    return await self._cmd("EXEC")

discard() async

Discard the transaction.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
103
104
105
async def discard(self) -> Optional[str]:
    """Discard the transaction."""
    return await self._cmd("DISCARD")

get(key) async

GET a key value.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
107
108
109
async def get(self, key: str) -> Optional[str]:
    """GET a key value."""
    return await self._cmd("GET", key)

set(key, value) async

SET a key to a value.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
111
112
113
async def set(self, key: str, value: str) -> Optional[str]:
    """SET a key to a value."""
    return await self._cmd("SET", key, value)

incr(key) async

Increment a key's integer value by 1.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
115
116
117
async def incr(self, key: str) -> Optional[str]:
    """Increment a key's integer value by 1."""
    return await self._cmd("INCR", key)

ping(message=None) async

PING the server.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
119
120
121
122
123
async def ping(self, message: Optional[str] = None) -> Optional[str]:
    """PING the server."""
    if message:
        return await self._cmd("PING", message)
    return await self._cmd("PING")

select(db) async

SELECT a database by index.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
125
126
127
async def select(self, db: int) -> Optional[str]:
    """SELECT a database by index."""
    return await self._cmd("SELECT", str(db))

execute_command(command, *args) async

Execute an arbitrary command on this scope.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
129
130
131
async def execute_command(self, command: str, *args: str) -> Optional[str]:
    """Execute an arbitrary command on this scope."""
    return await self._cmd(command, *args)

close() async

Release the scope back to the pool.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/isolated_scope.py
196
197
198
199
200
async def close(self):
    """Release the scope back to the pool."""
    if not self._released:
        self._released = True
        self._lib.glide_scope_release(self._scope_id, self._client_id)

MonitorClient

An async client that streams all commands processed by the server via MONITOR.

Must be used with a standalone (non-cluster) configuration. The configuration's lib_name and client_info_tag identify the dedicated monitor connection, using GlidePy as the default library name. Supports both asyncio and trio backends via anyio.

Warning: MONITOR is a debugging tool with performance implications. Do not use in production environments.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/monitor_client.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class MonitorClient:
    """
    An async client that streams all commands processed by the server via MONITOR.

    Must be used with a standalone (non-cluster) configuration.
    The configuration's ``lib_name`` and ``client_info_tag`` identify the dedicated
    monitor connection, using ``GlidePy`` as the default library name.
    Supports both asyncio and trio backends via anyio.

    Warning: MONITOR is a debugging tool with performance implications.
    Do not use in production environments.
    """

    def __init__(self) -> None:
        self._ffi = GlideFFI.ffi
        self._lib = GlideFFI.lib
        self._core_client = self._ffi.NULL
        self._callback_ref = None
        self._is_closed = False
        self._stop_lock = threading.Lock()
        self._user_callback: Optional[Callable[[MonitorMsg], None]] = None
        self._is_asyncio: bool = True
        # asyncio path
        self._asyncio_queue: Optional[asyncio.Queue[MonitorMsg]] = None
        self._asyncio_loop: Optional[asyncio.AbstractEventLoop] = None
        # trio path
        self._trio_send: Any = None
        self._trio_receive: Any = None
        self._trio_token: Any = None

    def _setup_queue(self) -> None:
        """Initialize the backend-specific message queue."""
        if not self._is_asyncio:
            import math

            import trio

            self._trio_token = trio.lowlevel.current_trio_token()
            # Unbounded — matches asyncio.Queue() default behavior for this debug-only client
            self._trio_send, self._trio_receive = trio.open_memory_channel(math.inf)
        else:
            self._asyncio_loop = asyncio.get_running_loop()
            self._asyncio_queue = asyncio.Queue()

    def _enqueue_message(self, msg: MonitorMsg) -> None:
        """Thread-safe enqueue from the FFI callback thread."""
        if self._is_closed:
            return
        if not self._is_asyncio:
            import trio

            def _safe_send(msg=msg):
                try:
                    self._trio_send.send_nowait(msg)
                except (trio.ClosedResourceError, trio.BrokenResourceError):
                    pass  # channel torn down, discard

            try:
                self._trio_token.run_sync_soon(_safe_send)
            except trio.RunFinishedError:
                pass  # trio loop exited, discard
        else:
            loop = self._asyncio_loop
            if loop is not None and not loop.is_closed():
                loop.call_soon_threadsafe(
                    self._asyncio_queue.put_nowait, msg  # type: ignore[union-attr]
                )

    @classmethod
    async def create(  # noqa: C901
        cls,
        config: GlideClientConfiguration,
        callback: Optional[Callable[[MonitorMsg], None]] = None,
    ) -> "MonitorClient":
        """
        Create a new async MonitorClient.

        Args:
            config: Standalone client configuration (must be GlideClientConfiguration).
                    Its library-name override and client information tag are applied
                    to the dedicated monitor connection.
            callback: Optional sync callback invoked for each MonitorMsg. If None,
                      messages are queued for get_monitor_message().

        Returns:
            A MonitorClient instance.
        """
        if not isinstance(config, GlideClientConfiguration):
            raise TypeError(
                "MonitorClient requires a GlideClientConfiguration (standalone only)"
            )
        iam_config = (
            config.credentials.iam_config if config.credentials is not None else None
        )
        if iam_config is not None:
            raise ConfigurationError(
                "MonitorClient does not support IAM authentication"
            )
        instance = cls()
        try:
            instance._is_asyncio = sniffio.current_async_library() == "asyncio"
        except sniffio.AsyncLibraryNotFoundError:
            instance._is_asyncio = True
        instance._user_callback = callback
        instance._setup_queue()

        conn_req = _create_async_connection_request(config)
        conn_req_bytes = conn_req.SerializeToString()

        @instance._ffi.callback("MonitorCallback")
        def _monitor_callback(
            client_ptr,
            timestamp,
            db,
            client_addr_ptr,
            client_addr_len,
            command_ptr,
            command_len,
            args_json_ptr,
            args_json_len,
        ):
            try:
                client_addr = bytes(
                    instance._ffi.buffer(client_addr_ptr, client_addr_len)
                ).decode("utf-8", errors="replace")
                command = bytes(instance._ffi.buffer(command_ptr, command_len)).decode(
                    "utf-8", errors="replace"
                )
                args_json_str = bytes(
                    instance._ffi.buffer(args_json_ptr, args_json_len)
                ).decode("utf-8", errors="replace")
                try:
                    args: List[str] = (
                        json.loads(args_json_str) if args_json_len > 0 else []
                    )
                except (json.JSONDecodeError, ValueError):
                    args = []
                msg = MonitorMsg(
                    timestamp=timestamp,
                    db=db,
                    client_addr=client_addr,
                    command=command,
                    args=args,
                )
                if instance._user_callback is not None:
                    instance._user_callback(msg)
                else:
                    instance._enqueue_message(msg)
            except Exception:
                pass  # Suppress to avoid crashing the FFI layer

        instance._callback_ref = _monitor_callback
        client_response = instance._lib.create_monitor_client(
            conn_req_bytes, len(conn_req_bytes), _monitor_callback
        )
        if client_response == instance._ffi.NULL:
            raise RuntimeError("Failed to create monitor client: null response")
        if client_response.connection_error_message != instance._ffi.NULL:
            error = instance._ffi.string(
                client_response.connection_error_message
            ).decode()
            error_class = get_connection_error_class(
                client_response.connection_error_type, default=RuntimeError
            )
            instance._lib.free_connection_response(client_response)
            raise error_class(f"Failed to create monitor client: {error}")
        instance._core_client = client_response.conn_ptr
        instance._lib.free_connection_response(client_response)
        return instance

    async def get_monitor_message(self) -> MonitorMsg:
        """Wait for and return the next MonitorMsg."""
        if not self._is_asyncio:
            return await self._trio_receive.receive()
        # asyncio path also covers uvloop: uvloop is a drop-in asyncio replacement
        # and sniffio reports it as "asyncio"
        return await self._asyncio_queue.get()  # type: ignore[union-attr]

    def try_get_monitor_message(self) -> Optional[MonitorMsg]:
        """Non-blocking retrieval. Returns None if queue is empty."""
        if not self._is_asyncio:
            import trio

            try:
                return self._trio_receive.receive_nowait()
            except trio.WouldBlock:
                return None
        try:
            return self._asyncio_queue.get_nowait()  # type: ignore[union-attr]
        except asyncio.QueueEmpty:
            return None

    async def stop(self) -> None:
        """Stop monitoring and release resources."""
        with self._stop_lock:
            if self._is_closed:
                return
            self._is_closed = True
            core_client, self._core_client = self._core_client, self._ffi.NULL
        if core_client != self._ffi.NULL:
            self._lib.close_monitor_client(core_client)
        if not self._is_asyncio and self._trio_send is not None:
            await self._trio_send.aclose()
            if self._trio_receive is not None:
                await self._trio_receive.aclose()
        self._callback_ref = None  # clear after Rust is done and channels are closed

    async def aclose(self) -> None:
        """Alias for stop()."""
        await self.stop()

    async def __aenter__(self) -> "MonitorClient":
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
        await self.stop()

create(config, callback=None) async classmethod

Create a new async MonitorClient.

Parameters:

Name Type Description Default
config GlideClientConfiguration

Standalone client configuration (must be GlideClientConfiguration). Its library-name override and client information tag are applied to the dedicated monitor connection.

required
callback Optional[Callable[[MonitorMsg], None]]

Optional sync callback invoked for each MonitorMsg. If None, messages are queued for get_monitor_message().

None

Returns:

Type Description
MonitorClient

A MonitorClient instance.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/monitor_client.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
@classmethod
async def create(  # noqa: C901
    cls,
    config: GlideClientConfiguration,
    callback: Optional[Callable[[MonitorMsg], None]] = None,
) -> "MonitorClient":
    """
    Create a new async MonitorClient.

    Args:
        config: Standalone client configuration (must be GlideClientConfiguration).
                Its library-name override and client information tag are applied
                to the dedicated monitor connection.
        callback: Optional sync callback invoked for each MonitorMsg. If None,
                  messages are queued for get_monitor_message().

    Returns:
        A MonitorClient instance.
    """
    if not isinstance(config, GlideClientConfiguration):
        raise TypeError(
            "MonitorClient requires a GlideClientConfiguration (standalone only)"
        )
    iam_config = (
        config.credentials.iam_config if config.credentials is not None else None
    )
    if iam_config is not None:
        raise ConfigurationError(
            "MonitorClient does not support IAM authentication"
        )
    instance = cls()
    try:
        instance._is_asyncio = sniffio.current_async_library() == "asyncio"
    except sniffio.AsyncLibraryNotFoundError:
        instance._is_asyncio = True
    instance._user_callback = callback
    instance._setup_queue()

    conn_req = _create_async_connection_request(config)
    conn_req_bytes = conn_req.SerializeToString()

    @instance._ffi.callback("MonitorCallback")
    def _monitor_callback(
        client_ptr,
        timestamp,
        db,
        client_addr_ptr,
        client_addr_len,
        command_ptr,
        command_len,
        args_json_ptr,
        args_json_len,
    ):
        try:
            client_addr = bytes(
                instance._ffi.buffer(client_addr_ptr, client_addr_len)
            ).decode("utf-8", errors="replace")
            command = bytes(instance._ffi.buffer(command_ptr, command_len)).decode(
                "utf-8", errors="replace"
            )
            args_json_str = bytes(
                instance._ffi.buffer(args_json_ptr, args_json_len)
            ).decode("utf-8", errors="replace")
            try:
                args: List[str] = (
                    json.loads(args_json_str) if args_json_len > 0 else []
                )
            except (json.JSONDecodeError, ValueError):
                args = []
            msg = MonitorMsg(
                timestamp=timestamp,
                db=db,
                client_addr=client_addr,
                command=command,
                args=args,
            )
            if instance._user_callback is not None:
                instance._user_callback(msg)
            else:
                instance._enqueue_message(msg)
        except Exception:
            pass  # Suppress to avoid crashing the FFI layer

    instance._callback_ref = _monitor_callback
    client_response = instance._lib.create_monitor_client(
        conn_req_bytes, len(conn_req_bytes), _monitor_callback
    )
    if client_response == instance._ffi.NULL:
        raise RuntimeError("Failed to create monitor client: null response")
    if client_response.connection_error_message != instance._ffi.NULL:
        error = instance._ffi.string(
            client_response.connection_error_message
        ).decode()
        error_class = get_connection_error_class(
            client_response.connection_error_type, default=RuntimeError
        )
        instance._lib.free_connection_response(client_response)
        raise error_class(f"Failed to create monitor client: {error}")
    instance._core_client = client_response.conn_ptr
    instance._lib.free_connection_response(client_response)
    return instance

get_monitor_message() async

Wait for and return the next MonitorMsg.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/monitor_client.py
186
187
188
189
190
191
192
async def get_monitor_message(self) -> MonitorMsg:
    """Wait for and return the next MonitorMsg."""
    if not self._is_asyncio:
        return await self._trio_receive.receive()
    # asyncio path also covers uvloop: uvloop is a drop-in asyncio replacement
    # and sniffio reports it as "asyncio"
    return await self._asyncio_queue.get()  # type: ignore[union-attr]

try_get_monitor_message()

Non-blocking retrieval. Returns None if queue is empty.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/monitor_client.py
194
195
196
197
198
199
200
201
202
203
204
205
206
def try_get_monitor_message(self) -> Optional[MonitorMsg]:
    """Non-blocking retrieval. Returns None if queue is empty."""
    if not self._is_asyncio:
        import trio

        try:
            return self._trio_receive.receive_nowait()
        except trio.WouldBlock:
            return None
    try:
        return self._asyncio_queue.get_nowait()  # type: ignore[union-attr]
    except asyncio.QueueEmpty:
        return None

stop() async

Stop monitoring and release resources.

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/monitor_client.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
async def stop(self) -> None:
    """Stop monitoring and release resources."""
    with self._stop_lock:
        if self._is_closed:
            return
        self._is_closed = True
        core_client, self._core_client = self._core_client, self._ffi.NULL
    if core_client != self._ffi.NULL:
        self._lib.close_monitor_client(core_client)
    if not self._is_asyncio and self._trio_send is not None:
        await self._trio_send.aclose()
        if self._trio_receive is not None:
            await self._trio_receive.aclose()
    self._callback_ref = None  # clear after Rust is done and channels are closed

aclose() async

Alias for stop().

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/monitor_client.py
223
224
225
async def aclose(self) -> None:
    """Alias for stop()."""
    await self.stop()

OpenTelemetry

Bases: OpenTelemetry

Async client OpenTelemetry singleton (separate from sync).

Source code in doc-gen/valkey-glide/python/glide-async/python/glide/opentelemetry.py
11
12
13
14
15
class OpenTelemetry(_BaseOpenTelemetry):
    """Async client OpenTelemetry singleton (separate from sync)."""

    _instance = None
    _config = None