@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, 04:45 UTC

main
ts 793 lines 30.4 KB
Raw
1 import { PgProtocol } from "@effect/sql-pg"
2 import { assert, describe, it } from "@effect/vitest"
3 import * as Result from "effect/Result"
4 import { backend, bytes, frontend } from "./fixtures/goldens.ts"
5
6 const hex = (value: Uint8Array): string => Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("")
7
8 const success = <A, E>(result: Result.Result<A, E>): A => {
9 assert.isTrue(Result.isSuccess(result))
10 return (result as Result.Success<A, E>).success
11 }
12
13 const parseOne = (golden: string): PgProtocol.BackendMessage => {
14 const messages = PgProtocol.makeParser().push(bytes(golden))
15 assert.strictEqual(messages.length, 1)
16 return messages[0]
17 }
18
19 const assertThrowsTagged = (tag: string, run: () => unknown, message?: string): void => {
20 try {
21 run()
22 } catch (error) {
23 assert.strictEqual((error as { readonly _tag?: string })._tag, tag)
24 if (message !== undefined) assert.strictEqual((error as Error).message, message)
25 return
26 }
27 assert.fail(`Expected ${tag}`)
28 }
29
30 const assertParseFailure = (golden: string): void =>
31 assertThrowsTagged("PgProtocolParseError", () => PgProtocol.makeParser().push(bytes(golden)))
32
33 describe("PgProtocol", () => {
34 describe("special messages", () => {
35 it("encodes an SSLRequest", () => {
36 assert.strictEqual(hex(PgProtocol.encodeSslRequest()), frontend.sslRequest)
37 })
38
39 it("decodes the SSLRequest response byte", () => {
40 assert.strictEqual(success(PgProtocol.decodeSslResponse(0x53)), "S")
41 assert.strictEqual(success(PgProtocol.decodeSslResponse(0x4e)), "N")
42 const invalid = PgProtocol.decodeSslResponse(0x41)
43 assert.isTrue(Result.isFailure(invalid))
44 if (Result.isFailure(invalid)) assert.strictEqual(invalid.failure._tag, "PgProtocolParseError")
45 })
46
47 it("encodes a StartupMessage", () => {
48 const encoded = PgProtocol.encodeStartupMessage({
49 user: "effect",
50 database: "effect",
51 application_name: "effect-pg-codec"
52 })
53 assert.strictEqual(hex(encoded), frontend.startupMessage)
54 })
55
56 it("keeps an explicit client_encoding", () => {
57 const encoded = PgProtocol.encodeStartupMessage({ user: "effect", client_encoding: "UTF8" })
58 assert.strictEqual(
59 hex(encoded),
60 "0000002a00030000757365720065666665637400636c69656e745f656e636f64696e6700555446380000"
61 )
62 })
63
64 it("encodes a CancelRequest", () => {
65 const encoded = PgProtocol.encodeCancelRequest({ pid: 63, secret: 166060928 })
66 assert.strictEqual(hex(encoded), frontend.cancelRequest)
67 })
68 })
69
70 describe("frontend messages", () => {
71 it("encodes Parse", () => {
72 assert.strictEqual(
73 hex(success(PgProtocol.encodeParse({ name: "s1", query: "SELECT $1", parameterTypes: [23] }))),
74 frontend.parse
75 )
76 })
77
78 it("encodes Bind with binary parameter and result formats", () => {
79 const encoded = success(PgProtocol.encodeBind({
80 portal: "p1",
81 statement: "s1",
82 parameters: [bytes("00000001"), null]
83 }))
84 assert.strictEqual(hex(encoded), frontend.bind)
85 })
86
87 it("encodes strings past the ASCII fast path", () => {
88 const encoder = new TextEncoder()
89 for (
90 const query of [
91 "SELECT $1",
92 `SELECT ${"c".repeat(200)} FROM t WHERE id = $1`,
93 "SELECT 'héllo ☃' , '👋🏽' FROM t WHERE id = $1",
94 "é",
95 ""
96 ]
97 ) {
98 const encoded = success(PgProtocol.encodeParse({ name: "s1", query, parameterTypes: [23] }))
99 const body = encoder.encode(query)
100 assert.deepStrictEqual(encoded.subarray(8, 8 + body.length), body)
101 assert.strictEqual(encoded[8 + body.length], 0)
102 assert.strictEqual(encoded.length, 8 + body.length + 1 + 2 + 4)
103 }
104 })
105
106 it("encodes Bind through a value sink", () => {
107 const encodeBind = PgProtocol.makeBindEncoder<Uint8Array | null>((sink, value) => {
108 if (value === null) sink.sqlNull()
109 else sink.raw(value)
110 return Result.void
111 })
112 assert.strictEqual(
113 hex(success(encodeBind({ portal: "p1", statement: "s1", parameters: [bytes("00000001"), null] }))),
114 frontend.bind
115 )
116 })
117
118 it("frames each sink-written parameter with the bytes it wrote", () => {
119 const encodeBind = PgProtocol.makeBindEncoder<number>((sink, value) => {
120 sink.int16(value)
121 sink.utf8("é")
122 sink.float64(value)
123 return Result.void
124 })
125 const encoded = success(encodeBind({ portal: "", statement: "", parameters: [1, 2] }))
126 // 1 type byte, 4 length, 2 empty cStrings, 3 int16 of format codes and
127 // count, then each parameter as its int32 length and 12 bytes of body
128 const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength)
129 assert.strictEqual(view.getInt32(13), 12)
130 assert.strictEqual(view.getInt16(17), 1)
131 assert.strictEqual(view.getFloat64(21), 1)
132 assert.strictEqual(view.getInt32(29), 12)
133 assert.strictEqual(view.getFloat64(37), 2)
134 })
135
136 it("keeps sink-written parameters intact when the pool grows mid-message", () => {
137 const encodeBind = PgProtocol.makeBindEncoder<string>((sink, value) => {
138 sink.utf8(value)
139 return Result.void
140 })
141 const long = "x".repeat(16 * 1024)
142 const encoded = success(encodeBind({ portal: "", statement: "", parameters: ["ab", long, "cd"] }))
143 assert.deepStrictEqual(
144 encoded,
145 success(PgProtocol.encodeBind({
146 portal: "",
147 statement: "",
148 parameters: ["ab", long, "cd"].map((value) => new TextEncoder().encode(value))
149 }))
150 )
151 })
152
153 it("encodes Execute", () => {
154 assert.strictEqual(hex(PgProtocol.encodeExecute({ portal: "p1", maxRows: 5 })), frontend.execute)
155 })
156
157 it("encodes Describe and Close", () => {
158 assert.strictEqual(
159 hex(PgProtocol.encodeDescribe({ target: "statement", name: "s1" })),
160 frontend.describeStatement
161 )
162 assert.strictEqual(hex(PgProtocol.encodeClose({ target: "portal", name: "p1" })), frontend.closePortal)
163 })
164
165 it("encodes the empty control messages", () => {
166 assert.strictEqual(hex(PgProtocol.encodeSync()), frontend.sync)
167 assert.strictEqual(hex(PgProtocol.encodeFlush()), frontend.flush)
168 assert.strictEqual(hex(PgProtocol.encodeTerminate()), frontend.terminate)
169 })
170
171 it("encodes the password messages", () => {
172 assert.strictEqual(
173 hex(PgProtocol.encodePasswordMessage({ password: "md5abc" })),
174 frontend.passwordMessage
175 )
176 assert.strictEqual(
177 hex(PgProtocol.encodeSASLInitialResponse({
178 mechanism: "SCRAM-SHA-256",
179 initialResponse: bytes("6e2c2c")
180 })),
181 frontend.saslInitialResponse
182 )
183 assert.strictEqual(
184 hex(PgProtocol.encodeSASLInitialResponse({ mechanism: "SCRAM-SHA-256", initialResponse: null })),
185 frontend.saslInitialResponseEmpty
186 )
187 assert.strictEqual(hex(PgProtocol.encodeSASLResponse({ data: bytes("010203") })), frontend.saslResponse)
188 })
189
190 it("dispatches encode over the tagged union", () => {
191 const cases: ReadonlyArray<readonly [PgProtocol.FrontendMessage, Uint8Array]> = [
192 [
193 { _tag: "Parse", name: "s1", query: "SELECT $1", parameterTypes: [23] },
194 success(PgProtocol.encodeParse({ name: "s1", query: "SELECT $1", parameterTypes: [23] }))
195 ],
196 [
197 { _tag: "Bind", portal: "p1", statement: "s1", parameters: [bytes("00000001"), null] },
198 success(PgProtocol.encodeBind({ portal: "p1", statement: "s1", parameters: [bytes("00000001"), null] }))
199 ],
200 [{ _tag: "Execute", portal: "p1", maxRows: 5 }, PgProtocol.encodeExecute({ portal: "p1", maxRows: 5 })],
201 [
202 { _tag: "Describe", target: "statement", name: "s1" },
203 PgProtocol.encodeDescribe({ target: "statement", name: "s1" })
204 ],
205 [
206 { _tag: "Close", target: "portal", name: "p1" },
207 PgProtocol.encodeClose({ target: "portal", name: "p1" })
208 ],
209 [{ _tag: "Sync" }, PgProtocol.encodeSync()],
210 [{ _tag: "Flush" }, PgProtocol.encodeFlush()],
211 [{ _tag: "Terminate" }, PgProtocol.encodeTerminate()],
212 [
213 { _tag: "PasswordMessage", password: "md5abc" },
214 PgProtocol.encodePasswordMessage({ password: "md5abc" })
215 ],
216 [
217 { _tag: "SASLInitialResponse", mechanism: "SCRAM-SHA-256", initialResponse: bytes("6e2c2c") },
218 PgProtocol.encodeSASLInitialResponse({ mechanism: "SCRAM-SHA-256", initialResponse: bytes("6e2c2c") })
219 ],
220 [{ _tag: "SASLResponse", data: bytes("010203") }, PgProtocol.encodeSASLResponse({ data: bytes("010203") })]
221 ]
222 for (const [message, expected] of cases) {
223 assert.deepStrictEqual(success(PgProtocol.encode(message)), expected)
224 }
225 })
226
227 it("writes the actual typed frame length into every message", () => {
228 const messages = [
229 success(PgProtocol.encodeParse({ name: "s1", query: "SELECT $1", parameterTypes: [23] })),
230 success(PgProtocol.encodeBind({ portal: "p1", statement: "s1", parameters: [bytes("00000001"), null] })),
231 PgProtocol.encodeExecute({ portal: "p1", maxRows: 5 }),
232 PgProtocol.encodeDescribe({ target: "statement", name: "s1" }),
233 PgProtocol.encodeClose({ target: "portal", name: "p1" }),
234 PgProtocol.encodeSync(),
235 PgProtocol.encodeFlush(),
236 PgProtocol.encodeTerminate(),
237 PgProtocol.encodePasswordMessage({ password: "md5abc" }),
238 PgProtocol.encodeSASLInitialResponse({ mechanism: "SCRAM-SHA-256", initialResponse: bytes("6e2c2c") }),
239 PgProtocol.encodeSASLResponse({ data: bytes("010203") })
240 ]
241 for (const message of messages) {
242 assert.strictEqual(
243 new DataView(message.buffer, message.byteOffset, message.byteLength).getInt32(1),
244 message.length - 1
245 )
246 }
247 })
248
249 it("accepts the maximum unsigned parameter count and rejects the next value", () => {
250 const encodeBind = PgProtocol.makeBindEncoder<Uint8Array | null>((sink, value) => {
251 if (value === null) sink.sqlNull()
252 else sink.raw(value)
253 return Result.void
254 })
255 const maxOids = new Array<number>(0xffff).fill(23)
256 const maxParameters = new Array<Uint8Array | null>(0xffff).fill(null)
257 const parse = success(PgProtocol.encodeParse({ name: "", query: "", parameterTypes: maxOids }))
258 const bind = success(PgProtocol.encodeBind({ portal: "", statement: "", parameters: maxParameters }))
259 const fused = success(encodeBind({ portal: "", statement: "", parameters: maxParameters }))
260 assert.strictEqual(new DataView(parse.buffer, parse.byteOffset, parse.byteLength).getUint16(7), 0xffff)
261 assert.strictEqual(new DataView(bind.buffer, bind.byteOffset, bind.byteLength).getUint16(11), 0xffff)
262 assert.deepStrictEqual(fused, bind)
263
264 const tooManyOids = new Array<number>(0x10000).fill(23)
265 const tooManyParameters = new Array<Uint8Array | null>(0x10000).fill(null)
266 const parseFailure = PgProtocol.encodeParse({ name: "", query: "", parameterTypes: tooManyOids })
267 const bindFailure = PgProtocol.encodeBind({ portal: "", statement: "", parameters: tooManyParameters })
268 const fusedFailure = encodeBind({ portal: "", statement: "", parameters: tooManyParameters })
269 assert.isTrue(Result.isFailure(parseFailure))
270 assert.isTrue(Result.isFailure(bindFailure))
271 assert.isTrue(Result.isFailure(fusedFailure))
272 })
273 })
274
275 describe("authentication messages", () => {
276 it("decodes AuthenticationOk", () => {
277 assert.deepStrictEqual(parseOne(backend.authenticationOk), { _tag: "AuthenticationOk" })
278 })
279
280 it("decodes AuthenticationCleartextPassword", () => {
281 assert.deepStrictEqual(parseOne(backend.authenticationCleartextPassword), {
282 _tag: "AuthenticationCleartextPassword"
283 })
284 })
285
286 it("decodes AuthenticationMD5Password", () => {
287 assert.deepStrictEqual(parseOne(backend.authenticationMD5Password), {
288 _tag: "AuthenticationMD5Password",
289 salt: bytes("70e7d45e")
290 })
291 })
292
293 it("decodes AuthenticationSASL", () => {
294 assert.deepStrictEqual(parseOne(backend.authenticationSASL), {
295 _tag: "AuthenticationSASL",
296 mechanisms: ["SCRAM-SHA-256"]
297 })
298 })
299
300 it("decodes the SASL continuation payloads as opaque bytes", () => {
301 const cont = parseOne(backend.authenticationSASLContinue)
302 assert.strictEqual(cont._tag, "AuthenticationSASLContinue")
303 assert.strictEqual(
304 new TextDecoder().decode((cont as PgProtocol.AuthenticationSASLContinue).data).slice(0, 2),
305 "r="
306 )
307 const final = parseOne(backend.authenticationSASLFinal)
308 assert.strictEqual(final._tag, "AuthenticationSASLFinal")
309 })
310
311 it("reports unsupported authentication methods", () => {
312 // AuthenticationGSS, method 7
313 assert.deepStrictEqual(parseOne("520000000800000007"), {
314 _tag: "AuthenticationUnsupported",
315 method: 7,
316 payload: new Uint8Array(0)
317 })
318 })
319
320 it("rejects truncated authentication fields", () => {
321 for (
322 const frame of [
323 "5200000007000000", // truncated authentication method
324 "520000000b00000005010203", // three-byte MD5 salt
325 "520000000e0000000a534352414d00" // SASL mechanism list without its empty terminator
326 ]
327 ) {
328 assertParseFailure(frame)
329 }
330 })
331 })
332
333 describe("backend messages", () => {
334 it("decodes ParameterStatus", () => {
335 assert.deepStrictEqual(parseOne(backend.parameterStatus), {
336 _tag: "ParameterStatus",
337 name: "in_hot_standby",
338 value: "off"
339 })
340 })
341
342 it("decodes BackendKeyData", () => {
343 assert.deepStrictEqual(parseOne(backend.backendKeyData), {
344 _tag: "BackendKeyData",
345 pid: 63,
346 secret: 166060928
347 })
348 })
349
350 it("decodes ReadyForQuery", () => {
351 assert.deepStrictEqual(parseOne(backend.readyForQuery), { _tag: "ReadyForQuery", status: "I" })
352 })
353
354 // ParameterStatus is two C-strings and nothing else, so it is the cheapest
355 // way to drive the string decoder across the length its fast path covers.
356 const parameterStatus = (name: string, value: string): Uint8Array => {
357 const encoder = new TextEncoder()
358 const encode = (text: string) => encoder.encode(text)
359 return frame(encode(name), encode(value))
360 }
361
362 const frame = (name: Uint8Array, value: Uint8Array): Uint8Array => {
363 const length = 4 + name.length + 1 + value.length + 1
364 const message = new Uint8Array(1 + length)
365 message[0] = 0x53
366 new DataView(message.buffer).setInt32(1, length)
367 message.set(name, 5)
368 message.set(value, 6 + name.length)
369 return message
370 }
371
372 it("decodes parameter names of every length across the string fast path", () => {
373 for (let length = 0; length <= 16; length++) {
374 const name = "abcdefgh".repeat(2).slice(0, length)
375 assert.deepStrictEqual(PgProtocol.makeParser().push(parameterStatus(name, "v")), [
376 { _tag: "ParameterStatus", name, value: "v" }
377 ])
378 }
379 })
380
381 it("decodes a multi-byte character at every position of the string fast path", () => {
382 for (let prefix = 0; prefix <= 16; prefix++) {
383 const name = "a".repeat(prefix) + "é☃"
384 assert.deepStrictEqual(PgProtocol.makeParser().push(parameterStatus(name, "v")), [
385 { _tag: "ParameterStatus", name, value: "v" }
386 ])
387 }
388 })
389
390 it("decodes a parameter that really contains the replacement character", () => {
391 const name = "status\ufffdmessage and some padding"
392 assert.deepStrictEqual(
393 PgProtocol.makeParser().push(parameterStatus(name, "v")),
394 [{ _tag: "ParameterStatus", name, value: "v" }]
395 )
396 })
397
398 it("rejects a stray high byte at every position of the string fast path", () => {
399 for (let length = 1; length <= 16; length++) {
400 for (let at = 0; at < length; at++) {
401 const name = new Uint8Array(length).fill(0x61)
402 name[at] = 0xc3
403 assertThrowsTagged(
404 "PgProtocolParseError",
405 () => PgProtocol.makeParser().push(frame(name, new Uint8Array([0x76])))
406 )
407 }
408 }
409 })
410
411 it("decodes RowDescription", () => {
412 assert.deepStrictEqual(parseOne(backend.rowDescription), {
413 _tag: "RowDescription",
414 fields: [
415 {
416 name: "a",
417 tableOid: 0,
418 columnAttributeNumber: 0,
419 dataTypeOid: 23,
420 dataTypeSize: 4,
421 typeModifier: -1,
422 format: 1
423 },
424 {
425 name: "b",
426 tableOid: 0,
427 columnAttributeNumber: 0,
428 dataTypeOid: 25,
429 dataTypeSize: -1,
430 typeModifier: -1,
431 format: 1
432 }
433 ]
434 })
435 })
436
437 it("decodes DataRow as raw bytes, with null for SQL NULL", () => {
438 assert.deepStrictEqual(parseOne(backend.dataRowTwoColumns), {
439 _tag: "DataRow",
440 values: [bytes("00000001"), bytes("78")]
441 })
442 assert.deepStrictEqual(parseOne(backend.dataRowWithNull), {
443 _tag: "DataRow",
444 values: [bytes("0000000000000007"), null]
445 })
446 })
447
448 it("decodes ParameterDescription", () => {
449 assert.deepStrictEqual(parseOne(backend.parameterDescription), {
450 _tag: "ParameterDescription",
451 parameterTypes: [20]
452 })
453 })
454
455 it("decodes CommandComplete", () => {
456 assert.deepStrictEqual(parseOne(backend.commandComplete), {
457 _tag: "CommandComplete",
458 commandTag: "SELECT 1"
459 })
460 })
461
462 it("decodes the empty acknowledgements", () => {
463 assert.deepStrictEqual(parseOne(backend.parseComplete), { _tag: "ParseComplete" })
464 assert.deepStrictEqual(parseOne(backend.bindComplete), { _tag: "BindComplete" })
465 assert.deepStrictEqual(parseOne(backend.closeComplete), { _tag: "CloseComplete" })
466 assert.deepStrictEqual(parseOne(backend.portalSuspended), { _tag: "PortalSuspended" })
467 assert.deepStrictEqual(parseOne(backend.emptyQueryResponse), { _tag: "EmptyQueryResponse" })
468 assert.deepStrictEqual(parseOne(backend.noData), { _tag: "NoData" })
469 })
470
471 it("decodes ErrorResponse fields by name", () => {
472 assert.deepStrictEqual(parseOne(backend.errorResponse), {
473 _tag: "ErrorResponse",
474 fields: {
475 severity: "ERROR",
476 severityUnlocalized: "ERROR",
477 code: "22012",
478 message: "division by zero",
479 file: "int.c",
480 line: "870",
481 routine: "int4div"
482 }
483 })
484 })
485
486 it("decodes NoticeResponse", () => {
487 const notice = parseOne(backend.noticeResponse)
488 assert.strictEqual(notice._tag, "NoticeResponse")
489 assert.strictEqual((notice as PgProtocol.NoticeResponse).fields.code, "00000")
490 assert.strictEqual((notice as PgProtocol.NoticeResponse).fields.severity, "NOTICE")
491 })
492
493 it("decodes NotificationResponse", () => {
494 assert.deepStrictEqual(parseOne(backend.notificationResponse), {
495 _tag: "NotificationResponse",
496 pid: 63,
497 channel: "effect_channel",
498 payload: "payload text"
499 })
500 })
501
502 it("decodes NegotiateProtocolVersion", () => {
503 // minor version 0, one unrecognised option "_pq_.foo"
504 assert.deepStrictEqual(parseOne("760000001500000000000000015f70715f2e666f6f00"), {
505 _tag: "NegotiateProtocolVersion",
506 minorVersion: 0,
507 unrecognizedOptions: ["_pq_.foo"]
508 })
509 })
510
511 it("decodes the COPY messages", () => {
512 assert.deepStrictEqual(parseOne("470000000b00000200000001"), {
513 _tag: "CopyInResponse",
514 format: 0,
515 columnFormats: [0, 1]
516 })
517 assert.deepStrictEqual(parseOne("48000000090100010000"), {
518 _tag: "CopyOutResponse",
519 format: 1,
520 columnFormats: [0]
521 })
522 assert.deepStrictEqual(parseOne("57000000090100010000"), {
523 _tag: "CopyBothResponse",
524 format: 1,
525 columnFormats: [0]
526 })
527 assert.deepStrictEqual(parseOne("6400000008010203ff"), {
528 _tag: "CopyData",
529 data: bytes("010203ff")
530 })
531 assert.deepStrictEqual(parseOne("6300000004"), { _tag: "CopyDone" })
532 assert.deepStrictEqual(parseOne("6400000004"), { _tag: "CopyData", data: new Uint8Array(0) })
533 })
534
535 it("reports an unknown type byte instead of failing", () => {
536 assert.deepStrictEqual(parseOne("5f00000008deadbeef"), {
537 _tag: "Unknown",
538 type: 0x5f,
539 payload: bytes("deadbeef")
540 })
541 assert.deepStrictEqual(parseOne("5f00000004"), {
542 _tag: "Unknown",
543 type: 0x5f,
544 payload: new Uint8Array(0)
545 })
546 })
547 })
548
549 describe("incremental parsing", () => {
550 it("buffers a message split across two chunks", () => {
551 const parser = PgProtocol.makeParser()
552 const frame = bytes(backend.dataRowTwoColumns)
553 assert.deepStrictEqual(parser.push(frame.subarray(0, 7)), [])
554 const messages = parser.push(frame.subarray(7))
555 assert.strictEqual(messages.length, 1)
556 assert.strictEqual(messages[0]._tag, "DataRow")
557 })
558
559 it("pushEach hands over a message before it reads the next", () => {
560 const parser = PgProtocol.makeParser<unknown>()
561 const seen: Array<PgProtocol.BackendMessage<unknown>> = []
562 parser.pushEach(bytes(backend.rowDescription + backend.dataRowTwoColumns), (message) => {
563 // A row's columns are only known from the description in front of it,
564 // so installing the reader here has to reach the rows behind it.
565 if (message._tag === "RowDescription") {
566 parser.readField = (bytes, offset, size) => (size < 0 ? null : hex(bytes.subarray(offset, offset + size)))
567 }
568 seen.push(message)
569 })
570 assert.strictEqual(seen.length, 2)
571 assert.strictEqual(seen[0]._tag, "RowDescription")
572 assert.deepStrictEqual(seen[1], { _tag: "DataRow", values: ["00000001", "78"] })
573 })
574
575 it("pushEach keeps the messages it handed over before a failure", () => {
576 const parser = PgProtocol.makeParser()
577 const seen: Array<PgProtocol.BackendMessage> = []
578 assertThrowsTagged(
579 "PgProtocolParseError",
580 () => parser.pushEach(bytes(backend.parseComplete + "4480000000"), (message) => seen.push(message))
581 )
582 assert.deepStrictEqual(seen, [{ _tag: "ParseComplete" }])
583 })
584
585 it("returns both messages when one chunk holds two", () => {
586 const parser = PgProtocol.makeParser()
587 const chunk = bytes(backend.parseComplete + backend.bindComplete)
588 assert.deepStrictEqual(parser.push(chunk), [{ _tag: "ParseComplete" }, { _tag: "BindComplete" }])
589 })
590
591 it("returns every message when one chunk holds many", () => {
592 const parser = PgProtocol.makeParser()
593 const messages = parser.push(bytes(backend.parseComplete.repeat(2_000)))
594 assert.strictEqual(messages.length, 2_000)
595 assert.strictEqual(messages.every((message) => message._tag === "ParseComplete"), true)
596 })
597
598 it("keeps the trailing partial message across pushes", () => {
599 const parser = PgProtocol.makeParser()
600 const chunk = bytes(backend.parseComplete + backend.readyForQuery)
601 assert.deepStrictEqual(parser.push(chunk.subarray(0, 8)), [{ _tag: "ParseComplete" }])
602 assert.deepStrictEqual(parser.push(chunk.subarray(8)), [{ _tag: "ReadyForQuery", status: "I" }])
603 })
604
605 it("handles a byte-at-a-time stream", () => {
606 const parser = PgProtocol.makeParser()
607 const frame = bytes(backend.rowDescription)
608 const messages: Array<PgProtocol.BackendMessage> = []
609 for (let i = 0; i < frame.length; i++) {
610 messages.push(...parser.push(frame.subarray(i, i + 1)))
611 }
612 assert.strictEqual(messages.length, 1)
613 assert.strictEqual(messages[0]._tag, "RowDescription")
614 })
615
616 it("grows its buffer for a large fragmented DataRow", () => {
617 const field = new Uint8Array(40 * 1024)
618 for (let index = 0; index < field.length; index++) field[index] = index % 251
619 const frame = new Uint8Array(11 + field.length)
620 const view = new DataView(frame.buffer)
621 frame[0] = 0x44
622 view.setInt32(1, frame.length - 1)
623 view.setInt16(5, 1)
624 view.setInt32(7, field.length)
625 frame.set(field, 11)
626
627 const parser = PgProtocol.makeParser()
628 const messages: Array<PgProtocol.BackendMessage> = []
629 for (let offset = 0; offset < frame.length; offset += 1024) {
630 messages.push(...parser.push(frame.subarray(offset, offset + 1024)))
631 }
632 assert.strictEqual(messages.length, 1)
633 assert.strictEqual(messages[0]._tag, "DataRow")
634 assert.deepStrictEqual((messages[0] as PgProtocol.DataRow).values, [field])
635 })
636
637 it("rejects a length prefix above maxMessageSize", () => {
638 const parser = PgProtocol.makeParser()
639 assertThrowsTagged("PgProtocolParseError", () => parser.push(bytes("447fffffff0000")))
640 })
641
642 it("honours a custom maxMessageSize", () => {
643 const parser = PgProtocol.makeParser({ maxMessageSize: 8 })
644 assertThrowsTagged("PgProtocolParseError", () => parser.push(bytes(backend.rowDescription)))
645 })
646
647 it("rejects a length prefix below the minimum", () => {
648 const parser = PgProtocol.makeParser()
649 assertThrowsTagged("PgProtocolParseError", () => parser.push(bytes("4400000003ff")))
650 assertThrowsTagged("PgProtocolParseError", () => PgProtocol.makeParser().push(bytes("4480000000")))
651 })
652
653 it("accepts a frame exactly at maxMessageSize", () => {
654 assert.deepStrictEqual(PgProtocol.makeParser({ maxMessageSize: 8 }).push(bytes("5f00000008deadbeef")), [
655 { _tag: "Unknown", type: 0x5f, payload: bytes("deadbeef") }
656 ])
657 })
658
659 it("rejects a truncated payload", () => {
660 // CommandComplete whose command tag is never NUL-terminated
661 assertParseFailure("430000000953454c454354")
662 })
663
664 it("rejects payload bytes beyond a message's declared fields", () => {
665 for (
666 const frame of [
667 "3100000005ff", // ParseComplete with a byte of payload
668 "44000000070000ff" // DataRow declares zero fields but carries a byte
669 ]
670 ) {
671 assertParseFailure(frame)
672 }
673 })
674
675 it("rejects a DataRow field length below the NULL sentinel", () => {
676 assertParseFailure("440000000a0001fffffffe")
677 })
678
679 it("rejects a negative DataRow field count", () => {
680 assertParseFailure("4400000006ffff")
681 })
682
683 it("rejects negative collection counts", () => {
684 for (
685 const frame of [
686 "5400000006ffff", // RowDescription
687 "7400000006ffff", // ParameterDescription
688 "470000000700ffff", // CopyInResponse
689 "480000000700ffff", // CopyOutResponse
690 "570000000700ffff", // CopyBothResponse
691 "760000000c00000000ffffffff" // NegotiateProtocolVersion
692 ]
693 ) {
694 assertParseFailure(frame)
695 }
696 })
697
698 it("rejects a truncated DataRow field length", () => {
699 assertParseFailure("440000000800010000")
700 assertParseFailure("4400000004")
701 })
702
703 it("rejects invalid statuses and UTF-8", () => {
704 assertParseFailure("5a0000000558")
705 assertParseFailure("5300000008ff007800")
706 })
707
708 it("does not read a DataRow field past the end of its own message", () => {
709 // One field that claims ten bytes in a message carrying two, followed by
710 // a complete message the field must not be allowed to reach into
711 assertThrowsTagged(
712 "PgProtocolParseError",
713 () => PgProtocol.makeParser().push(bytes(`440000000c00010000000a0102${backend.parseComplete}`))
714 )
715 })
716
717 it("cannot be reused after a malformed frame", () => {
718 const parser = PgProtocol.makeParser()
719 assertThrowsTagged(
720 "PgProtocolParseError",
721 () => parser.push(bytes(`${backend.parseComplete}430000000953454c454354`))
722 )
723 assertThrowsTagged(
724 "PgProtocolParseError",
725 () => parser.push(bytes(backend.bindComplete)),
726 "Parser cannot be reused after a failure"
727 )
728 })
729
730 it("does not read a string past the end of its own message", () => {
731 // CommandComplete whose tag is not NUL-terminated, followed by a message
732 // whose length prefix contains NUL bytes
733 assertThrowsTagged(
734 "PgProtocolParseError",
735 () => PgProtocol.makeParser().push(bytes(`430000000a53454c454354${backend.parseComplete}`))
736 )
737 })
738 })
739
740 describe("buffer reuse", () => {
741 it("keeps DataRow field views valid across later pushes", () => {
742 const parser = PgProtocol.makeParser()
743 const frame = bytes(backend.dataRowTwoColumns)
744 const first = parser.push(frame)[0] as PgProtocol.DataRow
745 const snapshot = first.values.map((value) => value === null ? null : value.slice())
746 // enough to run past the parser's buffer and force a replacement
747 for (let index = 0; index < 2000; index++) parser.push(frame)
748 assert.deepStrictEqual(first.values, snapshot)
749 })
750
751 it("keeps DataRow field views valid as the buffer pool grows", () => {
752 const parser = PgProtocol.makeParser()
753 const frame = bytes(backend.dataRowTwoColumns)
754 const retained: Array<{ readonly row: PgProtocol.DataRow; readonly snapshot: Array<Uint8Array | null> }> = []
755 // enough pushes to run the pool from its initial size up to its ceiling
756 for (let index = 0; index < 5000; index++) {
757 const row = parser.push(frame)[0] as PgProtocol.DataRow
758 if (index % 500 === 0) {
759 retained.push({ row, snapshot: row.values.map((value) => value === null ? null : value.slice()) })
760 }
761 }
762 for (const { row, snapshot } of retained) {
763 assert.deepStrictEqual(row.values, snapshot)
764 }
765 })
766
767 it("keeps an encoded frame valid after encoding more", () => {
768 const first = success(PgProtocol.encodeBind({
769 portal: "portal",
770 statement: "statement",
771 parameters: [bytes("0102030405")]
772 }))
773 const snapshot = first.slice()
774 for (let index = 0; index < 100; index++) {
775 success(PgProtocol.encodeBind({ portal: "other", statement: "s", parameters: [new Uint8Array(64)] }))
776 }
777 assert.deepStrictEqual(first, snapshot)
778 })
779
780 it("keeps an encoded frame valid after an oversized one", () => {
781 const first = PgProtocol.encodeSync()
782 const snapshot = first.slice()
783 const huge = success(PgProtocol.encodeBind({
784 portal: "",
785 statement: "",
786 parameters: [new Uint8Array(32 * 1024)]
787 }))
788 assert.strictEqual(huge.length, 32 * 1024 + 21)
789 assert.deepStrictEqual(first, snapshot)
790 assert.deepStrictEqual(PgProtocol.encodeSync(), snapshot)
791 })
792 })
793 })