@cslug/redis 0.0.0-stage → 0.2.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/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @cslug/redis
2
2
 
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.
3
+ Redis connections through `Bun.redis`, and Redis drivers for core's `Cache`, `Lock`, `RateLimiter` and
4
+ `SessionStore`. List `RedisProvider` in `bootstrap/providers.ts`.
5
+
6
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
7
+ [guide 10](../../guides/10-cache.md).
package/docs/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # @cslug/redis
2
+
3
+ ```ts
4
+ // config/redis.ts
5
+ export default defineConfig({ connections: { default: { url: env.REDIS_URL } }, prefix: 'albastr:' })
6
+ ```
7
+
8
+ `RedisProvider` binds `Redis` (the default connection) and, unless `cache.default` / `session.store` say
9
+ `memory`, the Redis drivers:
10
+
11
+ | Contract | Redis |
12
+ |---|---|
13
+ | `Cache` | `cache:<key>`, JSON that keeps `bigint` and `Date`; counters are `INCRBY` (ttl on creation, in Lua); tags are sets; `flush()` deletes only this prefix (SCAN + UNLINK) |
14
+ | `Lock` | `SET lock:<key> <token> NX PX`; released by its owner only (Lua compare-and-delete) |
15
+ | `RateLimiter` | sliding window: a sorted set per key, in one Lua call (concurrent hits never exceed the limit) |
16
+ | `SessionStore` | `session:<id>` with the session lifetime |
17
+
18
+ The memory drivers in core and these pass the **same contract tests** (`packages/redis/tests/contract.ts`).
19
+
20
+ Boot pings Redis and fails after `connectTimeout` (default 5 s). The `redis` health check is in `/health/ready`.
21
+ `redis.dedicated()` opens a separate connection with `autoReconnect: false`, for blocking loops such as queue
22
+ workers (see spikes/c-redis-streams).
package/docs/api.md ADDED
@@ -0,0 +1,9 @@
1
+ # @cslug/redis: API
2
+
3
+ | | |
4
+ |---|---|
5
+ | `Redis` | `key(k)` (prefixed), `send(cmd, args)`, `eval(script, keys, args)` (EVALSHA, reloads on NOSCRIPT, prefixes keys), `ping()`, `scan(pattern)`, `withPrefix(extra)`, `dedicated()`, `close()` |
6
+ | `RedisConnections` | `get(name)`: the named connections of `config('redis.connections')` |
7
+ | `RedisCache`, `RedisLock`, `RedisRateLimiter`, `RedisSessionStore` | Drivers (bound by the provider) |
8
+ | `encode` / `decode` | JSON keeping `bigint` and `Date` |
9
+ | `RedisProvider` | Config: `redis.connections.<name>.{url, prefix, connectTimeout}`, `redis.prefix`, `cache.default`, `cache.prefix`, `cache.stores`, `session.store` |
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@cslug/redis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Redis connections and Redis drivers for cache, locks, rate limits and sessions.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/redis"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/redis",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework"
17
+ ],
18
+ "exports": {
19
+ ".": "./src/index.ts"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "docs",
24
+ "stubs",
25
+ "README.md"
26
+ ],
27
+ "engines": {
28
+ "bun": ">=1.3.14"
29
+ },
30
+ "peerDependencies": {
31
+ "@cslug/core": "0.2.0"
32
+ }
33
+ }
package/src/drivers.ts ADDED
@@ -0,0 +1,160 @@
1
+ import {
2
+ Cache,
3
+ type Duration,
4
+ Lock,
5
+ type LockHandle,
6
+ parseDuration,
7
+ parseRate,
8
+ type RateLimit,
9
+ RateLimiter,
10
+ type RateLimitResult,
11
+ type SessionData,
12
+ SessionStore,
13
+ } from '@cslug/core'
14
+ import { decode, encode, type Redis } from './redis'
15
+
16
+ const ms = (ttl: Duration) => Math.max(1, Math.round(parseDuration(ttl)))
17
+
18
+ // ── Cache ────────────────────────────────────────────────────────────────────────────────────────────
19
+ const INCREMENT = `
20
+ local v = redis.call('INCRBY', KEYS[1], ARGV[1])
21
+ if tonumber(ARGV[2]) > 0 and redis.call('PTTL', KEYS[1]) == -1 and v == tonumber(ARGV[1]) then redis.call('PEXPIRE', KEYS[1], ARGV[2]) end
22
+ return v`
23
+
24
+ /** Cache in Redis: `cache:<key>`. Tags keep a set of their keys, so `tags([...]).flush()` removes only those. */
25
+ export class RedisCache extends Cache {
26
+ constructor(
27
+ private readonly redis: Redis,
28
+ private readonly ownTags: readonly string[] = [],
29
+ ) {
30
+ super()
31
+ }
32
+ private k = (key: string) => `cache:${key}`
33
+
34
+ async get<T>(key: string): Promise<T | undefined> {
35
+ const raw = (await this.redis.send('GET', [this.redis.key(this.k(key))])) as string | null
36
+ // counters are stored as plain integers (INCRBY)
37
+ if (raw !== null && /^-?\d+$/.test(raw)) return Number(raw) as T
38
+ return decode<T>(raw)
39
+ }
40
+ async set(key: string, value: unknown, ttl?: Duration): Promise<void> {
41
+ const args: (string | number)[] = [this.redis.key(this.k(key)), encode(value)]
42
+ if (ttl !== undefined) args.push('PX', ms(ttl))
43
+ await this.redis.send('SET', args)
44
+ await this.index(key)
45
+ }
46
+ async has(key: string): Promise<boolean> {
47
+ return (await this.redis.send('EXISTS', [this.redis.key(this.k(key))])) === 1
48
+ }
49
+ async forget(key: string): Promise<void> {
50
+ await this.redis.send('DEL', [this.redis.key(this.k(key))])
51
+ }
52
+ async increment(key: string, by = 1, ttl?: Duration): Promise<number> {
53
+ const v = Number(await this.redis.eval(INCREMENT, [this.k(key)], [by, ttl === undefined ? 0 : ms(ttl)]))
54
+ await this.index(key)
55
+ return v
56
+ }
57
+ async flush(): Promise<void> {
58
+ if (!this.ownTags.length) {
59
+ // only this app's cache keys (the prefix), never the whole database
60
+ const keys: string[] = []
61
+ for await (const k of this.redis.scan('cache:*')) keys.push(k)
62
+ for await (const k of this.redis.scan('cache-tag:*')) keys.push(k)
63
+ for (let i = 0; i < keys.length; i += 500) await this.redis.send('UNLINK', keys.slice(i, i + 500))
64
+ return
65
+ }
66
+ for (const tag of this.ownTags) {
67
+ const set = this.redis.key(`cache-tag:${tag}`)
68
+ const keys = (await this.redis.send('SMEMBERS', [set])) as string[]
69
+ if (keys.length)
70
+ await this.redis.send(
71
+ 'UNLINK',
72
+ keys.map((k) => this.redis.key(this.k(k))),
73
+ )
74
+ await this.redis.send('UNLINK', [set])
75
+ }
76
+ }
77
+ tags(tags: readonly string[]): Cache {
78
+ return new RedisCache(this.redis, tags)
79
+ }
80
+ private async index(key: string): Promise<void> {
81
+ for (const tag of this.ownTags) await this.redis.send('SADD', [this.redis.key(`cache-tag:${tag}`), key])
82
+ }
83
+ }
84
+
85
+ // ── Lock ─────────────────────────────────────────────────────────────────────────────────────────────
86
+ const RELEASE = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end`
87
+
88
+ /** `SET lock:<key> <token> NX PX ttl`; released only by its owner (Lua compare-and-delete). */
89
+ export class RedisLock extends Lock {
90
+ constructor(private readonly redis: Redis) {
91
+ super()
92
+ }
93
+ async acquire(key: string, ttl: Duration): Promise<LockHandle | null> {
94
+ const token = crypto.randomUUID()
95
+ const ok = await this.redis.send('SET', [this.redis.key(`lock:${key}`), token, 'NX', 'PX', ms(ttl)])
96
+ if (ok !== 'OK') return null
97
+ return {
98
+ key,
99
+ token,
100
+ release: async () => {
101
+ await this.redis.eval(RELEASE, [`lock:${key}`], [token])
102
+ },
103
+ }
104
+ }
105
+ }
106
+
107
+ // ── RateLimiter ──────────────────────────────────────────────────────────────────────────────────────
108
+ // sliding window: a sorted set of hit times; returns { allowed, count, oldest }
109
+ const HIT = `
110
+ local now, window, max = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
111
+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - window)
112
+ local count = redis.call('ZCARD', KEYS[1])
113
+ local allowed = 0
114
+ if count < max then
115
+ redis.call('ZADD', KEYS[1], now, ARGV[4])
116
+ count = count + 1
117
+ allowed = 1
118
+ end
119
+ redis.call('PEXPIRE', KEYS[1], window)
120
+ local oldest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
121
+ return { allowed, count, oldest[2] or now }`
122
+
123
+ export class RedisRateLimiter extends RateLimiter {
124
+ constructor(private readonly redis: Redis) {
125
+ super()
126
+ }
127
+ async hit(key: string, limit: RateLimit): Promise<RateLimitResult> {
128
+ const { max, windowMs } = parseRate(limit)
129
+ const now = Date.now()
130
+ const [allowed, count, oldest] = (await this.redis.eval(
131
+ HIT,
132
+ [`rate:${key}`],
133
+ [now, windowMs, max, `${now}-${crypto.randomUUID()}`],
134
+ )) as [number, number, string | number]
135
+ return {
136
+ allowed: allowed === 1,
137
+ remaining: Math.max(0, max - Number(count)),
138
+ retryAfter: allowed === 1 ? 0 : Math.ceil((Number(oldest) + windowMs - now) / 1000),
139
+ }
140
+ }
141
+ async reset(key: string): Promise<void> {
142
+ await this.redis.send('DEL', [this.redis.key(`rate:${key}`)])
143
+ }
144
+ }
145
+
146
+ // ── SessionStore ─────────────────────────────────────────────────────────────────────────────────────
147
+ export class RedisSessionStore extends SessionStore {
148
+ constructor(private readonly redis: Redis) {
149
+ super()
150
+ }
151
+ async read(id: string): Promise<SessionData | undefined> {
152
+ return decode<SessionData>((await this.redis.send('GET', [this.redis.key(`session:${id}`)])) as string | null)
153
+ }
154
+ async write(id: string, data: SessionData, ttl: Duration): Promise<void> {
155
+ await this.redis.send('SET', [this.redis.key(`session:${id}`), encode(data), 'PX', ms(ttl)])
156
+ }
157
+ async destroy(id: string): Promise<void> {
158
+ await this.redis.send('DEL', [this.redis.key(`session:${id}`)])
159
+ }
160
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @cslug/redis: Redis connections (`Bun.redis`) with a key prefix and Lua helper, and Redis drivers for
3
+ * core's `Cache`, `Lock`, `RateLimiter` and `SessionStore`.
4
+ */
5
+ export { RedisCache, RedisLock, RedisRateLimiter, RedisSessionStore } from './drivers'
6
+ export { RedisConnections, RedisProvider } from './provider'
7
+ export { decode, encode, Redis, type RedisConfig, type RedisConnectionConfig } from './redis'
@@ -0,0 +1,84 @@
1
+ import {
2
+ Cache,
3
+ CslugError,
4
+ HEALTH_CHECKS,
5
+ healthCheck,
6
+ Lock,
7
+ RateLimiter,
8
+ ServiceProvider,
9
+ SessionStore,
10
+ } from '@cslug/core'
11
+ import { RedisCache, RedisLock, RedisRateLimiter, RedisSessionStore } from './drivers'
12
+ import { Redis, type RedisConfig } from './redis'
13
+
14
+ /** All named connections: `resolve(RedisConnections).get('default')`. */
15
+ export class RedisConnections {
16
+ private readonly open = new Map<string, Redis>()
17
+ constructor(private readonly config: RedisConfig) {}
18
+
19
+ get(name = 'default'): Redis {
20
+ let r = this.open.get(name)
21
+ if (!r) {
22
+ const c = this.config.connections?.[name]
23
+ if (!c?.url)
24
+ throw new CslugError(
25
+ 'redis.no_connection',
26
+ `config/redis.ts has no connection "${name}" (connections.${name}.url)`,
27
+ )
28
+ r = new Redis(c.url, c.prefix ?? this.config.prefix ?? '', { connectTimeout: c.connectTimeout })
29
+ this.open.set(name, r)
30
+ }
31
+ return r
32
+ }
33
+ closeAll(): void {
34
+ for (const r of this.open.values()) r.close()
35
+ this.open.clear()
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Binds `Redis` (the default connection) and Redis drivers for core's `Cache`, `Lock`, `RateLimiter` and
41
+ * `SessionStore`, unless config picks `memory` (`cache.default`, `session.store`). Adds the `redis` health check.
42
+ */
43
+ export class RedisProvider extends ServiceProvider {
44
+ register() {
45
+ const config = this.app.config<RedisConfig | undefined>('redis') ?? {}
46
+ this.app.singleton(RedisConnections, () => new RedisConnections(config))
47
+ this.app.singleton(Redis, (c) => c.resolve(RedisConnections).get('default'))
48
+ const cache = this.app.config<
49
+ | { default?: string; prefix?: string; stores?: Record<string, { driver?: string; connection?: string }> }
50
+ | undefined
51
+ >('cache')
52
+ const store = cache?.stores?.[cache.default ?? 'redis']
53
+ const driver = store?.driver ?? cache?.default ?? 'redis'
54
+ const connection = (c: { resolve: (t: typeof RedisConnections) => RedisConnections }) => {
55
+ const base = c.resolve(RedisConnections).get(store?.connection ?? 'default')
56
+ return base.withPrefix(cache?.prefix ?? '')
57
+ }
58
+ if (driver === 'redis') {
59
+ this.app.singleton(Cache, (c) => new RedisCache(connection(c)))
60
+ this.app.singleton(Lock, (c) => new RedisLock(connection(c)))
61
+ this.app.singleton(RateLimiter, (c) => new RedisRateLimiter(connection(c)))
62
+ }
63
+ if ((this.app.config<string | undefined>('session.store') ?? 'redis') === 'redis') {
64
+ this.app.singleton(SessionStore, (c) => new RedisSessionStore(connection(c)))
65
+ }
66
+ const check = healthCheck('redis')
67
+ this.app.singleton(check, (c) => ({ name: 'redis', check: () => c.resolve(Redis).ping() }))
68
+ this.app.tag([check], HEALTH_CHECKS)
69
+ }
70
+
71
+ async boot() {
72
+ try {
73
+ await this.app.resolve(Redis).ping()
74
+ } catch (error) {
75
+ // shutdown() is not called for a provider whose boot failed: don't leave a reconnecting client behind
76
+ this.app.resolve(RedisConnections).closeAll()
77
+ throw error
78
+ }
79
+ }
80
+
81
+ shutdown() {
82
+ this.app.resolve(RedisConnections).closeAll()
83
+ }
84
+ }
package/src/redis.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { parseDuration } from '@cslug/core'
2
+ import { RedisClient } from 'bun'
3
+
4
+ export type RedisConnectionConfig = {
5
+ url: string
6
+ prefix?: string
7
+ /** How long `ping()` (boot, `/health/ready`) waits for an answer. Default `'5s'`. */
8
+ connectTimeout?: string | number
9
+ }
10
+ export type RedisConfig = {
11
+ connections?: Record<string, RedisConnectionConfig>
12
+ /** Prefix for every key cslug writes (default: none). */
13
+ prefix?: string
14
+ }
15
+
16
+ type Reply = unknown
17
+
18
+ /**
19
+ * A Redis connection (`Bun.redis`, RESP3) with a key prefix and a Lua helper. One per named connection;
20
+ * blocking readers (queue workers) take their own with `dedicated()`.
21
+ */
22
+ export class Redis {
23
+ readonly client: RedisClient
24
+ private readonly shas = new Map<string, string>()
25
+
26
+ constructor(
27
+ readonly url: string,
28
+ readonly prefix = '',
29
+ readonly options: { autoReconnect?: boolean; connectTimeout?: string | number } = {},
30
+ client?: RedisClient,
31
+ ) {
32
+ this.client =
33
+ client ?? new RedisClient(url, { autoReconnect: options.autoReconnect ?? true, enableOfflineQueue: true })
34
+ }
35
+
36
+ /** The same connection with a longer prefix (`cache.prefix`). */
37
+ withPrefix(extra: string): Redis {
38
+ return extra ? new Redis(this.url, this.prefix + extra, this.options, this.client) : this
39
+ }
40
+
41
+ /** The key with the prefix. */
42
+ key(key: string): string {
43
+ return this.prefix + key
44
+ }
45
+
46
+ send(command: string, args: (string | number)[] = []): Promise<Reply> {
47
+ return this.client.send(command, args.map(String))
48
+ }
49
+
50
+ /**
51
+ * Run a Lua script: `EVALSHA`, loading it on first use and again after `NOSCRIPT` (a restarted Redis).
52
+ * Keys are prefixed here.
53
+ */
54
+ async eval(script: string, keys: string[], args: (string | number)[] = []): Promise<Reply> {
55
+ let sha = this.shas.get(script)
56
+ if (!sha) {
57
+ sha = (await this.send('SCRIPT', ['LOAD', script])) as string
58
+ this.shas.set(script, sha)
59
+ }
60
+ const call = () => this.send('EVALSHA', [sha as string, keys.length, ...keys.map((k) => this.key(k)), ...args])
61
+ try {
62
+ return await call()
63
+ } catch (error) {
64
+ if (!String(error).includes('NOSCRIPT')) throw error
65
+ this.shas.delete(script)
66
+ return this.eval(script, keys, args)
67
+ }
68
+ }
69
+
70
+ /** Fails after `connectTimeout` instead of waiting for a server that is not there (commands queue offline). */
71
+ async ping(): Promise<void> {
72
+ const timeout = parseDuration(this.options.connectTimeout ?? '5s')
73
+ const reply = await Promise.race([
74
+ this.send('PING'),
75
+ Bun.sleep(timeout).then(() => {
76
+ throw new Error(`Redis at ${new URL(this.url).host} did not answer within ${timeout} ms`)
77
+ }),
78
+ ])
79
+ if (reply !== 'PONG') throw new Error(`Redis PING answered ${String(reply)}`)
80
+ }
81
+
82
+ /**
83
+ * A new connection to the same server for a blocking loop (queue workers): never shared with other commands,
84
+ * and `autoReconnect: false`, so a dropped connection fails at once instead of hanging (spike c). The caller
85
+ * reconnects by asking for another.
86
+ */
87
+ dedicated(): Redis {
88
+ return new Redis(this.url, this.prefix, { ...this.options, autoReconnect: false })
89
+ }
90
+
91
+ /** Every key under the prefix matching `pattern` (SCAN, never KEYS). */
92
+ async *scan(pattern: string): AsyncGenerator<string> {
93
+ let cursor = '0'
94
+ do {
95
+ const [next, keys] = (await this.send('SCAN', [cursor, 'MATCH', this.key(pattern), 'COUNT', 500])) as [
96
+ string,
97
+ string[],
98
+ ]
99
+ cursor = next
100
+ for (const k of keys) yield k
101
+ } while (cursor !== '0')
102
+ }
103
+
104
+ close(): void {
105
+ this.client.close()
106
+ }
107
+ }
108
+
109
+ /** JSON with bigint and Date kept (as the memory drivers keep them through structuredClone). */
110
+ export const encode = (value: unknown): string =>
111
+ JSON.stringify(value, function (this: Record<string, unknown>, key, v) {
112
+ const raw = this[key]
113
+ if (typeof raw === 'bigint') return { $bigint: raw.toString() }
114
+ if (raw instanceof Date) return { $date: raw.toISOString() }
115
+ return v
116
+ })
117
+
118
+ /** Reverse of `encode()`: restores bigint and Date values; undefined for a missing key. */
119
+ export const decode = <T>(text: string | null | undefined): T | undefined =>
120
+ text === null || text === undefined
121
+ ? undefined
122
+ : (JSON.parse(text, (_k, v) => {
123
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
124
+ const keys = Object.keys(v)
125
+ if (keys.length === 1 && keys[0] === '$bigint') return BigInt(v.$bigint)
126
+ if (keys.length === 1 && keys[0] === '$date') return new Date(v.$date)
127
+ }
128
+ return v
129
+ }) as T)