@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 153 lines 5.09 KB
Raw
1 /**
2 * Bun Redis integration backed by Bun's built-in `RedisClient`.
3 *
4 * This module creates scoped Bun `RedisClient` connections and exposes them as
5 * both the portable `Redis` service and the Bun-specific `BunRedis` service for
6 * direct access to the raw client. The `layer` helper accepts Redis options
7 * directly, while `layerConfig` reads them from Effect config. Both also accept
8 * `Redis.PoolOptions` for the connections behind `Redis.reserve`, and close the
9 * underlying clients when the layer scope finalizes.
10 *
11 * @stability unstable
12 * @since 4.0.0
13 */
14 import type { RedisClient, RedisOptions } from "bun"
15 import * as Config from "effect/Config"
16 import * as Context from "effect/Context"
17 import * as Deferred from "effect/Deferred"
18 import * as Effect from "effect/Effect"
19 import * as Fn from "effect/Function"
20 import * as Layer from "effect/Layer"
21 import * as Redis from "effect/persistence/Redis"
22 import * as Scope from "effect/Scope"
23
24 /**
25 * Service tag for Bun Redis integration, exposing the raw `RedisClient` and a `use` helper that maps client promise failures to `RedisError`.
26 *
27 * @stability unstable
28 * @category services
29 * @since 4.0.0
30 */
31 export class BunRedis extends Context.Service<BunRedis, {
32 readonly client: RedisClient
33 readonly use: <A>(f: (client: RedisClient) => Promise<A>) => Effect.Effect<A, Redis.RedisError>
34 }>()("@effect/platform-bun/BunRedis") {}
35
36 type BunRedisOptions = { readonly url?: string } & RedisOptions & Redis.PoolOptions
37
38 const make = Effect.fnUntraced(function*(
39 { acquireTimeout, idleTimeout, maxConnections, minConnections, ...options }: BunRedisOptions = {}
40 ) {
41 const { RedisClient } = yield* Effect.promise(() => import("bun"))
42 const scope = yield* Effect.scope
43 yield* Scope.addFinalizer(scope, Effect.sync(() => client.close()))
44 const client = new RedisClient(options.url, options)
45
46 const use = <A>(f: (client: RedisClient) => Promise<A>) =>
47 Effect.tryPromise({
48 try: () => f(client),
49 catch: (cause) => new Redis.RedisError({ cause })
50 })
51
52 const sendWith =
53 (client: RedisClient) =>
54 <A = unknown>(command: string, ...args: ReadonlyArray<string>): Effect.Effect<A, Redis.RedisError> =>
55 Effect.tryPromise({
56 try: () => client.send(command, args as Array<string>) as Promise<A>,
57 catch: (cause) => new Redis.RedisError({ cause })
58 })
59
60 const redis = yield* Redis.make({
61 send: sendWith(client),
62 // Reserved connections do not reconnect: a dropped socket fails the
63 // in-flight command and the connection leaves the pool.
64 connect: Effect.tryPromise({
65 try: async () => {
66 const connection = new RedisClient(options.url, { ...options, autoReconnect: false })
67 try {
68 await connection.connect()
69 return connection
70 } catch (cause) {
71 connection.close()
72 throw cause
73 }
74 },
75 catch: (cause) => new Redis.RedisError({ cause })
76 }).pipe(
77 Effect.map((connection) => ({
78 send: sendWith(connection),
79 close: Effect.sync(() => connection.close())
80 }))
81 ),
82 pool: { acquireTimeout, idleTimeout, maxConnections, minConnections },
83 subscribe: Effect.fnUntraced(function*(channel, onMessage) {
84 const terminal = yield* Deferred.make<void, Redis.RedisError>()
85 yield* Effect.acquireRelease(
86 Effect.tryPromise({
87 try: async () => {
88 const subscriber = new RedisClient(options.url, {
89 ...options,
90 autoReconnect: false
91 })
92 subscriber.onclose = (cause) => {
93 Deferred.doneUnsafe(terminal, new Redis.RedisError({ cause }))
94 }
95 try {
96 await subscriber.subscribe(channel, (message, channel) => {
97 onMessage({ channel, message })
98 })
99 return subscriber
100 } catch (cause) {
101 subscriber.onclose = null
102 subscriber.close()
103 throw cause
104 }
105 },
106 catch: (cause) => new Redis.RedisError({ cause })
107 }),
108 (subscriber) =>
109 Effect.sync(() => {
110 subscriber.onclose = null
111 subscriber.close()
112 })
113 )
114 return Deferred.await(terminal)
115 })
116 })
117
118 const bunRedis = Fn.identity<BunRedis["Service"]>({
119 client,
120 use
121 })
122
123 return Context.make(BunRedis, bunRedis).pipe(
124 Context.add(Redis.Redis, redis)
125 )
126 })
127
128 /**
129 * Creates scoped Bun Redis layers for `Redis.Redis` and `BunRedis`, closing the underlying client when the scope finalizes.
130 *
131 * @stability unstable
132 * @category layers
133 * @since 4.0.0
134 */
135 export const layer = (
136 options?: BunRedisOptions | undefined
137 ): Layer.Layer<Redis.Redis | BunRedis> => Layer.effectContext(make(options))
138
139 /**
140 * Creates scoped Bun Redis layers from configurable Redis options, closing the underlying client when the scope finalizes.
141 *
142 * @stability unstable
143 * @category layers
144 * @since 4.0.0
145 */
146 export const layerConfig = (
147 options: Config.Wrap<BunRedisOptions>
148 ): Layer.Layer<Redis.Redis | BunRedis, Config.ConfigError> =>
149 Layer.effectContext(
150 Config.unwrap(options).pipe(
151 Effect.flatMap(make)
152 )
153 )