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

main
ts 266 lines 10.2 KB
Raw
1 /**
2 * Node.js Redis integration backed by `redis` (node-redis).
3 *
4 * This module creates a scoped `node-redis` client and exposes it in two forms:
5 * the generic `Redis` service and the {@link NodeRedis} service for direct
6 * access to the underlying client. `layer` accepts node-redis client options
7 * directly, while `layerConfig` reads them from Effect config. Both also accept
8 * `Redis.PoolOptions` for the connections behind `Redis.reserve`. `node-redis`
9 * connects explicitly, so layer construction can fail with a `RedisError`.
10 * Both layers close the client when the layer scope ends.
11 *
12 * @stability unstable
13 * @since 4.0.0
14 */
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 { createClient, SocketTimeoutError } from "redis"
23
24 type NodeRedisClient = ReturnType<typeof createClient>
25 type NodeRedisClientOptions = NonNullable<Parameters<typeof createClient>[0]>
26 type NodeRedisOptions = NodeRedisClientOptions & Redis.PoolOptions
27
28 /**
29 * Service tag for the Node Redis integration, exposing the underlying
30 * `node-redis` client and a `use` helper that maps client failures to
31 * `RedisError`.
32 *
33 * @stability unstable
34 * @category services
35 * @since 4.0.0
36 */
37 export class NodeRedis extends Context.Service<NodeRedis, {
38 readonly client: NodeRedisClient
39 readonly use: <A>(f: (client: NodeRedisClient) => Promise<A>) => Effect.Effect<A, Redis.RedisError>
40 }>()("@effect/platform-node/NodeRedis") {}
41
42 // node-redis cannot destroy a socket that is still connecting, so every
43 // client gets a socket signal that `destroy` aborts.
44 const withSignal = (socket: NodeRedisClientOptions["socket"], signal: AbortSignal) => {
45 // node-redis' TLS option type omits `signal`, which `tls.connect` accepts.
46 const callerSignal = socket && "signal" in socket ? socket.signal : undefined
47 return { ...socket, signal: callerSignal ? AbortSignal.any([callerSignal, signal]) : signal }
48 }
49
50 const makeSocket = (
51 socket: NodeRedisClientOptions["socket"],
52 signal: AbortSignal,
53 isReady: () => boolean
54 ) => {
55 return {
56 ...withSignal(socket, signal),
57 reconnectStrategy: socket?.reconnectStrategy ?? ((retries, cause) => {
58 if (!isReady()) return cause
59 if (cause instanceof SocketTimeoutError) return false
60 const jitter = Math.floor(Math.random() * 200)
61 const delay = Math.min(2 ** retries * 50, 2000)
62 return delay + jitter
63 })
64 }
65 }
66
67 // Destroying first leaves the abort only an untracked, still-connecting socket
68 // to close, so it raises no client error.
69 const destroy = (client: NodeRedisClient, abort?: AbortController) => {
70 try {
71 client.destroy()
72 } catch {
73 // node-redis before 6.3 throws when destroying a client whose connection
74 // has failed.
75 }
76 abort?.abort()
77 }
78
79 const make = Effect.fnUntraced(function*(
80 { acquireTimeout, idleTimeout, maxConnections, minConnections, ...options }: NodeRedisOptions = {}
81 ) {
82 const socket = options.socket
83 const abort = new AbortController()
84 let ready = false
85 const client = yield* Effect.acquireRelease(
86 Effect.sync(() => createClient({ ...options, socket: makeSocket(socket, abort.signal, () => ready) })),
87 (client) => Effect.sync(() => destroy(client, abort))
88 )
89 client.once("ready", () => {
90 ready = true
91 })
92
93 // node-redis rethrows `error` events that have no listener, which would crash
94 // the process on a transient socket failure. Command failures are still
95 // reported as `RedisError`.
96 const runSync = Effect.runSyncWith(yield* Effect.context<never>())
97 client.on("error", (cause) => {
98 // node-redis before 6.3 reports connection attempts that teardown cut short.
99 if (abort.signal.aborted) return
100 runSync(Effect.logWarning("NodeRedis client error", cause))
101 })
102
103 yield* Effect.tryPromise({
104 try: () => client.connect(),
105 catch: (cause) => new Redis.RedisError({ cause })
106 })
107
108 const use = <A>(f: (client: NodeRedisClient) => Promise<A>) =>
109 Effect.tryPromise({
110 try: () => f(client),
111 catch: (cause) => new Redis.RedisError({ cause })
112 })
113
114 const sendWith =
115 (client: NodeRedisClient) =>
116 <A = unknown>(command: string, ...args: ReadonlyArray<string>): Effect.Effect<A, Redis.RedisError> =>
117 Effect.tryPromise({
118 try: () => client.sendCommand([command, ...args]) as Promise<A>,
119 catch: (cause) => new Redis.RedisError({ cause })
120 })
121
122 const redis = yield* Redis.make({
123 send: sendWith(client),
124 // Reserved connections do not reconnect: a dropped socket fails the
125 // in-flight command and the connection leaves the pool.
126 //
127 // The pool acquires connections uninterruptibly, so `connect` opts back in
128 // to interruption. The signal aborts only on interruption: it closes a
129 // socket that is still connecting, and `destroy` discards a connection
130 // that has already opened.
131 connect: Effect.interruptible(Effect.tryPromise({
132 try: async (signal) => {
133 const connection = client.duplicate({ socket: { ...withSignal(socket, signal), reconnectStrategy: false } })
134 connection.on("error", (cause) => {
135 if (signal.aborted) return
136 runSync(Effect.logWarning("NodeRedis reserved connection error", cause))
137 })
138 signal.addEventListener("abort", () => destroy(connection), { once: true })
139 try {
140 await connection.connect()
141 return connection
142 } catch (cause) {
143 destroy(connection)
144 throw cause
145 }
146 },
147 catch: (cause) => new Redis.RedisError({ cause })
148 })).pipe(
149 Effect.map((connection) => ({
150 send: sendWith(connection),
151 // `destroy` rejects in-flight commands instead of waiting for their
152 // replies like `close` does.
153 close: Effect.sync(() => destroy(connection))
154 }))
155 ),
156 pool: { acquireTimeout, idleTimeout, maxConnections, minConnections },
157 subscribe: Effect.fnUntraced(function*(channel, onMessage) {
158 const terminal = yield* Deferred.make<void, Redis.RedisError>()
159 const abort = new AbortController()
160 let subscriberReady = false
161 // Only creating the subscriber is uninterruptible, so a stalled connection
162 // or `SUBSCRIBE` can be interrupted and the scope closes it.
163 const subscriber = yield* Effect.acquireRelease(
164 Effect.sync(() => client.duplicate({ socket: makeSocket(socket, abort.signal, () => subscriberReady) })),
165 (subscriber) => Effect.sync(() => destroy(subscriber, abort))
166 )
167 subscriber.once("ready", () => {
168 subscriberReady = true
169 })
170 subscriber.on("error", (cause) => {
171 if (abort.signal.aborted) return
172 runSync(Effect.logWarning("NodeRedis subscriber error", cause))
173 if (!subscriber.isOpen) {
174 runSync(Deferred.fail(terminal, new Redis.RedisError({ cause })))
175 }
176 })
177 yield* Effect.tryPromise({
178 try: async () => {
179 try {
180 await subscriber.connect()
181 await subscriber.subscribe(channel, (message, channel) => {
182 onMessage({ channel, message })
183 })
184 } catch (cause) {
185 destroy(subscriber, abort)
186 throw cause
187 }
188 },
189 catch: (cause) => new Redis.RedisError({ cause })
190 })
191 return Deferred.await(terminal)
192 })
193 })
194
195 const nodeRedis = Fn.identity<NodeRedis["Service"]>({
196 client,
197 use
198 })
199
200 return Context.make(NodeRedis, nodeRedis).pipe(
201 Context.add(Redis.Redis, redis)
202 )
203 })
204
205 /**
206 * Provides `Redis` and `NodeRedis` services backed by a `node-redis` client
207 * created with the supplied options, connected when the layer is built and
208 * closed when the layer scope ends.
209 *
210 * **Details**
211 *
212 * By default, the initial connection fails on its first connection error. A
213 * caller-supplied `socket.reconnectStrategy` is used instead when present. Once
214 * the client has emitted `ready`, the default reconnect strategy uses
215 * node-redis' exponential backoff and stops on socket timeouts.
216 *
217 * Scope finalization destroys the shared client immediately, failing commands
218 * still in flight and aborting any connection attempt in progress, including
219 * reserved connections that are still being established. Interrupting
220 * `Redis.subscribe` while it is connecting or subscribing closes its
221 * connection. Interrupting `Redis.reserve` only stops waiting: a connection the
222 * pool is already opening joins the pool when it is ready. Run blocking
223 * commands on `Redis.reserve` so they do not hold up the shared connection.
224 *
225 * @stability unstable
226 * @category layers
227 * @since 4.0.0
228 */
229 export const layer = (
230 options?: NodeRedisOptions | undefined
231 ): Layer.Layer<Redis.Redis | NodeRedis, Redis.RedisError> => Layer.effectContext(make(options))
232
233 /**
234 * Provides `Redis` and `NodeRedis` services from `Config`-backed node-redis
235 * client options, connecting the client when the layer is built and closing it
236 * when the layer scope ends.
237 *
238 * **Details**
239 *
240 * By default, the initial connection fails on its first connection error. A
241 * caller-supplied `socket.reconnectStrategy` is used instead when present. Once
242 * the client has emitted `ready`, the default reconnect strategy uses
243 * node-redis' exponential backoff and stops on socket timeouts.
244 *
245 * Scope finalization destroys the shared client immediately, failing commands
246 * still in flight and aborting any connection attempt in progress, including
247 * reserved connections that are still being established. Interrupting
248 * `Redis.subscribe` while it is connecting or subscribing closes its
249 * connection. Interrupting `Redis.reserve` only stops waiting: a connection the
250 * pool is already opening joins the pool when it is ready. Run blocking
251 * commands on `Redis.reserve` so they do not hold up the shared connection.
252 *
253 * @stability unstable
254 * @category layers
255 * @since 4.0.0
256 */
257 export const layerConfig: (
258 options: Config.Wrap<NodeRedisOptions>
259 ) => Layer.Layer<Redis.Redis | NodeRedis, Redis.RedisError | Config.ConfigError> = (
260 options: Config.Wrap<NodeRedisOptions>
261 ): Layer.Layer<Redis.Redis | NodeRedis, Redis.RedisError | Config.ConfigError> =>
262 Layer.effectContext(
263 Config.unwrap(options).pipe(
264 Effect.flatMap(make)
265 )
266 )