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

main
ts 175 lines 6 KB
Raw
1 /**
2 * Deno Redis integration backed by `@db/redis`.
3 *
4 * This module creates a scoped, native Deno Redis client and exposes it as
5 * both the portable `Redis` service and the Deno-specific {@link DenoRedis}
6 * service for direct access to the raw client. Unlike Bun's built-in client,
7 * `@db/redis` connects eagerly using RESP2, so layer construction can fail
8 * with a `RedisError`. The layers also accept `Redis.PoolOptions` for the
9 * connections behind `Redis.reserve`.
10 *
11 * @stability unstable
12 * @since 4.0.0
13 */
14 import { connect, parseURL, type Redis as RedisClient, type RedisConnectOptions } from "@db/redis"
15 import * as Config from "effect/Config"
16 import * as Context from "effect/Context"
17 import * as Effect from "effect/Effect"
18 import * as Fn from "effect/Function"
19 import * as Layer from "effect/Layer"
20 import * as Redis from "effect/persistence/Redis"
21 import * as Predicate from "effect/Predicate"
22 import * as Record from "effect/Record"
23
24 /**
25 * Options for connecting to Redis, including a Redis URL or individual
26 * connection settings. Explicit settings override values from the URL.
27 *
28 * @stability unstable
29 * @category models
30 * @since 4.0.0
31 */
32 export type RedisOptions = Omit<RedisConnectOptions, "hostname"> & {
33 readonly hostname?: string
34 readonly url?: string
35 }
36
37 /**
38 * Service tag for Deno Redis integration, exposing the raw `@db/redis` client
39 * and a `use` helper that maps client promise failures to `RedisError`.
40 *
41 * @stability unstable
42 * @category services
43 * @since 4.0.0
44 */
45 export class DenoRedis extends Context.Service<DenoRedis, {
46 readonly client: RedisClient
47 readonly use: <A>(f: (client: RedisClient) => Promise<A>) => Effect.Effect<A, Redis.RedisError>
48 }>()("@effect/platform-deno/DenoRedis") {}
49
50 const make = Effect.fnUntraced(function*(
51 { acquireTimeout, idleTimeout, maxConnections, minConnections, ...options }: RedisOptions & Redis.PoolOptions = {}
52 ) {
53 const connectClient = (overrides?: Partial<RedisConnectOptions>) => {
54 const { url, ...connectOptions } = options
55 const parsedUrl = url === undefined ? undefined : new URL(url)
56 const { name, ...parsed } = url === undefined ? { hostname: "localhost" } : parseURL(url)
57 return connect({
58 ...parsed,
59 ...(name === undefined ? {} : { username: name }),
60 ...(parsedUrl?.username ? { username: decodeURIComponent(parsedUrl.username) } : {}),
61 ...(parsedUrl?.password ? { password: decodeURIComponent(parsedUrl.password) } : {}),
62 ...Record.filter(connectOptions, Predicate.isNotUndefined),
63 ...overrides
64 })
65 }
66
67 const client = yield* Effect.acquireRelease(
68 Effect.tryPromise({
69 try: () => connectClient(),
70 catch: (cause) => new Redis.RedisError({ cause })
71 }),
72 (client) => Effect.sync(() => client.close())
73 )
74
75 const use = <A>(f: (client: RedisClient) => Promise<A>) =>
76 Effect.tryPromise({
77 try: () => f(client),
78 catch: (cause) => new Redis.RedisError({ cause })
79 })
80
81 const sendWith =
82 (client: RedisClient) =>
83 <A = unknown>(command: string, ...args: ReadonlyArray<string>): Effect.Effect<A, Redis.RedisError> =>
84 Effect.tryPromise({
85 try: () => client.sendCommand(command, args as Array<string>) as Promise<A>,
86 catch: (cause) => new Redis.RedisError({ cause })
87 })
88
89 const redis = yield* Redis.make({
90 send: sendWith(client),
91 connect: Effect.tryPromise({
92 // @db/redis re-executes commands after a reconnect, which could repeat
93 // a destructive blocking command whose reply was lost.
94 try: () => connectClient({ maxRetryCount: 0 }),
95 catch: (cause) => new Redis.RedisError({ cause })
96 }).pipe(
97 Effect.map((connection) => ({
98 send: sendWith(connection),
99 close: Effect.sync(() => connection.close())
100 }))
101 ),
102 pool: { acquireTimeout, idleTimeout, maxConnections, minConnections },
103 subscribe: (channel, onMessage) =>
104 Effect.acquireRelease(
105 Effect.tryPromise({
106 try: async () => {
107 const subscriber = await connectClient()
108 try {
109 const subscription = await subscriber.subscribe(channel)
110 // @db/redis resolves subscribe after writing the command, before
111 // reading its acknowledgement. This ordered reply proves that
112 // Redis processed SUBSCRIBE before the dequeue is returned.
113 await subscriber.ping()
114 return { subscriber, subscription }
115 } catch (cause) {
116 subscriber.close()
117 throw cause
118 }
119 },
120 catch: (cause) => new Redis.RedisError({ cause })
121 }),
122 ({ subscriber }) => Effect.sync(() => subscriber.close())
123 ).pipe(
124 Effect.map(({ subscription }) =>
125 Effect.tryPromise({
126 try: async () => {
127 for await (const message of subscription.receive()) {
128 onMessage(message)
129 }
130 },
131 catch: (cause) => new Redis.RedisError({ cause })
132 })
133 )
134 )
135 })
136
137 const denoRedis = Fn.identity<DenoRedis["Service"]>({
138 client,
139 use
140 })
141
142 return Context.make(DenoRedis, denoRedis).pipe(
143 Context.add(Redis.Redis, redis)
144 )
145 })
146
147 /**
148 * Provides `Redis` and `DenoRedis` services backed by an `@db/redis` client,
149 * closing the client when the layer scope ends. URL-derived options can be
150 * overridden by other supplied options.
151 *
152 * @stability unstable
153 * @category layers
154 * @since 4.0.0
155 */
156 export const layer = (
157 options?: (RedisOptions & Redis.PoolOptions) | undefined
158 ): Layer.Layer<Redis.Redis | DenoRedis, Redis.RedisError> => Layer.effectContext(make(options))
159
160 /**
161 * Provides `Redis` and `DenoRedis` services from `Config`-backed options,
162 * closing the client when the layer scope ends.
163 *
164 * @stability unstable
165 * @category layers
166 * @since 4.0.0
167 */
168 export const layerConfig = (
169 options: Config.Wrap<RedisOptions & Redis.PoolOptions>
170 ): Layer.Layer<Redis.Redis | DenoRedis, Redis.RedisError | Config.ConfigError> =>
171 Layer.effectContext(
172 Config.unwrap(options).pipe(
173 Effect.flatMap(make)
174 )
175 )