Open History to see the last commit
1import { PgProtocol } from "@effect/sql-pg"
2import { assert, describe, it } from "@effect/vitest"
3import * as Result from "effect/Result"
4import { backend, bytes, frontend } from "./fixtures/goldens.ts"
5
6const hex = (value: Uint8Array): string => Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("")
7
8const 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
13const 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
19const 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
30const assertParseFailure = (golden: string): void =>
31 assertThrowsTagged("PgProtocolParseError", () => PgProtocol.makeParser().push(bytes(golden)))
32
33describe("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("keeps a leading U+FEFF when the string contains U+FFFD", () => {
399 const name = "\ufeffnote\ufffd"
400 assert.deepStrictEqual(
401 PgProtocol.makeParser().push(parameterStatus(name, name)),
402 [{ _tag: "ParameterStatus", name, value: name }]
403 )
404 })
405
406 it("rejects a stray high byte at every position of the string fast path", () => {
407 for (let length = 1; length <= 16; length++) {
408 for (let at = 0; at < length; at++) {
409 const name = new Uint8Array(length).fill(0x61)
410 name[at] = 0xc3
411 assertThrowsTagged(
412 "PgProtocolParseError",
413 () => PgProtocol.makeParser().push(frame(name, new Uint8Array([0x76])))
414 )
415 }
416 }
417 })
418
419 it("decodes RowDescription", () => {
420 assert.deepStrictEqual(parseOne(backend.rowDescription), {
421 _tag: "RowDescription",
422 fields: [
423 {
424 name: "a",
425 tableOid: 0,
426 columnAttributeNumber: 0,
427 dataTypeOid: 23,
428 dataTypeSize: 4,
429 typeModifier: -1,
430 format: 1
431 },
432 {
433 name: "b",
434 tableOid: 0,
435 columnAttributeNumber: 0,
436 dataTypeOid: 25,
437 dataTypeSize: -1,
438 typeModifier: -1,
439 format: 1
440 }
441 ]
442 })
443 })
444
445 it("decodes DataRow as raw bytes, with null for SQL NULL", () => {
446 assert.deepStrictEqual(parseOne(backend.dataRowTwoColumns), {
447 _tag: "DataRow",
448 values: [bytes("00000001"), bytes("78")]
449 })
450 assert.deepStrictEqual(parseOne(backend.dataRowWithNull), {
451 _tag: "DataRow",
452 values: [bytes("0000000000000007"), null]
453 })
454 })
455
456 it("decodes ParameterDescription", () => {
457 assert.deepStrictEqual(parseOne(backend.parameterDescription), {
458 _tag: "ParameterDescription",
459 parameterTypes: [20]
460 })
461 })
462
463 it("decodes CommandComplete", () => {
464 assert.deepStrictEqual(parseOne(backend.commandComplete), {
465 _tag: "CommandComplete",
466 commandTag: "SELECT 1"
467 })
468 })
469
470 it("decodes the empty acknowledgements", () => {
471 assert.deepStrictEqual(parseOne(backend.parseComplete), { _tag: "ParseComplete" })
472 assert.deepStrictEqual(parseOne(backend.bindComplete), { _tag: "BindComplete" })
473 assert.deepStrictEqual(parseOne(backend.closeComplete), { _tag: "CloseComplete" })
474 assert.deepStrictEqual(parseOne(backend.portalSuspended), { _tag: "PortalSuspended" })
475 assert.deepStrictEqual(parseOne(backend.emptyQueryResponse), { _tag: "EmptyQueryResponse" })
476 assert.deepStrictEqual(parseOne(backend.noData), { _tag: "NoData" })
477 })
478
479 it("decodes ErrorResponse fields by name", () => {
480 assert.deepStrictEqual(parseOne(backend.errorResponse), {
481 _tag: "ErrorResponse",
482 fields: {
483 severity: "ERROR",
484 severityUnlocalized: "ERROR",
485 code: "22012",
486 message: "division by zero",
487 file: "int.c",
488 line: "870",
489 routine: "int4div"
490 }
491 })
492 })
493
494 it("decodes NoticeResponse", () => {
495 const notice = parseOne(backend.noticeResponse)
496 assert.strictEqual(notice._tag, "NoticeResponse")
497 assert.strictEqual((notice as PgProtocol.NoticeResponse).fields.code, "00000")
498 assert.strictEqual((notice as PgProtocol.NoticeResponse).fields.severity, "NOTICE")
499 })
500
501 it("decodes NotificationResponse", () => {
502 assert.deepStrictEqual(parseOne(backend.notificationResponse), {
503 _tag: "NotificationResponse",
504 pid: 63,
505 channel: "effect_channel",
506 payload: "payload text"
507 })
508 })
509
510 it("decodes NegotiateProtocolVersion", () => {
511 // minor version 0, one unrecognised option "_pq_.foo"
512 assert.deepStrictEqual(parseOne("760000001500000000000000015f70715f2e666f6f00"), {
513 _tag: "NegotiateProtocolVersion",
514 minorVersion: 0,
515 unrecognizedOptions: ["_pq_.foo"]
516 })
517 })
518
519 it("decodes the COPY messages", () => {
520 assert.deepStrictEqual(parseOne("470000000b00000200000001"), {
521 _tag: "CopyInResponse",
522 format: 0,
523 columnFormats: [0, 1]
524 })
525 assert.deepStrictEqual(parseOne("48000000090100010000"), {
526 _tag: "CopyOutResponse",
527 format: 1,
528 columnFormats: [0]
529 })
530 assert.deepStrictEqual(parseOne("57000000090100010000"), {
531 _tag: "CopyBothResponse",
532 format: 1,
533 columnFormats: [0]
534 })
535 assert.deepStrictEqual(parseOne("6400000008010203ff"), {
536 _tag: "CopyData",
537 data: bytes("010203ff")
538 })
539 assert.deepStrictEqual(parseOne("6300000004"), { _tag: "CopyDone" })
540 assert.deepStrictEqual(parseOne("6400000004"), { _tag: "CopyData", data: new Uint8Array(0) })
541 })
542
543 it("reports an unknown type byte instead of failing", () => {
544 assert.deepStrictEqual(parseOne("5f00000008deadbeef"), {
545 _tag: "Unknown",
546 type: 0x5f,
547 payload: bytes("deadbeef")
548 })
549 assert.deepStrictEqual(parseOne("5f00000004"), {
550 _tag: "Unknown",
551 type: 0x5f,
552 payload: new Uint8Array(0)
553 })
554 })
555 })
556
557 describe("incremental parsing", () => {
558 it("buffers a message split across two chunks", () => {
559 const parser = PgProtocol.makeParser()
560 const frame = bytes(backend.dataRowTwoColumns)
561 assert.deepStrictEqual(parser.push(frame.subarray(0, 7)), [])
562 const messages = parser.push(frame.subarray(7))
563 assert.strictEqual(messages.length, 1)
564 assert.strictEqual(messages[0]._tag, "DataRow")
565 })
566
567 it("pushEach hands over a message before it reads the next", () => {
568 const parser = PgProtocol.makeParser<unknown>()
569 const seen: Array<PgProtocol.BackendMessage<unknown>> = []
570 parser.pushEach(bytes(backend.rowDescription + backend.dataRowTwoColumns), (message) => {
571 // A row's columns are only known from the description in front of it,
572 // so installing the reader here has to reach the rows behind it.
573 if (message._tag === "RowDescription") {
574 parser.readField = (bytes, offset, size) => (size < 0 ? null : hex(bytes.subarray(offset, offset + size)))
575 }
576 seen.push(message)
577 })
578 assert.strictEqual(seen.length, 2)
579 assert.strictEqual(seen[0]._tag, "RowDescription")
580 assert.deepStrictEqual(seen[1], { _tag: "DataRow", values: ["00000001", "78"] })
581 })
582
583 it("pushEach keeps the messages it handed over before a failure", () => {
584 const parser = PgProtocol.makeParser()
585 const seen: Array<PgProtocol.BackendMessage> = []
586 assertThrowsTagged(
587 "PgProtocolParseError",
588 () => parser.pushEach(bytes(backend.parseComplete + "4480000000"), (message) => seen.push(message))
589 )
590 assert.deepStrictEqual(seen, [{ _tag: "ParseComplete" }])
591 })
592
593 it("returns both messages when one chunk holds two", () => {
594 const parser = PgProtocol.makeParser()
595 const chunk = bytes(backend.parseComplete + backend.bindComplete)
596 assert.deepStrictEqual(parser.push(chunk), [{ _tag: "ParseComplete" }, { _tag: "BindComplete" }])
597 })
598
599 it("returns every message when one chunk holds many", () => {
600 const parser = PgProtocol.makeParser()
601 const messages = parser.push(bytes(backend.parseComplete.repeat(2_000)))
602 assert.strictEqual(messages.length, 2_000)
603 assert.strictEqual(messages.every((message) => message._tag === "ParseComplete"), true)
604 })
605
606 it("keeps the trailing partial message across pushes", () => {
607 const parser = PgProtocol.makeParser()
608 const chunk = bytes(backend.parseComplete + backend.readyForQuery)
609 assert.deepStrictEqual(parser.push(chunk.subarray(0, 8)), [{ _tag: "ParseComplete" }])
610 assert.deepStrictEqual(parser.push(chunk.subarray(8)), [{ _tag: "ReadyForQuery", status: "I" }])
611 })
612
613 it("handles a byte-at-a-time stream", () => {
614 const parser = PgProtocol.makeParser()
615 const frame = bytes(backend.rowDescription)
616 const messages: Array<PgProtocol.BackendMessage> = []
617 for (let i = 0; i < frame.length; i++) {
618 messages.push(...parser.push(frame.subarray(i, i + 1)))
619 }
620 assert.strictEqual(messages.length, 1)
621 assert.strictEqual(messages[0]._tag, "RowDescription")
622 })
623
624 it("grows its buffer for a large fragmented DataRow", () => {
625 const field = new Uint8Array(40 * 1024)
626 for (let index = 0; index < field.length; index++) field[index] = index % 251
627 const frame = new Uint8Array(11 + field.length)
628 const view = new DataView(frame.buffer)
629 frame[0] = 0x44
630 view.setInt32(1, frame.length - 1)
631 view.setInt16(5, 1)
632 view.setInt32(7, field.length)
633 frame.set(field, 11)
634
635 const parser = PgProtocol.makeParser()
636 const messages: Array<PgProtocol.BackendMessage> = []
637 for (let offset = 0; offset < frame.length; offset += 1024) {
638 messages.push(...parser.push(frame.subarray(offset, offset + 1024)))
639 }
640 assert.strictEqual(messages.length, 1)
641 assert.strictEqual(messages[0]._tag, "DataRow")
642 assert.deepStrictEqual((messages[0] as PgProtocol.DataRow).values, [field])
643 })
644
645 it("rejects a length prefix above maxMessageSize", () => {
646 const parser = PgProtocol.makeParser()
647 assertThrowsTagged("PgProtocolParseError", () => parser.push(bytes("447fffffff0000")))
648 })
649
650 it("honours a custom maxMessageSize", () => {
651 const parser = PgProtocol.makeParser({ maxMessageSize: 8 })
652 assertThrowsTagged("PgProtocolParseError", () => parser.push(bytes(backend.rowDescription)))
653 })
654
655 it("rejects a length prefix below the minimum", () => {
656 const parser = PgProtocol.makeParser()
657 assertThrowsTagged("PgProtocolParseError", () => parser.push(bytes("4400000003ff")))
658 assertThrowsTagged("PgProtocolParseError", () => PgProtocol.makeParser().push(bytes("4480000000")))
659 })
660
661 it("accepts a frame exactly at maxMessageSize", () => {
662 assert.deepStrictEqual(PgProtocol.makeParser({ maxMessageSize: 8 }).push(bytes("5f00000008deadbeef")), [
663 { _tag: "Unknown", type: 0x5f, payload: bytes("deadbeef") }
664 ])
665 })
666
667 it("rejects a truncated payload", () => {
668 // CommandComplete whose command tag is never NUL-terminated
669 assertParseFailure("430000000953454c454354")
670 })
671
672 it("rejects payload bytes beyond a message's declared fields", () => {
673 for (
674 const frame of [
675 "3100000005ff", // ParseComplete with a byte of payload
676 "44000000070000ff" // DataRow declares zero fields but carries a byte
677 ]
678 ) {
679 assertParseFailure(frame)
680 }
681 })
682
683 it("rejects a DataRow field length below the NULL sentinel", () => {
684 assertParseFailure("440000000a0001fffffffe")
685 })
686
687 it("rejects a negative DataRow field count", () => {
688 assertParseFailure("4400000006ffff")
689 })
690
691 it("rejects negative collection counts", () => {
692 for (
693 const frame of [
694 "5400000006ffff", // RowDescription
695 "7400000006ffff", // ParameterDescription
696 "470000000700ffff", // CopyInResponse
697 "480000000700ffff", // CopyOutResponse
698 "570000000700ffff", // CopyBothResponse
699 "760000000c00000000ffffffff" // NegotiateProtocolVersion
700 ]
701 ) {
702 assertParseFailure(frame)
703 }
704 })
705
706 it("rejects a truncated DataRow field length", () => {
707 assertParseFailure("440000000800010000")
708 assertParseFailure("4400000004")
709 })
710
711 it("rejects invalid statuses and UTF-8", () => {
712 assertParseFailure("5a0000000558")
713 assertParseFailure("5300000008ff007800")
714 })
715
716 it("does not read a DataRow field past the end of its own message", () => {
717 // One field that claims ten bytes in a message carrying two, followed by
718 // a complete message the field must not be allowed to reach into
719 assertThrowsTagged(
720 "PgProtocolParseError",
721 () => PgProtocol.makeParser().push(bytes(`440000000c00010000000a0102${backend.parseComplete}`))
722 )
723 })
724
725 it("cannot be reused after a malformed frame", () => {
726 const parser = PgProtocol.makeParser()
727 assertThrowsTagged(
728 "PgProtocolParseError",
729 () => parser.push(bytes(`${backend.parseComplete}430000000953454c454354`))
730 )
731 assertThrowsTagged(
732 "PgProtocolParseError",
733 () => parser.push(bytes(backend.bindComplete)),
734 "Parser cannot be reused after a failure"
735 )
736 })
737
738 it("does not read a string past the end of its own message", () => {
739 // CommandComplete whose tag is not NUL-terminated, followed by a message
740 // whose length prefix contains NUL bytes
741 assertThrowsTagged(
742 "PgProtocolParseError",
743 () => PgProtocol.makeParser().push(bytes(`430000000a53454c454354${backend.parseComplete}`))
744 )
745 })
746 })
747
748 describe("buffer reuse", () => {
749 it("keeps DataRow field views valid across later pushes", () => {
750 const parser = PgProtocol.makeParser()
751 const frame = bytes(backend.dataRowTwoColumns)
752 const first = parser.push(frame)[0] as PgProtocol.DataRow
753 const snapshot = first.values.map((value) => value === null ? null : value.slice())
754 // enough to run past the parser's buffer and force a replacement
755 for (let index = 0; index < 2000; index++) parser.push(frame)
756 assert.deepStrictEqual(first.values, snapshot)
757 })
758
759 it("keeps DataRow field views valid as the buffer pool grows", () => {
760 const parser = PgProtocol.makeParser()
761 const frame = bytes(backend.dataRowTwoColumns)
762 const retained: Array<{ readonly row: PgProtocol.DataRow; readonly snapshot: Array<Uint8Array | null> }> = []
763 // enough pushes to run the pool from its initial size up to its ceiling
764 for (let index = 0; index < 5000; index++) {
765 const row = parser.push(frame)[0] as PgProtocol.DataRow
766 if (index % 500 === 0) {
767 retained.push({ row, snapshot: row.values.map((value) => value === null ? null : value.slice()) })
768 }
769 }
770 for (const { row, snapshot } of retained) {
771 assert.deepStrictEqual(row.values, snapshot)
772 }
773 })
774
775 it("keeps an encoded frame valid after encoding more", () => {
776 const first = success(PgProtocol.encodeBind({
777 portal: "portal",
778 statement: "statement",
779 parameters: [bytes("0102030405")]
780 }))
781 const snapshot = first.slice()
782 for (let index = 0; index < 100; index++) {
783 success(PgProtocol.encodeBind({ portal: "other", statement: "s", parameters: [new Uint8Array(64)] }))
784 }
785 assert.deepStrictEqual(first, snapshot)
786 })
787
788 it("keeps an encoded frame valid after an oversized one", () => {
789 const first = PgProtocol.encodeSync()
790 const snapshot = first.slice()
791 const huge = success(PgProtocol.encodeBind({
792 portal: "",
793 statement: "",
794 parameters: [new Uint8Array(32 * 1024)]
795 }))
796 assert.strictEqual(huge.length, 32 * 1024 + 21)
797 assert.deepStrictEqual(first, snapshot)
798 assert.deepStrictEqual(PgProtocol.encodeSync(), snapshot)
799 })
800 })
801})