The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Redis from "@alchemy.run/redis"; |
| 2 | import { |
| 3 | encodeError, |
| 4 | encodeInteger, |
| 5 | encodeNull, |
| 6 | encodeReply, |
| 7 | encodeSimpleString, |
| 8 | Parser, |
| 9 | } from "@alchemy.run/redis/Resp"; |
| 10 | import { describe, expect, it } from "@alchemy.run/test"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Result from "effect/Result"; |
| 13 | |
| 14 | type Session = { parser: Parser; authed: boolean }; |
| 15 | |
| 16 | type Stored = |
| 17 | | { readonly t: "string"; v: string } |
| 18 | | { readonly t: "hash"; v: Map<string, string> } |
| 19 | | { readonly t: "list"; v: string[] } |
| 20 | | { readonly t: "set"; v: Set<string> } |
| 21 | | { readonly t: "zset"; v: Map<string, number> }; |
| 22 | |
| 23 | const asString = (value: unknown): string => String(value ?? ""); |
| 24 | |
| 25 | const wrongType = () => |
| 26 | encodeError("WRONGTYPE Operation against a key holding the wrong kind of value"); |
| 27 | |
| 28 | const execute = (store: Map<string, Stored>, name: string, args: string[]): Uint8Array => { |
| 29 | const cmd = name.toUpperCase(); |
| 30 | if (cmd === "PING") { |
| 31 | return args[0] === undefined ? encodeSimpleString("PONG") : encodeReply(args[0]); |
| 32 | } |
| 33 | if (cmd === "ECHO") return encodeReply(args[0] ?? ""); |
| 34 | if (cmd === "AUTH") return encodeSimpleString("OK"); |
| 35 | if (cmd === "SELECT") return encodeSimpleString("OK"); |
| 36 | if (cmd === "GET") { |
| 37 | const row = store.get(args[0] ?? ""); |
| 38 | if (row === undefined) return encodeNull(); |
| 39 | if (row.t !== "string") return wrongType(); |
| 40 | return encodeReply(row.v); |
| 41 | } |
| 42 | if (cmd === "SET") { |
| 43 | store.set(args[0] ?? "", { t: "string", v: args[1] ?? "" }); |
| 44 | return encodeSimpleString("OK"); |
| 45 | } |
| 46 | if (cmd === "DEL") { |
| 47 | let n = 0; |
| 48 | for (const key of args) { |
| 49 | if (store.delete(key)) n++; |
| 50 | } |
| 51 | return encodeInteger(n); |
| 52 | } |
| 53 | if (cmd === "EXISTS") { |
| 54 | return encodeInteger(args.filter((key) => store.has(key)).length); |
| 55 | } |
| 56 | if (cmd === "INCR" || cmd === "INCRBY" || cmd === "DECR") { |
| 57 | const key = args[0] ?? ""; |
| 58 | const delta = cmd === "DECR" ? -1 : cmd === "INCR" ? 1 : Number(args[1] ?? 1); |
| 59 | const row = store.get(key); |
| 60 | if (row !== undefined && row.t !== "string") return wrongType(); |
| 61 | const next = Number(row?.t === "string" ? row.v : 0) + delta; |
| 62 | store.set(key, { t: "string", v: String(next) }); |
| 63 | return encodeInteger(next); |
| 64 | } |
| 65 | if (cmd === "HSET") { |
| 66 | const key = args[0] ?? ""; |
| 67 | const row = store.get(key); |
| 68 | if (row !== undefined && row.t !== "hash") return wrongType(); |
| 69 | const hash = row?.t === "hash" ? row.v : new Map<string, string>(); |
| 70 | let added = 0; |
| 71 | for (let i = 1; i + 1 < args.length; i += 2) { |
| 72 | if (!hash.has(args[i]!)) added++; |
| 73 | hash.set(args[i]!, args[i + 1]!); |
| 74 | } |
| 75 | store.set(key, { t: "hash", v: hash }); |
| 76 | return encodeInteger(added); |
| 77 | } |
| 78 | if (cmd === "HGET") { |
| 79 | const row = store.get(args[0] ?? ""); |
| 80 | if (row === undefined) return encodeNull(); |
| 81 | if (row.t !== "hash") return wrongType(); |
| 82 | const value = row.v.get(args[1] ?? ""); |
| 83 | return value === undefined ? encodeNull() : encodeReply(value); |
| 84 | } |
| 85 | if (cmd === "HGETALL") { |
| 86 | const row = store.get(args[0] ?? ""); |
| 87 | if (row === undefined) return encodeReply([]); |
| 88 | if (row.t !== "hash") return wrongType(); |
| 89 | const items: string[] = []; |
| 90 | for (const [field, value] of row.v) { |
| 91 | items.push(field, value); |
| 92 | } |
| 93 | return encodeReply(items); |
| 94 | } |
| 95 | if (cmd === "LPUSH" || cmd === "RPUSH") { |
| 96 | const key = args[0] ?? ""; |
| 97 | const row = store.get(key); |
| 98 | if (row !== undefined && row.t !== "list") return wrongType(); |
| 99 | const list = row?.t === "list" ? row.v : []; |
| 100 | const values = args.slice(1); |
| 101 | if (cmd === "LPUSH") list.unshift(...values.reverse()); |
| 102 | else list.push(...values); |
| 103 | store.set(key, { t: "list", v: list }); |
| 104 | return encodeInteger(list.length); |
| 105 | } |
| 106 | if (cmd === "LRANGE") { |
| 107 | const row = store.get(args[0] ?? ""); |
| 108 | if (row === undefined) return encodeReply([]); |
| 109 | if (row.t !== "list") return wrongType(); |
| 110 | const start = Number(args[1] ?? 0); |
| 111 | const stop = Number(args[2] ?? -1); |
| 112 | const end = stop < 0 ? row.v.length + stop + 1 : stop + 1; |
| 113 | return encodeReply(row.v.slice(start, end)); |
| 114 | } |
| 115 | if (cmd === "SADD") { |
| 116 | const key = args[0] ?? ""; |
| 117 | const row = store.get(key); |
| 118 | if (row !== undefined && row.t !== "set") return wrongType(); |
| 119 | const set = row?.t === "set" ? row.v : new Set<string>(); |
| 120 | let added = 0; |
| 121 | for (const member of args.slice(1)) { |
| 122 | if (!set.has(member)) { |
| 123 | set.add(member); |
| 124 | added++; |
| 125 | } |
| 126 | } |
| 127 | store.set(key, { t: "set", v: set }); |
| 128 | return encodeInteger(added); |
| 129 | } |
| 130 | if (cmd === "SMEMBERS") { |
| 131 | const row = store.get(args[0] ?? ""); |
| 132 | if (row === undefined) return encodeReply([]); |
| 133 | if (row.t !== "set") return wrongType(); |
| 134 | return encodeReply([...row.v]); |
| 135 | } |
| 136 | if (cmd === "ZADD") { |
| 137 | const key = args[0] ?? ""; |
| 138 | const row = store.get(key); |
| 139 | if (row !== undefined && row.t !== "zset") return wrongType(); |
| 140 | const zset = row?.t === "zset" ? row.v : new Map<string, number>(); |
| 141 | const member = args[2] ?? ""; |
| 142 | const added = zset.has(member) ? 0 : 1; |
| 143 | zset.set(member, Number(args[1] ?? 0)); |
| 144 | store.set(key, { t: "zset", v: zset }); |
| 145 | return encodeInteger(added); |
| 146 | } |
| 147 | if (cmd === "ZRANGE") { |
| 148 | const row = store.get(args[0] ?? ""); |
| 149 | if (row === undefined) return encodeReply([]); |
| 150 | if (row.t !== "zset") return wrongType(); |
| 151 | const ranked = [...row.v.entries()].sort((a, b) => a[1] - b[1]); |
| 152 | const start = Number(args[1] ?? 0); |
| 153 | const stop = Number(args[2] ?? -1); |
| 154 | const end = stop < 0 ? ranked.length + stop + 1 : stop + 1; |
| 155 | return encodeReply(ranked.slice(start, end).map(([member]) => member)); |
| 156 | } |
| 157 | return encodeError(`ERR unknown command '${name}'`); |
| 158 | }; |
| 159 | |
| 160 | const startFakeRedis = (options?: { readonly password?: string; readonly splitWrites?: boolean }) => |
| 161 | Effect.acquireRelease( |
| 162 | Effect.sync(() => { |
| 163 | const store = new Map<string, Stored>(); |
| 164 | const sessions = new WeakMap<object, Session>(); |
| 165 | const password = options?.password ?? ""; |
| 166 | const splitWrites = options?.splitWrites === true; |
| 167 | const write = (socket: { write(bytes: Uint8Array): unknown }, payload: Uint8Array) => { |
| 168 | if (!splitWrites) { |
| 169 | socket.write(payload); |
| 170 | return; |
| 171 | } |
| 172 | for (const byte of payload) { |
| 173 | socket.write(new Uint8Array([byte])); |
| 174 | } |
| 175 | }; |
| 176 | const server = Bun.listen({ |
| 177 | hostname: "127.0.0.1", |
| 178 | port: 0, |
| 179 | socket: { |
| 180 | binaryType: "uint8array", |
| 181 | open(socket) { |
| 182 | sessions.set(socket, { |
| 183 | parser: new Parser(), |
| 184 | authed: password.length === 0, |
| 185 | }); |
| 186 | }, |
| 187 | data(socket, chunk) { |
| 188 | const session = sessions.get(socket); |
| 189 | if (session === undefined) return; |
| 190 | session.parser.push(chunk); |
| 191 | while (true) { |
| 192 | const frame = session.parser.next(); |
| 193 | if (frame._tag === "Incomplete") break; |
| 194 | if (frame._tag !== "Reply" || !Array.isArray(frame.value)) { |
| 195 | write(socket, encodeError("ERR protocol")); |
| 196 | continue; |
| 197 | } |
| 198 | const [name, ...args] = frame.value.map(asString); |
| 199 | if (!session.authed) { |
| 200 | if ((name ?? "").toUpperCase() !== "AUTH") { |
| 201 | write(socket, encodeError("NOAUTH Authentication required")); |
| 202 | continue; |
| 203 | } |
| 204 | const supplied = args.length > 1 ? args[1] : args[0]; |
| 205 | if (supplied !== password) { |
| 206 | write(socket, encodeError("ERR invalid password")); |
| 207 | continue; |
| 208 | } |
| 209 | session.authed = true; |
| 210 | write(socket, encodeSimpleString("OK")); |
| 211 | continue; |
| 212 | } |
| 213 | write(socket, execute(store, name ?? "", args)); |
| 214 | } |
| 215 | }, |
| 216 | }, |
| 217 | }); |
| 218 | return { |
| 219 | url: Redis.connectionUrl({ |
| 220 | host: "127.0.0.1", |
| 221 | port: server.port, |
| 222 | password, |
| 223 | }), |
| 224 | server, |
| 225 | }; |
| 226 | }), |
| 227 | ({ server }) => |
| 228 | Effect.sync(() => { |
| 229 | server.stop(true); |
| 230 | }), |
| 231 | ); |
| 232 | |
| 233 | describe("Redis protocol client", { tags: ["unit", "local"] }, () => { |
| 234 | it.effect("PING SET GET DEL over a one-shot connection", () => |
| 235 | Effect.gen(function* () { |
| 236 | const { url } = yield* startFakeRedis(); |
| 237 | expect(yield* Redis.run(url, "PING")).toBe("PONG"); |
| 238 | expect(yield* Redis.run(url, "SET", ["marker", "hello"])).toBe("OK"); |
| 239 | expect(yield* Redis.run(url, "GET", ["marker"])).toBe("hello"); |
| 240 | expect(yield* Redis.run(url, "GET", ["missing"])).toBeNull(); |
| 241 | expect(yield* Redis.run(url, "DEL", ["marker"])).toBe(1); |
| 242 | }), |
| 243 | ); |
| 244 | |
| 245 | it.effect("values may contain CR LF $ * and UTF-8", () => |
| 246 | Effect.gen(function* () { |
| 247 | const { url } = yield* startFakeRedis(); |
| 248 | const value = "line1\r\n$bulk\n*2\r\n😀"; |
| 249 | yield* Redis.run(url, "SET", ["k", value]); |
| 250 | expect(yield* Redis.run(url, "GET", ["k"])).toBe(value); |
| 251 | }), |
| 252 | ); |
| 253 | |
| 254 | it.effect("AUTH then command, and AUTH failure", () => |
| 255 | Effect.gen(function* () { |
| 256 | const { url } = yield* startFakeRedis({ password: "s3cret" }); |
| 257 | expect(yield* Redis.run(url, "PING")).toBe("PONG"); |
| 258 | const denied = yield* Redis.run( |
| 259 | Redis.connectionUrl({ |
| 260 | host: "127.0.0.1", |
| 261 | port: Number(new URL(url).port), |
| 262 | password: "nope", |
| 263 | }), |
| 264 | "PING", |
| 265 | ).pipe(Effect.result); |
| 266 | expect(Result.isFailure(denied)).toBe(true); |
| 267 | }), |
| 268 | ); |
| 269 | |
| 270 | it.effect("pipeline issues several commands on one connection", () => |
| 271 | Effect.gen(function* () { |
| 272 | const { url } = yield* startFakeRedis(); |
| 273 | const replies = yield* Redis.pipeline(url, [ |
| 274 | ["PING"], |
| 275 | ["SET", "a", "1"], |
| 276 | ["INCR", "n"], |
| 277 | ["GET", "a"], |
| 278 | ]); |
| 279 | expect(replies).toEqual(["PONG", "OK", 1, "1"]); |
| 280 | }), |
| 281 | ); |
| 282 | |
| 283 | it.effect("session send reuses the socket", () => |
| 284 | Effect.gen(function* () { |
| 285 | const { url } = yield* startFakeRedis(); |
| 286 | const conn = yield* Redis.connect(url); |
| 287 | expect(yield* conn.send("PING")).toBe("PONG"); |
| 288 | expect(yield* conn.send("SET", ["k", "v"])).toBe("OK"); |
| 289 | expect(yield* conn.send("GET", ["k"])).toBe("v"); |
| 290 | expect(yield* conn.send("INCR", ["n"])).toBe(1); |
| 291 | expect(yield* conn.send("INCR", ["n"])).toBe(2); |
| 292 | }), |
| 293 | ); |
| 294 | |
| 295 | it.effect("hashes lists sets sorted sets and typed errors", () => |
| 296 | Effect.gen(function* () { |
| 297 | const { url } = yield* startFakeRedis(); |
| 298 | const conn = yield* Redis.connect(url); |
| 299 | expect(yield* conn.send("HSET", ["h", "a", "1", "b", "2"])).toBe(2); |
| 300 | expect(yield* conn.send("HGET", ["h", "a"])).toBe("1"); |
| 301 | expect(yield* conn.send("HGETALL", ["h"])).toEqual(["a", "1", "b", "2"]); |
| 302 | expect(yield* conn.send("LPUSH", ["l", "x", "y"])).toBe(2); |
| 303 | expect(yield* conn.send("LRANGE", ["l", 0, -1])).toEqual(["y", "x"]); |
| 304 | expect(yield* conn.send("SADD", ["s", "a", "a", "b"])).toBe(2); |
| 305 | const members = yield* conn.send("SMEMBERS", ["s"]); |
| 306 | expect(Array.isArray(members) ? [...members].sort() : members).toEqual(["a", "b"]); |
| 307 | expect(yield* conn.send("ZADD", ["z", 2, "b"])).toBe(1); |
| 308 | expect(yield* conn.send("ZADD", ["z", 1, "a"])).toBe(1); |
| 309 | expect(yield* conn.send("ZRANGE", ["z", 0, -1])).toEqual(["a", "b"]); |
| 310 | const wrong = yield* conn.send("GET", ["h"]).pipe(Effect.result); |
| 311 | expect(Result.isFailure(wrong)).toBe(true); |
| 312 | const unknown = yield* conn.send("NOPE").pipe(Effect.result); |
| 313 | expect(Result.isFailure(unknown)).toBe(true); |
| 314 | }), |
| 315 | ); |
| 316 | |
| 317 | it.effect("buffers replies split into one-byte TCP writes", () => |
| 318 | Effect.gen(function* () { |
| 319 | const { url } = yield* startFakeRedis({ splitWrites: true }); |
| 320 | expect(yield* Redis.run(url, "PING")).toBe("PONG"); |
| 321 | yield* Redis.run(url, "SET", ["k", "hello\r\nworld"]); |
| 322 | expect(yield* Redis.run(url, "GET", ["k"])).toBe("hello\r\nworld"); |
| 323 | expect( |
| 324 | yield* Redis.pipeline(url, [ |
| 325 | ["HSET", "h", "f", "v"], |
| 326 | ["HGETALL", "h"], |
| 327 | ]), |
| 328 | ).toEqual([1, ["f", "v"]]); |
| 329 | }), |
| 330 | ); |
| 331 | |
| 332 | it.effect("SELECT from the URL path", () => |
| 333 | Effect.gen(function* () { |
| 334 | const { url } = yield* startFakeRedis(); |
| 335 | const parsed = new URL(url); |
| 336 | const withDb = `${parsed.protocol}//${parsed.username}:${parsed.password}@${parsed.hostname}:${parsed.port}/2`; |
| 337 | expect(yield* Redis.run(withDb, "PING")).toBe("PONG"); |
| 338 | }), |
| 339 | ); |
| 340 | }); |