# Redis

Redis from the back end (and what speaks its protocol: Valkey, KeyDB,
Dragonfly, a managed one), over RESP written out in Mote on
[`tcp.open`](back-end.md#connections-of-its-own); or Upstash's REST API
behind the same calls, by the address alone. The common commands typed,
any command raw, pipelines, MULTI/EXEC, pub/sub, streams with consumer
groups; and what a product builds on them: a rate limiter, a lock with a
fencing token, cache-aside. An [extension](../extensions/README.md):
ordinary Mote in `extensions/redis/`. Back to the [map](README.md).

```mote
use "pkg:redis/redis.mote"

shape Profile
  name: string
  plan: string

// At most 5 tries a minute for each address; the profile kept for five minutes.
server fn signIn(email: string): string requires anyone
  let l = redisLimit(`signin:${email}`, 5, 60000)?
  if !l.allowed fail(`too many tries: wait ${l.retryAfter} s`, {kind: "limited", data: {retryAfter: l.retryAfter}})?
  return "ok"

server fn profile(id: string): Profile requires signedIn
  let hit: Profile? = redisCacheGet(`profile:${id}`)?
  if hit != none return hit
  let fresh: Profile = {name: "Ada", plan: "pro"}
  redisCachePut(`profile:${id}`, fresh, 300)?
  return fresh
```

```sh
REDIS_URL='rediss://default:…@redis-12345.c1.eu-west-1-2.ec2.redns.redis-cloud.com:12345' bun dist/server/main.js
```

**What was checked.** Every call runs against a stand-in
(`tests/redis_standin.mjs`) three times: over TCP in RESP3, over TLS, and
over Upstash's REST API, each giving the same answers
(`tests/all.sh real_svc_redis`); then pub/sub, a pop that waits, a
connection dropped before its reply, a server older than 6 (no `HELLO`:
RESP2 and `AUTH`), replies that come a byte at a time. The stand-in runs
the extension's three scripts by their text, as Redis would run their Lua.
**It has never met a real Redis or Upstash**; [one command](#checking-it-against-a-real-server)
runs the same calls against yours.

## The settings

One, `REDIS_URL`, a [secret](back-end.md#secrets):

| | |
|---|---|
| `redis://user:password@host:6379/2` | RESP over TCP; `/2` the database (0 unsaid). A password alone is `redis://:password@host`; the user is then `default`. |
| `rediss://…` | The same over TLS, the certificate checked against this machine's authorities, or `REDIS_CA` (PEM, an `env` setting), and the host's name. |
| `https://:<token>@<name>.upstash.io` | Upstash's REST API: its `UPSTASH_REDIS_REST_URL` with its `UPSTASH_REDIS_REST_TOKEN` as the password. |

In the query: `pool` (connections kept, 10), `idle` (ms one stands idle,
60 000), `pool_wait` (ms a call waits when all are out, 10 000; then
`busy`), `timeout` (ms each reply may take, 10 000), `addr` (connect to this
address, the certificate still the host's).

On connecting: `HELLO 3 AUTH user password SETNAME mote`, so replies are
RESP3 (maps, sets, doubles, pushes); a server older than 6, which has no
`HELLO`, is spoken to in RESP2 after `AUTH`. Then `SELECT` for a database
that is not 0. Values are text (UTF-8) both ways; an argument may be bytes,
sent as they are, but replies are read as text.

## The calls

| Call | Gives |
|---|---|
| `redisCall(["XADD", "s", "*", "k", "v"])` | Any command, as its words: its reply (`none`, a text, a number, a list, a record). An error reply fails. |
| `redisPipe([[…], […]])` | Several commands written at once and their replies read after: one round trip, not one transaction. An error reply is `{error}` in its place. |
| `redisMulti([[…], […]])` | MULTI … EXEC: the replies, or a failure when one was refused before it ran (`aborted`). One that fails as it runs is `{error}` in its place. |
| `redisGet(k)` · `redisSet(k, v, {ex, px, nx, xx, keepTtl}?)` | A text or none; whether it was set (`nx`: only if it is not there; `xx`: only if it is). |
| `redisDel(keys)` · `redisExists(k)` · `redisIncr(k, by?)` · `redisExpire(k, s)` · `redisTtl(k)` | |
| `redisHset(k, record)` · `redisHget(k, f)` · `redisHgetall(k)` · `redisHdel(k, fields)` · `redisHincr(k, f, by)` | A hash; `redisHgetall` a record of texts. |
| `redisPush(k, values, left?)` · `redisPop(k, left?)` · `redisRange(k, start, stop)` · `redisLen(k)` · `redisWaitPop(keys, seconds)` | A list; `redisWaitPop` is BLPOP, on a connection of its own: `{key, value}` or none. |
| `redisSadd` · `redisSrem` · `redisMembers` · `redisIsMember` | A set. |
| `redisZadd(k, [{member, score}])` · `redisZrange(k, start, stop, rev?)` · `redisZbyScore(k, min, max)` · `redisZincr` · `redisZscore` · `redisZrem` | A sorted set; ranges as `[{member, score}]`. |
| `redisXadd(s, record, maxlen?)` · `redisXlen` · `redisXrange(s, "-", "+", count)` · `redisXgroup(s, group, "0")` · `redisXreadGroup(s, group, consumer, count, blockMs)` · `redisXack(s, group, ids)` | A stream: entries as `[{id, fields}]`; a group made with its stream, one already there being fine. |
| `redisPublish(ch, m)` · `redisSubscribe(channels, patterns)` · `redisMessage(sub, ms)` · `redisUnsubscribe(sub)` | Pub/sub ([below](#pubsub)). |
| `redisLimit(key, most, windowMs)` | A sliding window: `{allowed, count, retryAfter}` (seconds). |
| `redisLock(name, ttlMs)` · `redisUnlock(lock)` · `redisExtend(lock, ttlMs)` | A lock ([below](#a-lock-and-its-fencing-token)). |
| `redisCacheGet(k)` · `redisCachePut(k, value, seconds)` · `redisCacheDrop(k)` | Cache-aside: a value kept as JSON. |
| `redisPools()` | How the pools stand. |

**The kinds of failure.** An error reply's first word: `wrongtype`,
`auth` (NOAUTH, WRONGPASS, NOPERM), `busy` (BUSY, LOADING, TRYAGAIN, and a
pool with none to give), `cluster` (MOVED, ASK, CROSSSLOT: this client does
not follow a cluster), `full` (OOM), `readonly` (a replica), `aborted`,
`noscript`, else `redis`; and the connection's: `offline`, `timeout`,
`tls`, `refused`, `lookup`. Over REST: `auth` (401, 403), `limited` (429),
`offline`.

**A connection that breaks before its reply** is closed and the call
fails (`offline`), but a pooled connection that had stood idle is tried
again on a new one when every command only reads (GET, HGETALL, LRANGE …):
a write is never sent twice.

### Pub/sub

```text
let sub = redisSubscribe(["news"], ["orders.*"])?
while true
  let m = redisMessage(sub, 30000)?        // {channel, message, pattern}, or none in that time
  if m != none
    emit("heard", m.message)
```

A subscription has a connection of its own, which it holds; `redisMessage`
fails when that connection broke: subscribe again after a pause (a `server
start` that `detach`es a loop, as Postgres's
[LISTEN](postgres.md#listen-and-notify) is). Over REST there is none
(Upstash's subscription is a stream of events of its own).

### A lock and its fencing token

`redisLock(name, ttlMs)` takes the lock if nobody holds it (`SET NX PX`)
and gives `{name, token, fence}`, or `none`. `fence` is a number that is
larger for every later holder: a lock that ran out while its holder was
paused (a long garbage collection, a slow disk) is then held by another,
and the first holder's late write carries a smaller fence than the second's.
**Give the fence to what the lock guards and let it refuse a smaller one**:
`update … set …, fence = $2 where id = $1 and fence < $2`. Without that,
no lock in Redis keeps two holders from writing. `redisUnlock` and
`redisExtend` change it only if it is still this holder's (its token): a
script, so the check and the change are one.

### Scripts

`redisLimit`, `redisLock`, `redisUnlock` and `redisExtend` are `EVAL` of
short Lua scripts (in `redis.mote`, as text): one round trip each, done in
the server as one. A server that runs no scripts (some managed ones) refuses
them (`noscript` or `redis`).

## Checking it against a real server

```sh
cd mote
(cd compiler && cargo build)
MOTE_REDIS_URL='rediss://default:password@host:6379' tests/all.sh real_redis_live
MOTE_REDIS_URL='https://:token@name.upstash.io' tests/all.sh real_redis_live
```

Every key it writes begins `mote_test_<random>:`; it removes them at the
end, and nothing else is read or written. Its output must be what
`tests/expect/real_redis_live.txt` holds. It needs Redis 6.2 or later
(`ZRANGE … REV`, `BYSCORE`). Over REST the subscription and the pop that
waits are refused with their sentences, so the last lines differ there.

## What it leaves out

- **Cluster**: MOVED and ASK are failures (`cluster`); one node, or a
  proxy before the cluster (Envoy, a managed one's single endpoint).
- **Sentinel** and a replica chosen by role.
- **Client-side caching** (RESP3's tracking), `MONITOR`, `WATCH` across
  calls (a pooled connection is not the caller's for long enough).
- **Binary replies**: a reply is read as UTF-8 text.
- Streams' `XAUTOCLAIM`, `XPENDING`, `XINFO` have no helper: `redisCall`.
