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

main
ts 274 lines 8.68 KB
Raw
1 import { ProtocolError, ReplyError } from "@alchemy.run/redis/Errors";
2 import {
3 decode,
4 decodeAll,
5 encodeArray,
6 encodeBoolean,
7 encodeBulk,
8 encodeCommand,
9 encodeDouble,
10 encodeError,
11 encodeInteger,
12 encodeNull,
13 encodeNullArray,
14 encodeReply,
15 encodeSimpleString,
16 Parser,
17 type ParseResult,
18 type Reply,
19 } from "@alchemy.run/redis/Resp";
20 import { describe, expect, test } from "@alchemy.run/test";
21
22 const utf8 = new TextEncoder();
23 const bytes = (value: string): Uint8Array => utf8.encode(value);
24
25 const asReply = (input: Uint8Array | string): Reply => {
26 const result = decode(input);
27 if (result._tag !== "Reply") {
28 throw new Error(`expected Reply, got ${JSON.stringify(result)}`);
29 }
30 return result.value;
31 };
32
33 const asError = (input: Uint8Array | string): ReplyError => {
34 const result = decode(input);
35 if (result._tag !== "Error") {
36 throw new Error(`expected Error, got ${JSON.stringify(result)}`);
37 }
38 return result.error;
39 };
40
41 const drain = (input: Uint8Array, size: number): ParseResult[] => {
42 const parser = new Parser();
43 const frames: ParseResult[] = [];
44 for (let offset = 0; offset < input.length; offset += size) {
45 parser.push(input.subarray(offset, offset + size));
46 while (true) {
47 const next = parser.next();
48 if (next._tag === "Incomplete") break;
49 frames.push(next);
50 if (next._tag === "Protocol") return frames;
51 }
52 }
53 return frames;
54 };
55
56 describe("encodeCommand", { tags: ["unit", "local"] }, () => {
57 test("PING is an array of bulk strings", () => {
58 expect(encodeCommand("PING")).toEqual(bytes("*1\r\n$4\r\nPING\r\n"));
59 });
60
61 test("LLEN mylist matches the RESP2 spec example", () => {
62 expect(encodeCommand("LLEN", ["mylist"])).toEqual(
63 bytes("*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n"),
64 );
65 });
66
67 test("bulk length is bytes, not JS string length", () => {
68 const encoded = encodeCommand("SET", ["k", "😀"]);
69 expect(encoded).toEqual(bytes("*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$4\r\n😀\r\n"));
70 });
71
72 test("binary args are length-prefixed without scanning", () => {
73 const payload = new Uint8Array([0, 13, 10, 36, 42]);
74 const encoded = encodeCommand("SET", ["bin", payload]);
75 const prefix = bytes("*3\r\n$3\r\nSET\r\n$3\r\nbin\r\n$5\r\n");
76 const expected = new Uint8Array(prefix.length + payload.length + 2);
77 expected.set(prefix, 0);
78 expected.set(payload, prefix.length);
79 expected.set([13, 10], prefix.length + payload.length);
80 expect(encoded).toEqual(expected);
81 });
82 });
83
84 describe("RESP2 decode", { tags: ["unit", "local"] }, () => {
85 test("simple string", () => {
86 expect(asReply("+OK\r\n")).toBe("OK");
87 expect(asReply("+\r\n")).toBe("");
88 });
89
90 test("error prefix and message", () => {
91 const error = asError("-ERR unknown command 'foobar'\r\n");
92 expect(error).toBeInstanceOf(ReplyError);
93 expect(error.code).toBe("ERR");
94 expect(error.message).toBe("ERR unknown command 'foobar'");
95 const wrongType = asError(
96 "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n",
97 );
98 expect(wrongType.code).toBe("WRONGTYPE");
99 });
100
101 test("integers including negative", () => {
102 expect(asReply(":0\r\n")).toBe(0);
103 expect(asReply(":1000\r\n")).toBe(1000);
104 expect(asReply(":-1\r\n")).toBe(-1);
105 expect(asReply(":48293\r\n")).toBe(48293);
106 });
107
108 test("integers outside MAX_SAFE_INTEGER become bigint", () => {
109 expect(asReply(":9007199254740993\r\n")).toBe(9007199254740993n);
110 });
111
112 test("null bulk and empty bulk", () => {
113 expect(asReply("$-1\r\n")).toBeNull();
114 expect(asReply("$0\r\n\r\n")).toBe("");
115 });
116
117 test("bulk string with CR LF $ * inside", () => {
118 expect(asReply("$6\r\nfoobar\r\n")).toBe("foobar");
119 const payload = "\r\n$*";
120 expect(asReply(encodeBulk(payload))).toBe(payload);
121 });
122
123 test("null array, empty array, mixed array, nested array", () => {
124 expect(asReply("*-1\r\n")).toBeNull();
125 expect(asReply("*0\r\n")).toEqual([]);
126 expect(asReply("*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n")).toEqual(["foo", "bar"]);
127 expect(asReply("*3\r\n:1\r\n:2\r\n:3\r\n")).toEqual([1, 2, 3]);
128 expect(asReply("*5\r\n:1\r\n:2\r\n:3\r\n:4\r\n$6\r\nfoobar\r\n")).toEqual([
129 1,
130 2,
131 3,
132 4,
133 "foobar",
134 ]);
135 const nested = asReply("*2\r\n*3\r\n:1\r\n:2\r\n:3\r\n*2\r\n+Foo\r\n-Bar\r\n");
136 expect(Array.isArray(nested)).toBe(true);
137 const [first, second] = nested as Reply[];
138 expect(first).toEqual([1, 2, 3]);
139 expect(Array.isArray(second)).toBe(true);
140 const pair = second as Reply[];
141 expect(pair[0]).toBe("Foo");
142 expect(pair[1]).toBeInstanceOf(ReplyError);
143 expect((pair[1] as ReplyError).code).toBe("Bar");
144 });
145
146 test("null element in array", () => {
147 expect(asReply("*3\r\n$3\r\nfoo\r\n$-1\r\n$3\r\nbar\r\n")).toEqual(["foo", null, "bar"]);
148 });
149
150 test("round-trip encodeReply", () => {
151 const value: Reply = ["ok", 3, null, ["nested"]];
152 expect(asReply(encodeReply(value))).toEqual(value);
153 });
154 });
155
156 describe("RESP3 decode", { tags: ["unit", "local"] }, () => {
157 test("null boolean double big number", () => {
158 expect(asReply("_\r\n")).toBeNull();
159 expect(asReply("#t\r\n")).toBe(true);
160 expect(asReply("#f\r\n")).toBe(false);
161 expect(asReply(",1.23\r\n")).toBe(1.23);
162 expect(asReply(",inf\r\n")).toBe(Infinity);
163 expect(asReply(",-inf\r\n")).toBe(-Infinity);
164 expect(Number.isNaN(asReply(",nan\r\n") as number)).toBe(true);
165 expect(asReply("(3492890328409238509324850943850943825024385\r\n")).toBe(
166 3492890328409238509324850943850943825024385n,
167 );
168 });
169
170 test("verbatim string strips the encoding prefix", () => {
171 expect(asReply("=15\r\ntxt:Some string\r\n")).toBe("Some string");
172 });
173
174 test("map with string keys becomes an object", () => {
175 expect(asReply("%2\r\n+first\r\n:1\r\n+second\r\n:2\r\n")).toEqual({
176 first: 1,
177 second: 2,
178 });
179 });
180
181 test("set is an array", () => {
182 expect(asReply("~2\r\n+orange\r\n+apple\r\n")).toEqual(["orange", "apple"]);
183 });
184
185 test("attributes are skipped and the following value is returned", () => {
186 expect(asReply("|1\r\n+ttl\r\n:3600\r\n:3\r\n")).toBe(3);
187 });
188
189 test("push frames are tagged", () => {
190 const result = decode(">2\r\n+message\r\n+chan\r\n");
191 expect(result).toEqual({
192 _tag: "Push",
193 value: ["message", "chan"],
194 });
195 });
196
197 test("blob error", () => {
198 const result = decode("!21\r\nSYNTAX invalid syntax\r\n");
199 expect(result._tag).toBe("Error");
200 if (result._tag === "Error") {
201 expect(result.error.code).toBe("SYNTAX");
202 expect(result.error.message).toBe("SYNTAX invalid syntax");
203 }
204 });
205
206 test("streamed string", () => {
207 expect(asReply("$?\r\n;5\r\nHello\r\n;1\r\n \r\n;5\r\nworld\r\n;0\r\n")).toBe("Hello world");
208 });
209
210 test("streamed array", () => {
211 expect(asReply("*?\r\n:1\r\n:2\r\n:3\r\n.\r\n")).toEqual([1, 2, 3]);
212 });
213 });
214
215 describe("incremental parser", { tags: ["unit", "local"] }, () => {
216 test("replies split one byte at a time", () => {
217 const payload = encodeArray([
218 encodeBulk("foo"),
219 encodeNull(),
220 encodeInteger(2),
221 encodeSimpleString("OK"),
222 ]);
223 const frames = drain(payload, 1);
224 expect(frames).toEqual([{ _tag: "Reply", value: ["foo", null, 2, "OK"] }]);
225 });
226
227 test("bulk payload split across chunks", () => {
228 const parser = new Parser();
229 parser.push(bytes("$6\r\nfoo"));
230 expect(parser.next()._tag).toBe("Incomplete");
231 parser.push(bytes("bar\r\n"));
232 expect(parser.next()).toEqual({ _tag: "Reply", value: "foobar" });
233 });
234
235 test("multiple replies in one buffer", () => {
236 const frames = decodeAll("+OK\r\n:1\r\n$4\r\nPONG\r\n");
237 expect(frames).toEqual([
238 { _tag: "Reply", value: "OK" },
239 { _tag: "Reply", value: 1 },
240 { _tag: "Reply", value: "PONG" },
241 ]);
242 });
243
244 test("CRLF split across chunks", () => {
245 const parser = new Parser();
246 parser.push(bytes("+OK\r"));
247 expect(parser.next()._tag).toBe("Incomplete");
248 parser.push(bytes("\n"));
249 expect(parser.next()).toEqual({ _tag: "Reply", value: "OK" });
250 });
251 });
252
253 describe("protocol errors", { tags: ["unit", "local"] }, () => {
254 test("unknown type byte", () => {
255 const result = decode("xOK\r\n");
256 expect(result._tag).toBe("Protocol");
257 if (result._tag === "Protocol") {
258 expect(result.error).toBeInstanceOf(ProtocolError);
259 }
260 });
261
262 test("incomplete value", () => {
263 const result = decode("$6\r\nfoo");
264 expect(result._tag).toBe("Protocol");
265 });
266
267 test("encode helpers used by servers", () => {
268 expect(asReply(encodeBoolean(true))).toBe(true);
269 expect(asReply(encodeDouble(1.5))).toBe(1.5);
270 expect(asError(encodeError("ERR boom")).code).toBe("ERR");
271 expect(asReply(encodeNull())).toBeNull();
272 expect(asReply(encodeNullArray())).toBeNull();
273 });
274 });