@kerf-js/realtime-redis 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ravonus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,315 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://github.com/Ravonus/kerf">
3
+ <img src="https://raw.githubusercontent.com/Ravonus/kerf/main/site/public/logo.svg" width="88" height="88" alt="Kerf">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <h1 align="center">@kerf-js/realtime-redis</h1>
8
+
9
+ <p align="center">
10
+ <strong>Redis pub/sub as Kerf's realtime bus, so live data reaches every instance of your app.</strong><br>
11
+ One line in <code>kerf.config.ts</code>, one <code>REDIS_URL</code>, and no change to your pages or server functions.
12
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/@kerf-js/realtime-redis"><img src="https://img.shields.io/npm/v/@kerf-js/realtime-redis?color=145c3c&label=npm" alt="npm version"></a>
16
+ <a href="https://github.com/Ravonus/kerf/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-145c3c" alt="MIT license"></a>
17
+ <a href="https://github.com/Ravonus/kerf/actions"><img src="https://img.shields.io/github/actions/workflow/status/Ravonus/kerf/quality.yml?branch=main&label=checks" alt="checks"></a>
18
+ </p>
19
+
20
+ <p align="center">
21
+ <a href="#quick-start">Quick start</a> ·
22
+ <a href="https://github.com/Ravonus/kerf/tree/main/docs">Docs</a> ·
23
+ <a href="https://github.com/Ravonus/kerf/tree/main/examples">Examples</a> ·
24
+ <a href="https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md">Changelog</a> ·
25
+ <a href="https://github.com/Ravonus/kerf">GitHub</a>
26
+ </p>
27
+
28
+ > [!IMPORTANT]
29
+ > **Early release (0.1.x).** APIs can change between minor versions. Pin the version and read the
30
+ > [changelog](https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md) before you upgrade.
31
+
32
+ On one server, Kerf's realtime needs nothing: messages, `.live()` pokes, channels and shared state go through a memory
33
+ bus inside the process. Run two instances and each one only reaches its own sockets, so a mutation on one never
34
+ refreshes a page connected to the other. This package fills the `realtime.bus` slot with Redis pub/sub, so every
35
+ instance hears every publish. It's for apps that already run Redis, or deploy to a host that runs several instances.
36
+
37
+ ## Highlights
38
+
39
+ - **A plugin, not code.** `redis()` in `plugins` replaces the memory bus. Nothing in `src/` changes.
40
+ - **Reads `REDIS_URL`.** The URL comes from the environment unless you pass `url`, so no secret lands in the config.
41
+ - **Several apps, one server.** Every channel name is prefixed (`kerf:` by default), so apps can share a Redis.
42
+ - **Lazy.** It opens no connection until the first publish or subscribe, and `kerf build` never connects.
43
+ - **Reconnects on its own.** ioredis retries forever and resubscribes. Each reconnect after the first is reported to
44
+ the hub as a gap, so clients know that messages may be missing.
45
+ - **Tested against a real server.** The test suite runs the shared `realtime.bus@1` conformance checks against a
46
+ `redis-server` it starts, then kills and restarts, to prove the gap and the resume.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ # npm
52
+ npm install @kerf-js/realtime-redis
53
+
54
+ # pnpm
55
+ pnpm add @kerf-js/realtime-redis
56
+
57
+ # bun
58
+ bun add @kerf-js/realtime-redis
59
+ ```
60
+
61
+ Or let the `kerf` CLI install it and add it to `kerf.config.ts` in one step:
62
+
63
+ ```bash
64
+ npx kerf add redis
65
+ ```
66
+
67
+ `kerf add` installs the package and adds the plugin to `kerf.config.ts`.
68
+
69
+ ## Quick start
70
+
71
+ 1. Run a Redis server. For local work:
72
+
73
+ ```bash
74
+ docker run --rm -p 6379:6379 redis
75
+ ```
76
+
77
+ 2. Add the plugin. `kerf add redis` writes this for you:
78
+
79
+ ```ts
80
+ // kerf.config.ts
81
+ import { defineConfig } from '@kerf-js/core/config'
82
+ import realtimeRedis from '@kerf-js/realtime-redis/plugin'
83
+
84
+ export default defineConfig({
85
+ plugins: [realtimeRedis()],
86
+ })
87
+ ```
88
+
89
+ `import { redis } from '@kerf-js/realtime-redis/plugin'` is the same function under its own name.
90
+
91
+ 3. Set the URL in the app's environment:
92
+
93
+ ```bash
94
+ # .env
95
+ REDIS_URL=redis://localhost:6379
96
+ ```
97
+
98
+ 4. Start two instances on different ports and open a page that reads a query with `.live()` on each. A mutation through
99
+ one refreshes the page on the other.
100
+
101
+ ## How it plugs into Kerf
102
+
103
+ Kerf's realtime hub keeps everything that has state (tags, topics, replay rings, cursors, presence) and hands the bus
104
+ three things to do: publish a string to a channel, subscribe to a channel, and close. That is the `Bus` interface in
105
+ [`@kerf-js/start/bus`](https://github.com/Ravonus/kerf/blob/main/packages/start/src/bus.ts). A bus is at-most-once and
106
+ ordered per publisher, like this one.
107
+
108
+ The plugin provides the `realtime.bus` slot (version 1, one provider, server side). At build time Kerf writes the slot
109
+ binding to `.kerf/slots/realtime.bus.ts`, and the server entry wraps it in a bus that loads this package on the first
110
+ publish or subscribe. The order of precedence is:
111
+
112
+ | Where the bus comes from | Wins over |
113
+ | --- | --- |
114
+ | `bus` in `src/realtime.server.ts` | everything: an explicit choice beats a plugin |
115
+ | a `realtime.bus` plugin in `kerf.config.ts` (this one, or `@kerf-js/realtime-nats`) | the memory bus |
116
+ | nothing | the memory bus, one process only |
117
+
118
+ So if `src/realtime.server.ts` already sets `bus: postgresBus(...)`, adding this plugin changes nothing until you take
119
+ that line out.
120
+
121
+ ### Using it without the plugin
122
+
123
+ `redisBus()` is a plain function, so you can set it in `src/realtime.server.ts` instead, next to the other realtime
124
+ options:
125
+
126
+ ```ts
127
+ // src/realtime.server.ts
128
+ import { realtime } from '@kerf-js/start'
129
+ import { redisBus } from '@kerf-js/realtime-redis'
130
+
131
+ export default realtime({
132
+ bus: redisBus({
133
+ url: process.env.REDIS_URL ?? '',
134
+ prefix: 'shop:',
135
+ }),
136
+ origins: ['https://admin.example.com'],
137
+ })
138
+ ```
139
+
140
+ Use this form when you want the bus next to `origins`, `limits` or `changes`, or when you build the URL from other
141
+ settings. The package still has to be installed.
142
+
143
+ ## Options
144
+
145
+ `redis(options)` in `kerf.config.ts` and `redisBus(options)` take the same options. The plugin passes them through to
146
+ `bus()`, which fills `url` from `REDIS_URL` when it's missing.
147
+
148
+ | Option | Type | Default | What it does |
149
+ | --- | --- | --- | --- |
150
+ | `url` | `string` | `process.env.REDIS_URL` (plugin and `bus()` only) | Server to connect to. Must start with `redis://` or `rediss://` (TLS). Required for `redisBus()`. |
151
+ | `prefix` | `string` | `'kerf:'` | Put in front of every Redis channel name. Give each app its own when apps share a server. |
152
+
153
+ The plugin's options end up in generated code, so keep them to plain values. Leave the password in `REDIS_URL` rather
154
+ than in `url`.
155
+
156
+ ### Environment
157
+
158
+ | Variable | Read by | Needed |
159
+ | --- | --- | --- |
160
+ | `REDIS_URL` | the plugin and `bus()` | At run time, unless `url` is given. `redis://user:pass@host:6379/0` or `rediss://…` for TLS. |
161
+ | `KERF_BUILD` | `redisBus()` | Set by `kerf build`. While it's set a missing URL is not an error, since a build loads the module but never connects. |
162
+
163
+ ### What the plugin declares
164
+
165
+ `kerf plugins` and the trust check show what a plugin may reach. This one declares:
166
+
167
+ | Permission | Value |
168
+ | --- | --- |
169
+ | `net` | `env:REDIS_URL`, the host in that variable |
170
+ | `env` | `REDIS_URL`, `KERF_BUILD` |
171
+
172
+ ## How it behaves
173
+
174
+ - **Two connections.** A Redis connection in subscribe mode can't publish, so the bus opens one for publishing and one
175
+ for subscribing, each on first use.
176
+ - **One Redis subscription per channel.** Several listeners on the same channel in one process share a single
177
+ `SUBSCRIBE`. The bus unsubscribes from Redis when the last one stops.
178
+ - **Errors don't crash the process.** Connection errors are swallowed and ioredis keeps retrying
179
+ (`maxRetriesPerRequest: null`), because an unhandled `error` event would end Node.
180
+ - **A reconnect is a gap.** Redis pub/sub keeps nothing for a subscriber that was away. Every `ready` after the first
181
+ calls the hub's `gap`, and the hub treats everything before it as outside the resume window. Clients refetch rather
182
+ than trust a stream with a hole in it.
183
+ - **`close()`** disconnects both connections. The next publish or subscribe connects again.
184
+
185
+ ## API reference
186
+
187
+ | Export | From | What it is |
188
+ | --- | --- | --- |
189
+ | `redisBus(options)` | `@kerf-js/realtime-redis` | A `Bus` over Redis pub/sub, connecting on first use. Throws Q013 without a `redis://` or `rediss://` URL, except during a build. |
190
+ | `bus(options?)` | `@kerf-js/realtime-redis` | The `realtime.bus` provider the plugin loads: `redisBus` with `url` defaulting to `REDIS_URL`. |
191
+ | `RedisBusOptions` | `@kerf-js/realtime-redis` | Type: `{ url: string; prefix?: string }`. |
192
+ | `redisStore(options?)` | `@kerf-js/realtime-redis` | The shared query cache on Redis: default-export it from `src/cache.server.ts`. Values are JSON with their `life` as a TTL; tag versions live in Redis, so every instance sees an invalidation. |
193
+ | `redisRateLimit(options?)` | `@kerf-js/realtime-redis` | Better Auth's rate limit on Redis, counted once across instances: `createAuth({ options: { rateLimit: { customStorage: redisRateLimit() } } })`. |
194
+ | `redisQueue(options?)` | `@kerf-js/realtime-redis` | The job queue on Redis: `defineJobs(jobs, { queue: redisQueue() })`. Jobs survive restarts and every instance works them, each claimed by one at a time; `dead(count?)` lists dead jobs, newest first (the last `deadLimit`, default 1000). |
195
+ | `RedisStoreOptions` | `@kerf-js/realtime-redis` | Type: `{ url?: string; prefix?: string }`. `url` defaults to `REDIS_URL`. |
196
+ | default export, `redis` | `@kerf-js/realtime-redis/plugin` | The plugin for `kerf.config.ts`. Takes the same options as `bus()`. |
197
+
198
+ The returned bus has `name: 'redis'`, `publish(channel, message)`, `subscribe(channel, on, gap?)` (resolves once Redis
199
+ confirms the subscription, with a function that stops it) and `close()`.
200
+
201
+ ## Recipes
202
+
203
+ ### The shared cache and sign-in limits on Redis
204
+
205
+ The bus carries realtime messages. The same Redis can also hold the query cache and auth's rate limit, so several
206
+ instances agree on both:
207
+
208
+ ```ts
209
+ // src/cache.server.ts
210
+ import { redisStore } from '@kerf-js/realtime-redis'
211
+ export default redisStore()
212
+ ```
213
+
214
+ ```ts
215
+ // src/auth.server.ts
216
+ import { redisRateLimit } from '@kerf-js/realtime-redis'
217
+ export default createAuth({
218
+ db,
219
+ secret,
220
+ options: {
221
+ ...options,
222
+ rateLimit: { customStorage: redisRateLimit() },
223
+ },
224
+ })
225
+ ```
226
+
227
+ ### Queued jobs on Redis
228
+
229
+ ```ts
230
+ // src/jobs.server.ts
231
+ import { defineJobs } from '@kerf-js/start/jobs'
232
+ import { redisQueue } from '@kerf-js/realtime-redis'
233
+
234
+ export default defineJobs(
235
+ { welcome: { run: ({ input }) => sendWelcome(input) } },
236
+ { queue: redisQueue() },
237
+ )
238
+ ```
239
+
240
+ Jobs are stored as JSON under `<prefix>q:`, so their input must be JSON too.
241
+
242
+ ### Several apps on one Redis
243
+
244
+ ```ts
245
+ // kerf.config.ts
246
+ import { defineConfig } from '@kerf-js/core/config'
247
+ import { redis } from '@kerf-js/realtime-redis/plugin'
248
+
249
+ export default defineConfig({
250
+ plugins: [redis({ prefix: 'billing:' })],
251
+ })
252
+ ```
253
+
254
+ ### TLS on a managed Redis
255
+
256
+ Most hosted Redis services give a `rediss://` URL. Use it as it is:
257
+
258
+ ```bash
259
+ REDIS_URL=rediss://default:secret@my-redis.example.com:6380
260
+ ```
261
+
262
+ ### Covering a gap in your own channel
263
+
264
+ The bus is at-most-once, and a reconnect can drop messages. Anything that must survive goes through a mutation, and a
265
+ channel's `collect` plus a history query fills in what a client missed. The
266
+ [live data guide](https://github.com/Ravonus/kerf/blob/main/site/content/learn/live-data.md) shows the pattern.
267
+
268
+ ## Limits
269
+
270
+ - **At-most-once.** Redis pub/sub has no history. A message published while an instance is disconnected is gone for
271
+ that instance; it gets a gap instead.
272
+ - **Plain pub/sub only.** It doesn't use Redis Streams, keyspace notifications or sharded pub/sub (`SPUBLISH`).
273
+ - **Messages are strings.** The hub serializes before publishing; the bus never parses.
274
+ - **Sizes are the hub's.** A message over 1 MiB is refused by the hub (R008) before it reaches Redis.
275
+
276
+ ## Troubleshooting
277
+
278
+ | Symptom | Cause | Fix |
279
+ | --- | --- | --- |
280
+ | `Q013` "`redisBus` needs a `redis://` URL" at startup | `REDIS_URL` is unset, or the URL has another scheme (`http://`, a bare host) | Set `REDIS_URL` to a `redis://` or `rediss://` URL, or pass `url`. Credentials are masked in the message. |
281
+ | `R002` from `kerf build` | The preset runs many instances and the app is still on the memory bus | Add this plugin, `@kerf-js/realtime-nats`, or `postgresBus` in `src/realtime.server.ts`. |
282
+ | `E009` from `kerf deploy` | The same problem, found for a deploy target | As above. |
283
+ | The plugin is listed but nothing crosses instances | `src/realtime.server.ts` sets its own `bus`, which wins | Remove that `bus`, or set `redisBus()` there. |
284
+ | Messages published while Redis was down never arrived | Pub/sub keeps nothing; the reconnect was reported as a gap | Expected. Put what must survive in a mutation, and refetch after a gap. |
285
+ | Two apps see each other's messages | Same server, same `prefix` | Give each app its own `prefix`. |
286
+
287
+ ## Related packages
288
+
289
+ | Package | What it is |
290
+ | --- | --- |
291
+ | [`@kerf-js/start`](https://www.npmjs.com/package/@kerf-js/start) | The full-stack runtime: the realtime hub, `realtime()`, `memoryBus` and `postgresBus` (`@kerf-js/start/bus/postgres`). |
292
+ | [`@kerf-js/realtime-nats`](https://www.npmjs.com/package/@kerf-js/realtime-nats) | The same slot on core NATS. |
293
+ | [`@kerf-js/realtime-durable-object`](https://www.npmjs.com/package/@kerf-js/realtime-durable-object) | The bus for Cloudflare, on Durable Objects. |
294
+ | [`@kerf-js/multiplayer`](https://www.npmjs.com/package/@kerf-js/multiplayer) | Presence, cursors and a relay on `channel`. Its traffic crosses instances through this bus. |
295
+ | [`@kerf-js/core`](https://www.npmjs.com/package/@kerf-js/core) | The plugin system (`definePlugin`, slots) and `busSuite`, the conformance checks a bus must pass. |
296
+
297
+ ## Contributing
298
+
299
+ See [CONTRIBUTING.md](https://github.com/Ravonus/kerf/blob/main/CONTRIBUTING.md). To test this package:
300
+
301
+ ```bash
302
+ pnpm --filter @kerf-js/realtime-redis test
303
+ ```
304
+
305
+ The test against a real server needs a `redis-server` binary. Name it in `KERF_TEST_REDIS`; without it that test is
306
+ skipped and says so:
307
+
308
+ ```bash
309
+ KERF_TEST_REDIS=$(command -v redis-server) \
310
+ pnpm --filter @kerf-js/realtime-redis test
311
+ ```
312
+
313
+ ## License
314
+
315
+ [MIT](https://github.com/Ravonus/kerf/blob/main/LICENSE)
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@kerf-js/realtime-redis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "@kerf-js/realtime-redis: the realtime.bus provider for Redis pub/sub",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Ravonus/kerf.git",
9
+ "directory": "packages/realtime-redis"
10
+ },
11
+ "homepage": "https://github.com/Ravonus/kerf/tree/main/packages/realtime-redis#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Ravonus/kerf/issues"
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ ".": "./src/index.ts",
18
+ "./plugin": "./plugin.mjs"
19
+ },
20
+ "dependencies": {
21
+ "ioredis": "6.0.0"
22
+ },
23
+ "peerDependencies": {
24
+ "@kerf-js/start": "^0.1.0",
25
+ "@kerf-js/core": "^0.1.0"
26
+ },
27
+ "engines": {
28
+ "node": ">=24"
29
+ },
30
+ "keywords": [
31
+ "kerf"
32
+ ],
33
+ "files": [
34
+ "src",
35
+ "plugin.mjs",
36
+ "plugin.d.mts",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
6
43
  }
package/plugin.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ declare const plugin: (options?: Record<string, unknown>) => PluginInstance<unknown>
4
+ /** `redis()` for `kerf.config.ts`: Redis as the `realtime.bus` provider, at `REDIS_URL`. */
5
+ export default plugin
package/plugin.mjs ADDED
@@ -0,0 +1,32 @@
1
+ // redis() for kerf.config.ts: this package as the `realtime.bus` provider. Listed here, it replaces the memory bus, and
2
+ // a bus set in `src/realtime.server.ts` still wins.
3
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
4
+
5
+ const slot = defineSlot({ id: 'realtime.bus', version: 1, cardinality: 'one', sides: ['server'] })
6
+
7
+ export const redis = definePlugin({
8
+ name: '@kerf-js/realtime-redis',
9
+ version: '0.1.0',
10
+ kerf: '*',
11
+ permissions: { net: ['env:REDIS_URL'], env: ['REDIS_URL', 'KERF_BUILD'] },
12
+ contribute: (options) => ({
13
+ provides: [
14
+ provide(slot, {
15
+ sides: { server: { module: '@kerf-js/realtime-redis', export: 'bus', options } },
16
+ }),
17
+ ],
18
+ agents: {
19
+ title: 'Realtime bus (Redis)',
20
+ text: '`realtime.bus` is Redis, at `REDIS_URL`. Rooms, shared state, `.live` and streams reach every instance. It is at-most-once: anything that must survive is a mutation, and `collect` plus a query covers a gap.',
21
+ },
22
+ map: [
23
+ {
24
+ want: 'Change the realtime bus',
25
+ call: 'replace this plugin in `plugins`, or set `bus` in `src/realtime.server.ts`',
26
+ have: 'Redis',
27
+ },
28
+ ],
29
+ }),
30
+ })
31
+
32
+ export default redis
package/src/index.ts ADDED
@@ -0,0 +1,84 @@
1
+ // Redis pub/sub (research 32 §6): two connections, because a subscriber can't publish. ioredis resubscribes after a
2
+ // reconnect, and whatever was published meanwhile is gone: every `ready` after the first is the `gap`.
3
+
4
+ import { Redis } from 'ioredis'
5
+ import type { Bus } from '@kerf-js/start/bus'
6
+ import { StartError } from '@kerf-js/start/data'
7
+
8
+ /** Options of `redisBus()`. */
9
+ export interface RedisBusOptions {
10
+ /** `redis://…` or `rediss://…`. */
11
+ url: string
12
+ /** Prefix of every Redis channel. Default `kerf:`: several apps can share a server. */
13
+ prefix?: string
14
+ }
15
+
16
+ /** A `Bus` over Redis pub/sub, connecting on first use. Throws Q013 without a `redis://` URL, except during a build. */
17
+ export function redisBus({ url, prefix = 'kerf:' }: RedisBusOptions): Bus {
18
+ if (!url && process.env.KERF_BUILD) url = 'redis://localhost' // a build loads this module and never connects
19
+ if (!/^rediss?:\/\//.test(url ?? ''))
20
+ throw new StartError(
21
+ 'Q013',
22
+ `\`redisBus\` needs a \`redis://\` URL, not \`${(url ?? '').replace(/\/\/.*@/, '//…@')}\``,
23
+ 'set the URL, or leave `bus` out for the memory bus on one instance',
24
+ )
25
+ let pub: Redis | undefined, sub: Redis | undefined
26
+ const listeners = new Map<string, Set<(message: string) => void>>()
27
+ const gaps = new Set<() => void>()
28
+ const opts = { maxRetriesPerRequest: null, lazyConnect: false }
29
+ const subscriber = () => {
30
+ if (sub) return sub
31
+ let connected = false
32
+ sub = new Redis(url, opts)
33
+ sub.on('error', () => {}) // ioredis retries; an unhandled `error` event would end the process
34
+ sub.on('ready', () => {
35
+ if (connected) for (const gap of gaps) gap()
36
+ connected = true
37
+ })
38
+ sub.on('message', (channel: string, message: string) => {
39
+ const list = listeners.get(channel)
40
+ if (list) for (const on of list) on(message)
41
+ })
42
+ return sub
43
+ }
44
+ const publisher = () => {
45
+ if (pub) return pub
46
+ pub = new Redis(url, opts)
47
+ pub.on('error', () => {})
48
+ return pub
49
+ }
50
+ return {
51
+ name: 'redis',
52
+ async publish(channel, message) {
53
+ await publisher().publish(prefix + channel, message)
54
+ },
55
+ async subscribe(channel, on, gap) {
56
+ const name = prefix + channel
57
+ let list = listeners.get(name)
58
+ if (!list) listeners.set(name, (list = new Set()))
59
+ list.add(on)
60
+ if (gap) gaps.add(gap)
61
+ if (list.size === 1) await subscriber().subscribe(name)
62
+ return () => {
63
+ list.delete(on)
64
+ if (gap) gaps.delete(gap)
65
+ if (list.size) return
66
+ listeners.delete(name)
67
+ void sub?.unsubscribe(name).catch(() => {})
68
+ }
69
+ },
70
+ close() {
71
+ sub?.disconnect()
72
+ pub?.disconnect()
73
+ sub = pub = undefined
74
+ return Promise.resolve()
75
+ },
76
+ }
77
+ }
78
+
79
+ /** The `realtime.bus` provider: `REDIS_URL` unless the plugin was given a `url`. */
80
+ export const bus = (options: Partial<RedisBusOptions> = {}) =>
81
+ redisBus({ ...options, url: options.url ?? process.env.REDIS_URL ?? '' })
82
+
83
+ export { redisRateLimit, redisStore, type RedisStoreOptions } from './store'
84
+ export { redisQueue, type RedisQueueOptions } from './queue'
package/src/queue.ts ADDED
@@ -0,0 +1,109 @@
1
+ // The job queue on Redis: `defineJobs(jobs, { queue: redisQueue() })`. Jobs survive a restart, and every instance
2
+ // works the same queue, each job claimed by one at a time.
3
+
4
+ import type { DeadJob, Queue, QueuedJob } from '@kerf-js/start/jobs'
5
+ import { connect, type RedisStoreOptions } from './store'
6
+
7
+ // The job's JSON is stored as given and never decoded in Lua (cjson would turn an empty array into an object):
8
+ // attempts and keys live in hashes of their own.
9
+ // KEYS: jobs (id → JSON), ready (sorted set by run-at ms), attempts (id → n), keyOf (id → key), key prefix, dead (list).
10
+
11
+ // ARGV: id, JSON, run-at, key ('' for none).
12
+ const PUSH = `
13
+ if ARGV[4] ~= '' then
14
+ if not redis.call('SET', KEYS[5] .. ARGV[4], ARGV[1], 'NX') then return 0 end
15
+ redis.call('HSET', KEYS[4], ARGV[1], ARGV[4])
16
+ end
17
+ redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
18
+ redis.call('ZADD', KEYS[2], ARGV[3], ARGV[1])
19
+ return 1
20
+ `
21
+ // Due jobs move their run-at to the lease's end, so no other instance claims them meanwhile, and count one attempt.
22
+ // ARGV: now, lease, max. Returns JSON, attempt, JSON, attempt, ...
23
+ const CLAIM = `
24
+ local ids = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[1], 'LIMIT', 0, tonumber(ARGV[3]))
25
+ local out = {}
26
+ for _, id in ipairs(ids) do
27
+ local raw = redis.call('HGET', KEYS[1], id)
28
+ if raw then
29
+ redis.call('ZADD', KEYS[2], tonumber(ARGV[1]) + tonumber(ARGV[2]), id)
30
+ out[#out + 1] = raw
31
+ out[#out + 1] = redis.call('HINCRBY', KEYS[3], id, 1)
32
+ else
33
+ redis.call('ZREM', KEYS[2], id)
34
+ end
35
+ end
36
+ return out
37
+ `
38
+ // ARGV: id, dead JSON ('' when it ran), dead limit.
39
+ const DROP = `
40
+ local key = redis.call('HGET', KEYS[4], ARGV[1])
41
+ if key then redis.call('DEL', KEYS[5] .. key) end
42
+ redis.call('HDEL', KEYS[1], ARGV[1])
43
+ redis.call('ZREM', KEYS[2], ARGV[1])
44
+ redis.call('HDEL', KEYS[3], ARGV[1])
45
+ redis.call('HDEL', KEYS[4], ARGV[1])
46
+ if ARGV[2] ~= '' then
47
+ redis.call('LPUSH', KEYS[6], ARGV[2])
48
+ redis.call('LTRIM', KEYS[6], 0, tonumber(ARGV[3]) - 1)
49
+ end
50
+ return 1
51
+ `
52
+
53
+ /** Options of `redisQueue()`. */
54
+ export interface RedisQueueOptions extends RedisStoreOptions {
55
+ /** How many dead jobs to keep (newest first, in `<prefix>q:dead`). Default 1000. */
56
+ deadLimit?: number
57
+ }
58
+
59
+ /**
60
+ * The job queue on Redis. Jobs are JSON (inputs must be too), due ones in a sorted set by when they may run; a
61
+ * claim moves a job's time to its lease's end, so if its instance dies it's due again then.
62
+ */
63
+ export function redisQueue(
64
+ options: RedisQueueOptions = {},
65
+ ): Queue & { dead(count?: number): Promise<DeadJob[]> } {
66
+ const prefix = `${options.prefix ?? 'kerf:'}q:`
67
+ const client = connect(options, 'redisQueue')
68
+ const keys = ['jobs', 'ready', 'attempts', 'keyOf', 'key:', 'dead'].map((k) => prefix + k)
69
+ const deadLimit = options.deadLimit ?? 1000
70
+ const drop = (job: QueuedJob, dead: string) =>
71
+ client().eval(DROP, 6, ...keys, job.id, dead, deadLimit)
72
+ return {
73
+ async push(job, key) {
74
+ const { attempt: _attempt, runAt: _runAt, ...stored } = job
75
+ const added = await client().eval(
76
+ PUSH,
77
+ 6,
78
+ ...keys,
79
+ job.id,
80
+ JSON.stringify(stored),
81
+ job.runAt,
82
+ key ?? '',
83
+ )
84
+ return added === 1
85
+ },
86
+ async claim(now, lease, max) {
87
+ const raw = (await client().eval(CLAIM, 6, ...keys, now, lease, max)) as (string | number)[]
88
+ const out: QueuedJob[] = []
89
+ for (let i = 0; i < raw.length; i += 2) {
90
+ const job = JSON.parse(raw[i] as string) as Omit<QueuedJob, 'attempt' | 'runAt'>
91
+ out.push({ ...job, attempt: Number(raw[i + 1]), runAt: now })
92
+ }
93
+ return out
94
+ },
95
+ async done(job) {
96
+ await drop(job, '')
97
+ },
98
+ async retry(job, runAt) {
99
+ await client().zadd(keys[1]!, 'XX', runAt, job.id)
100
+ },
101
+ async fail(job, error) {
102
+ await drop(job, JSON.stringify({ ...job, error, at: Date.now() } satisfies DeadJob))
103
+ },
104
+ async dead(count = 100) {
105
+ const raw = await client().lrange(keys[5]!, 0, count - 1)
106
+ return raw.map((r) => JSON.parse(r) as DeadJob)
107
+ },
108
+ }
109
+ }
package/src/store.ts ADDED
@@ -0,0 +1,116 @@
1
+ // The shared cache and auth's rate limit on Redis: every server instance reads the same values, so a mutation's
2
+ // invalidation on one reaches them all, and sign-in attempts count once however many servers there are.
3
+
4
+ import { Redis } from 'ioredis'
5
+ import type { Store, Stored } from '@kerf-js/start/cache'
6
+ import { StartError } from '@kerf-js/start/data'
7
+
8
+ /** Options of `redisStore()` and `redisRateLimit()`. */
9
+ export interface RedisStoreOptions {
10
+ /** `redis://…` or `rediss://…`. Default `REDIS_URL`. */
11
+ url?: string
12
+ /** Prefix of every key. Default `kerf:`: several apps can share a server. */
13
+ prefix?: string
14
+ }
15
+
16
+ export function connect(options: RedisStoreOptions, what: string) {
17
+ let url = options.url ?? process.env.REDIS_URL ?? ''
18
+ if (!url && process.env.KERF_BUILD) url = 'redis://localhost' // a build loads this module and never connects
19
+ if (!/^rediss?:\/\//.test(url))
20
+ throw new StartError(
21
+ 'Q013',
22
+ `\`${what}\` needs a \`redis://\` URL, not \`${url.replace(/\/\/.*@/, '//…@')}\``,
23
+ 'set `REDIS_URL`, or pass `url`',
24
+ )
25
+ let client: Redis | undefined
26
+ return () => {
27
+ if (client) return client
28
+ client = new Redis(url, { maxRetriesPerRequest: 2, lazyConnect: false })
29
+ client.on('error', () => {}) // ioredis retries; an unhandled `error` event would end the process
30
+ return client
31
+ }
32
+ }
33
+
34
+ // A tag's version comes from one counter that never repeats. A tag Redis doesn't have (never bumped, or evicted)
35
+ // gets a fresh number, so no stored value can match it: an evicted tag costs a miss, never a stale answer.
36
+ const VERSIONS = `
37
+ local out = {}
38
+ for i, key in ipairs(KEYS) do
39
+ local v = redis.call('GET', key)
40
+ if not v then
41
+ v = redis.call('INCR', ARGV[1])
42
+ redis.call('SET', key, v, 'NX')
43
+ v = redis.call('GET', key)
44
+ end
45
+ out[i] = tonumber(v)
46
+ end
47
+ return out
48
+ `
49
+ const BUMP = `
50
+ for _, key in ipairs(KEYS) do redis.call('SET', key, redis.call('INCR', ARGV[1])) end
51
+ return 0
52
+ `
53
+
54
+ const CONSUME = `
55
+ local n = redis.call('INCR', KEYS[1])
56
+ if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
57
+ if n > tonumber(ARGV[2]) then return redis.call('TTL', KEYS[1]) end
58
+ return -1
59
+ `
60
+
61
+ /** One call against `key` in a fixed window, on Redis: what `redisStore().consume` and `redisRateLimit()` share. */
62
+ async function count(client: Redis, key: string, rule: { window: number; max: number }) {
63
+ const wait = (await client.eval(
64
+ CONSUME,
65
+ 1,
66
+ key,
67
+ Math.max(1, Math.ceil(rule.window)),
68
+ rule.max,
69
+ )) as number
70
+ return wait < 0
71
+ ? { allowed: true, retryAfter: null }
72
+ : { allowed: false, retryAfter: Math.max(1, wait) }
73
+ }
74
+
75
+ /**
76
+ * The shared cache on Redis: `export default redisStore()` in `src/cache.server.ts`. Values are JSON (what a query
77
+ * already sends), kept until their `life` runs out; tags are versioned in Redis, so every instance sees a bump.
78
+ */
79
+ export function redisStore(options: RedisStoreOptions = {}): Store {
80
+ const prefix = options.prefix ?? 'kerf:'
81
+ const client = connect(options, 'redisStore')
82
+ const value = (k: string) => `${prefix}c:${k}`
83
+ const tag = (t: string) => `${prefix}t:${t}`
84
+ const counter = `${prefix}t#`
85
+ return {
86
+ async get(k) {
87
+ const raw = await client().get(value(k))
88
+ return raw ? (JSON.parse(raw) as Stored) : undefined
89
+ },
90
+ async set(k, v) {
91
+ const ms = Math.min(v.expires - Date.now(), 2 ** 31 - 1)
92
+ if (ms > 0) await client().set(value(k), JSON.stringify(v), 'PX', Math.ceil(ms))
93
+ },
94
+ async versions(tags) {
95
+ if (!tags.length) return []
96
+ return (await client().eval(VERSIONS, tags.length, ...tags.map(tag), counter)) as number[]
97
+ },
98
+ async bump(tags) {
99
+ if (tags.length) await client().eval(BUMP, tags.length, ...tags.map(tag), counter)
100
+ },
101
+ consume: (key, rule) => count(client(), `${prefix}rl:${key}`, rule),
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Better Auth's rate limit on Redis, so every instance counts the same attempts:
107
+ * `createAuth({ options: { rateLimit: { customStorage: redisRateLimit() } } })`. A fixed window per key.
108
+ */
109
+ export function redisRateLimit(options: RedisStoreOptions = {}) {
110
+ const prefix = options.prefix ?? 'kerf:'
111
+ const client = connect(options, 'redisRateLimit')
112
+ return {
113
+ consume: (key: string, rule: { window: number; max: number }) =>
114
+ count(client(), `${prefix}rl:${key}`, rule),
115
+ }
116
+ }