Standard library
nox.redis
A Redis client (RESP2) written in Zig: no hiredis needed. Plain TCP or TLS from the first byte, AUTH (password or user + password), SELECT, byte-safe commands
and replies, Streams and consumer groups, a script cache with NOSCRIPT recovery, and reconnecting.
import nox.redis
from nox.redis import Client, Reply, RedisErrorCapability: network.
Connecting#
connect(host, port=6379, tls=False, username="", password="", db=0, ca_file="", cert_file="", key_file="") -> Client
tls=Truestarts TLS immediately (arediss://-style endpoint); the certificate and host name are checked against the system CA store.ca_file(a PEM path) replaces the system store: only the CAs in that file are trusted (a private CA or a self-signed server).cert_file+key_file(PEM) present a client certificate when the server requires one (mTLS): ECDSA P-256/P-384, Ed25519 or RSA (RSASSA-PSS) keys, unencrypted PEM.reconnect()keeps all three.- A non-empty
passwordsendsAUTH(AUTH username passwordwhenusernameis given);db > 0sendsSELECT. - Failure raises
RedisErrorwithkind == "connection".
connect_url(url, ca_file="", cert_file="", key_file="") -> Client connects from a connection URL, the form managed services (Upstash, Redis Cloud, ElastiCache, Azure Cache) hand out:
c: Client = nox.redis.connect_url("rediss://default:[email protected]:6380/2")redis:// is plain TCP, rediss:// starts TLS (system CA store unless ca_file). [user]:password@ becomes AUTH (a password alone: redis://:password@host; user and password may be percent-encoded, e.g. %40 for @); the path is the database number (/2); the port defaults to 6379. Another scheme, an empty host or a non-numeric database raises RedisError with kind == "connection"; the error message never contains the password.
Commands#
| Member | Description |
|---|---|
command(args: list[str]) -> Reply |
any Redis command; the arguments are binary-safe (NUL bytes and non-UTF-8 bytes are sent as is) |
ping(), get(key) -> str \| None, set(key, value), set_ex(key, value, seconds), delete(key), incr(key), expire(key, seconds) |
common commands |
xadd(stream, fields, maxlen=0) |
XADD (approximate MAXLEN ~ when maxlen > 0); returns the new entry id |
xgroup_create(stream, group, start_id="$", mkstream=True) / xgroup_ensure(...) |
XGROUP CREATE; xgroup_ensure returns False instead of raising when the group exists (BUSYGROUP) |
xreadgroup(group, consumer, stream, id=">", count=1, block_ms=-1) |
XREADGROUP; block_ms < 0 does not block, 0 blocks forever. A timeout returns a nil Reply |
xautoclaim(stream, group, consumer, min_idle_ms, start="0-0", count=100) |
XAUTOCLAIM: [next-id, [[id, [field, value, ...]], ...], [deleted ids]] |
xack(stream, group, ids) |
XACK; returns how many entries were acknowledged |
script_load(script), eval_cached(script, keys, args) |
SCRIPT LOAD + EVALSHA, caching the sha per connection; a NOSCRIPT reply (server restart, SCRIPT FLUSH) reloads the script and retries once |
set_read_timeout(ms) |
per-reply read deadline (0 = off, the default); see Read timeout below |
pipeline(commands: list[list[str]]) -> list[Reply] |
sends every command in one write, then reads the replies in order; a server error is the matching Reply (is_error()), not an exception |
is_ok(), reconnect(), close() |
connection management |
Replies#
A Reply is a tree: kind() is 0 nil, 1 simple string, 2 error, 3 integer, 4 bulk string, 5 array. as_str(), as_int(), len(), at(i) read it;
to_str_list() turns an array of strings into a list[str]. Bulk strings are byte-exact. A child returned by at(i) borrows the parent's memory and keeps the parent alive.
r: Reply = client.xreadgroup("workers", "w1", "jobs", ">", 10, 2000)
if not r.is_nil():
entry: Reply = r.at(0).at(1).at(0) # first entry of the first stream
print(entry.at(0).as_str(), entry.at(1).to_str_list())Errors#
RedisError has kind and code:
kind == "server": the server answered with an error (-WRONGTYPE ...).codeis its first word ("WRONGTYPE","NOSCRIPT","BUSYGROUP","NOAUTH","NOPERM"); helpersis_wrongtype(),is_noscript(),is_busygroup().kind == "timeout"(is_timeout(); alsois_connection_error()): a reply did not arrive withinset_read_timeout. The client is closed afterwards (a late reply must not be mistaken for the next command's): callreconnect().kind == "connection"(is_connection_error()): connecting failed, or the connection broke. The client is closed afterwards: callreconnect()(it repeatsAUTH/SELECTand clears the script cache). A command interrupted by a broken connection may or may not have run on the server; whether to retry is up to the caller.
Notes#
- Read timeout: off by default (blocking commands such as
XREADGROUP ... BLOCKlegitimately wait; inside a task only that task waits).set_read_timeout(ms)bounds every reply;xreadgroupadds its ownblock_msto the bound, soBLOCK 0is bounded by the timeout alone. Inside a fiber only that fiber is suspended. Onwasm32-freestanding --asyncifythe host bounds the TCP read (the request carriestimeout=<ms>); a host that ignores that field blocks as before. If the deadline passes, the late bytes stay with the host and are not lost, but the client is closed anyway. - RESP2 only; no pub/sub push messages. A single
Clienttalks to one node:MOVED/ASKsurface asRedisErrorthere; usenox.redis_clusterfor a Redis Cluster. - Verified against real
redis-serverfor commands, binary payloads, Streams, scripts,AUTH/ACL and reconnecting. TLS reuses the client ofnox.tls(an untrusted certificate is rejected); a successful handshake with a publicly trusted server certificate has not been exercised against a Redis in this repository's tests.