redis
The redis package is a Redis (and Valkey) client for tasks: a pool of connections that every task shares, the everyday commands as functions, any other command through cmd, pipelines (several commands in one round trip), and publish / subscribe. It is written in Tern on top of net.
import redis
fn main():
r = redis.connect("redis://localhost:6379")
if not r.ok():
print("can't connect:", redis.error())
return
r.set_ex("session:abc", "user 7", 3600) # expires in an hour
print(r.get_str("session:abc"))
print(r.incr("page:views"))Connecting
fn connect(url: str) Client a pool of 8 connections
fn pool(url: str, size: int) Client
fn ok(c: Client) bool
fn error() strThe URL is redis://[:password@]host[:port][/db] (port 6379 and database 0 by default), or rediss://... for TLS, which needs import tls and checks the server's certificate (use tls.trust(ca_file) for a private CA, as managed Redis services often have). The connections open right away, so c.ok() reports a wrong address or password. A connection that breaks fails the calls waiting on it and is dialed again on its next use. The tasks on one thread share one of the pool's connections, so the commands of tasks woken by one batch of replies go out together in one write (and a reply never crosses threads). A Client is a handle: copy it into tasks and closures freely; after c.close() every call fails.
When a call fails, it returns "", false, 0 or -1, and redis.error() says why: the server's message (ERR unknown command 'X', WRONGTYPE ...) or a connection problem. The message is set at the very end of the failing call, so the task that made the call reads its own message even while other tasks use Redis on the same thread. After a call that succeeds, redis.error() is "".
Commands
fn get_str(c, key: str) str "" if the key doesn't exist (see exists)
fn set_str(c, key: str, value: str) bool
fn set_ex(c, key: str, value: str, seconds: int) bool
fn set_nx(c, key: str, value: str) bool only if the key doesn't exist yet (a simple lock)
fn del(c, key: str) int keys removed
fn exists(c, key: str) bool
fn incr(c, key: str) int fn incr_by(c, key: str, n: int) int
fn expire(c, key: str, seconds: int) bool fn ttl(c, key: str) int
fn mget(c, keys: [str]) [str]
fn publish(c, channel: str, message: str) int subscribers that got it(get and set are builtin names in Tern, hence get_str and set_str.)
Every other command goes through cmd, which returns a Reply: kind is "str", "int", "array", "nil" or "error", with the value in text, num or items:
fn cmd(c, args: [str]) Reply
fn pipeline(c, cmds: [[str]]) [Reply]import redis
fn main():
r = redis.connect("redis://localhost:6379")
r.cmd(["HSET", "user:7", "name", "Ada", "lang", "tern"])
fields = r.cmd(["HGETALL", "user:7"]).items
for i in 0..len(fields) / 2:
print(fields[2 * i].text, "=", fields[2 * i + 1].text)
counts = r.pipeline([["INCR", "a"], ["INCR", "b"], ["MGET", "a", "b"]])
print(counts[2].items[0].text, counts[2].items[1].text)Publish / subscribe
fn subscribe(c, channels: [str]) Subscription
fn next(s: Subscription, m: mut Message) bool
fn close(s: Subscription)A subscription has a connection of its own. Channel names with * or ? are patterns (PSUBSCRIBE). sub.next(&m) waits (only its task) for the next message, whose fields are channel and data, and returns false once the subscription is closed or its connection drops.
import redis
import task
fn main():
r = redis.connect("redis://localhost:6379")
sub = r.subscribe(["chat", "events.*"])
m = redis.Message("", "")
while sub.next(&m):
print(m.channel, m.data)With Result
fn try_get(c: Client, key: str) Result[Option[str], str] None: no such key
fn try_cmd(c: Client, args: [str]) Result[Reply, str]try_get tells a missing key (Ok(None)) from an empty value (Ok(Some(""))) and from a failure (Err("redis: connection lost")); try_cmd turns an error reply into Err("redis: command failed: WRONGTYPE ...").
Performance
See bench/std/results.md (tern run bench/std/run.tn -- redis, against the Rust redis crate and Go's go-redis).