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

main
ts 1,936 lines 51.7 KB
Raw
1 /**
2 * Wire codec for the PostgreSQL frontend/backend protocol, version 3.0.
3 *
4 * The module encodes frontend messages and decodes backend messages. Every
5 * function is pure: bytes in, bytes or plain data out. Nothing here opens a
6 * socket, negotiates TLS, or tracks session state, and nothing here decodes
7 * column values - `DataRow` fields stay raw bytes for `PgTypes` to interpret.
8 *
9 * Typed messages are a type byte, an `int32` length that counts itself but not
10 * the type byte, and a payload. Integers are big-endian and strings are
11 * NUL-terminated UTF-8 unless they are explicitly length-prefixed.
12 *
13 * Encoded frames and decoded byte fields are views into pooled buffers that
14 * are written once and never rewritten. They stay valid for as long as they
15 * are held, but holding one keeps its whole pool buffer alive, so copy
16 * anything that has to outlive the message it came from.
17 *
18 * @stability unstable
19 * @since 4.0.0
20 */
21 import * as Data from "effect/Data"
22 import * as Result from "effect/Result"
23
24 /**
25 * Default `maxMessageSize` for `makeParser`: 16 MiB.
26 *
27 * @stability unstable
28 * @category constants
29 * @since 4.0.0
30 */
31 export const defaultMaxMessageSize = 16 * 1024 * 1024
32
33 /** Where a parser stops growing its buffer pool. */
34 const maxBufferSize = 64 * 1024
35
36 /**
37 * An incremental decoder for the post-startup backend message stream.
38 *
39 * @stability unstable
40 * @category models
41 * @since 4.0.0
42 */
43 export interface Parser<A = Uint8Array | null> {
44 /**
45 * Reads each `DataRow` field, for a parser built with one. A result's
46 * columns are only known from its `RowDescription`, which arrives on the
47 * same stream, so this is settable: replace it when the columns change.
48 */
49 readField: FieldReader<A> | undefined
50
51 /**
52 * Decodes a chunk and returns every complete message. A partial message is
53 * retained for the next call. Parse and field-reader errors are terminal and
54 * discard messages decoded earlier in the same call.
55 *
56 * **Details**
57 *
58 * `DataRow`, `CopyData`, and `Unknown` payloads are views into an internal
59 * buffer. Copy a payload that must outlive the current row, otherwise its
60 * entire buffer remains in memory.
61 */
62 readonly push: (chunk: Uint8Array) => ReadonlyArray<BackendMessage<A>>
63
64 /**
65 * Decodes a chunk and passes each complete message to `onMessage`
66 * immediately. This lets a `RowDescription` update `readField` before a
67 * `DataRow` later in the same chunk is decoded. The failure and
68 * buffer-lifetime rules match `push`, except messages
69 * delivered before a failure are not discarded.
70 */
71 readonly pushEach: (chunk: Uint8Array, onMessage: (message: BackendMessage<A>) => void) => void
72 }
73
74 /**
75 * Creates a `Parser`.
76 *
77 * **Details**
78 *
79 * Special pre-startup replies have no type byte. Use `decodeSslResponse` for
80 * those replies.
81 *
82 * @stability unstable
83 * @category constructors
84 * @since 4.0.0
85 */
86 export const makeParser = <A = Uint8Array | null>(options?: {
87 readonly maxMessageSize?: number | undefined
88 /**
89 * Reads each `DataRow` field as it is parsed, so a client that decodes its
90 * columns never needs a view per column. Without one every field is handed
91 * out as a view, which is the default.
92 */
93 readonly readField?: FieldReader<A> | undefined
94 }): Parser<A> => {
95 const maxMessageSize = options?.maxMessageSize ?? defaultMaxMessageSize
96 const reader = new Reader()
97 let bufferSize = 8192
98 let buffer = new Uint8Array(bufferSize)
99 let store = buffer.buffer
100 let start = 0
101 let end = 0
102 let failed = false
103
104 // Bytes already handed to the caller are never overwritten, so a full buffer
105 // is replaced rather than compacted in place. That lets `DataRow` fields be
106 // views instead of copies, which is the difference between one allocation per
107 // buffer and one per column.
108 //
109 // Every refill therefore allocates, so the pool doubles up to
110 // `maxBufferSize`: a busy connection spreads the allocation over more
111 // messages while a low-volume one stays small. A single oversized message
112 // grows its buffer beyond the pool without raising the pool itself.
113 const append = (chunk: Uint8Array): void => {
114 if (end + chunk.length > buffer.length) {
115 const pending = end - start
116 if (bufferSize < maxBufferSize) bufferSize *= 2
117 let capacity = bufferSize
118 while (capacity < pending + chunk.length) capacity *= 2
119 const next = new Uint8Array(capacity)
120 next.set(buffer.subarray(start, end))
121 buffer = next
122 store = next.buffer
123 start = 0
124 end = pending
125 }
126 buffer.set(chunk, end)
127 end += chunk.length
128 }
129
130 const parser: Parser<A> = {
131 readField: options?.readField,
132 push(chunk) {
133 const messages: Array<BackendMessage<A>> = []
134 parser.pushEach(chunk, (message) => {
135 messages.push(message)
136 })
137 return messages
138 },
139 pushEach(chunk, onMessage) {
140 if (failed) {
141 throw new ParseError({ message: "Parser cannot be reused after a failure" })
142 }
143 try {
144 append(chunk)
145 while (end - start >= 5) {
146 const length = (buffer[start + 1] << 24) | (buffer[start + 2] << 16) | (buffer[start + 3] << 8) |
147 buffer[start + 4]
148 if (length < 4) {
149 throw new ParseError({ message: `Invalid message length: ${length}` })
150 }
151 if (length > maxMessageSize) {
152 throw new ParseError({
153 message: `Message length ${length} exceeds maxMessageSize ${maxMessageSize}`
154 })
155 }
156 if (end - start < length + 1) break
157 const type = buffer[start]
158 const body = start + 5
159 const limit = start + 1 + length
160 start = limit
161 if (type === BackendType.DataRow) {
162 // `buffer` always starts at byte 0 of `store`, so offsets index both.
163 onMessage(decodeDataRow<A>(buffer, store, 0, body, limit, parser.readField))
164 } else {
165 reader.reset(buffer, body, limit)
166 const message = decodeBackend(type, reader)
167 if (reader.offset !== limit) {
168 throw new ParseError({ message: `Message has ${limit - reader.offset} trailing byte(s)` })
169 }
170 onMessage(message as BackendMessage<A>)
171 }
172 }
173 } catch (error) {
174 failed = true
175 throw error
176 }
177 }
178 }
179 return parser
180 }
181
182 // -----------------------------------------------------------------------------
183 // frontend messages
184 // -----------------------------------------------------------------------------
185
186 /**
187 * Prepares a named or unnamed statement.
188 *
189 * @stability unstable
190 * @category models
191 * @since 4.0.0
192 */
193 export interface Parse {
194 readonly _tag: "Parse"
195 readonly name: string
196 readonly query: string
197 readonly parameterTypes: ReadonlyArray<number>
198 }
199
200 /**
201 * Binds parameter values to a prepared statement and creates a portal.
202 * Parameters and results use the binary format.
203 *
204 * @stability unstable
205 * @category models
206 * @since 4.0.0
207 */
208 export interface Bind {
209 readonly _tag: "Bind"
210 readonly portal: string
211 readonly statement: string
212 readonly parameters: ReadonlyArray<Uint8Array | null>
213 }
214
215 /**
216 * Runs a portal, optionally limiting the number of rows returned.
217 *
218 * @stability unstable
219 * @category models
220 * @since 4.0.0
221 */
222 export interface Execute {
223 readonly _tag: "Execute"
224 readonly portal: string
225 readonly maxRows: number
226 }
227
228 /**
229 * Which kind of object a `Describe` or `Close` message names.
230 *
231 * @stability unstable
232 * @category models
233 * @since 4.0.0
234 */
235 export type DescribeTarget = "statement" | "portal"
236
237 /**
238 * Asks for the parameter and row shape of a statement or portal.
239 *
240 * @stability unstable
241 * @category models
242 * @since 4.0.0
243 */
244 export interface Describe {
245 readonly _tag: "Describe"
246 readonly target: DescribeTarget
247 readonly name: string
248 }
249
250 /**
251 * Drops a prepared statement or portal.
252 *
253 * @stability unstable
254 * @category models
255 * @since 4.0.0
256 */
257 export interface Close {
258 readonly _tag: "Close"
259 readonly target: DescribeTarget
260 readonly name: string
261 }
262
263 /**
264 * Closes the current transaction block and requests a `ReadyForQuery`.
265 *
266 * @stability unstable
267 * @category models
268 * @since 4.0.0
269 */
270 export interface Sync {
271 readonly _tag: "Sync"
272 }
273
274 /**
275 * Asks the backend to deliver buffered output without ending the transaction.
276 *
277 * @stability unstable
278 * @category models
279 * @since 4.0.0
280 */
281 export interface Flush {
282 readonly _tag: "Flush"
283 }
284
285 /**
286 * Ends the session.
287 *
288 * @stability unstable
289 * @category models
290 * @since 4.0.0
291 */
292 export interface Terminate {
293 readonly _tag: "Terminate"
294 }
295
296 /**
297 * Answers a cleartext or MD5 password request.
298 *
299 * @stability unstable
300 * @category models
301 * @since 4.0.0
302 */
303 export interface PasswordMessage {
304 readonly _tag: "PasswordMessage"
305 readonly password: string
306 }
307
308 /**
309 * Selects a SASL mechanism and carries its opaque initial response.
310 *
311 * @stability unstable
312 * @category models
313 * @since 4.0.0
314 */
315 export interface SASLInitialResponse {
316 readonly _tag: "SASLInitialResponse"
317 readonly mechanism: string
318 readonly initialResponse: Uint8Array | null
319 }
320
321 /**
322 * Carries an opaque SASL continuation payload.
323 *
324 * @stability unstable
325 * @category models
326 * @since 4.0.0
327 */
328 export interface SASLResponse {
329 readonly _tag: "SASLResponse"
330 readonly data: Uint8Array
331 }
332
333 /**
334 * Any message the client sends after startup.
335 *
336 * @stability unstable
337 * @category models
338 * @since 4.0.0
339 */
340 export type FrontendMessage =
341 | Parse
342 | Bind
343 | Execute
344 | Describe
345 | Close
346 | Sync
347 | Flush
348 | Terminate
349 | PasswordMessage
350 | SASLInitialResponse
351 | SASLResponse
352
353 /**
354 * Error produced when bytes cannot be interpreted as a protocol message.
355 *
356 * @stability unstable
357 * @category errors
358 * @since 4.0.0
359 */
360 export class ParseError extends Data.TaggedError("PgProtocolParseError")<{
361 readonly message: string
362 }> {}
363
364 /**
365 * Error returned when a frontend message cannot be encoded.
366 *
367 * @stability unstable
368 * @category errors
369 * @since 4.0.0
370 */
371 export class EncodeError extends Data.TaggedError("PgProtocolEncodeError")<{
372 readonly message: string
373 }> {}
374
375 const textEncoder = new TextEncoder()
376 const textDecoder = new TextDecoder("utf-8", { fatal: true })
377
378 /**
379 * Above this length `TextEncoder.encodeInto` beats a per-character loop, below
380 * it the call overhead dominates. Measured on V8: the loop runs at about a
381 * nanosecond per character and `encodeInto` costs about 50 ns whatever the
382 * length, so the crossover is around 50 characters.
383 */
384 const asciiEncodeLimit = 48
385
386 /**
387 * A view over part of a cached backing store. Slicing runs once per column of
388 * every row, and both obvious spellings are slower than this one: `subarray`
389 * consults the constructor's `Symbol.species` before it can allocate, and
390 * reading `.buffer` off a typed array is an accessor call rather than a field
391 * load. Callers hold the store and the array's byte offset instead.
392 */
393 const view = (store: ArrayBufferLike, offset: number, length: number): Uint8Array =>
394 new Uint8Array(store, offset, length)
395
396 /** Up to this many bytes a copy loop beats `Uint8Array.prototype.set`. */
397 const smallCopyLimit = 8
398
399 /**
400 * Writes messages back to back into a pooled buffer and hands out a view of
401 * each one, so encoding a message costs no allocation of its own. Bytes below
402 * `start` have already been handed out and are never rewritten; when the pool
403 * runs out it is replaced rather than reused.
404 */
405 class Writer {
406 readonly poolSize: number
407 bytes: Uint8Array
408 view: DataView
409 /** Where the message currently being written begins. */
410 start = 0
411 offset = 0
412 /** Set by `sqlNull`, read and cleared by the `makeBindEncoder` loop. */
413 isNull = false
414
415 constructor(poolSize: number) {
416 this.poolSize = poolSize
417 this.bytes = new Uint8Array(poolSize)
418 this.view = new DataView(this.bytes.buffer)
419 }
420
421 reserve(size: number): void {
422 if (this.offset + size <= this.bytes.length) return
423 const pending = this.offset - this.start
424 let capacity = this.poolSize
425 while (capacity < pending + size) capacity *= 2
426 const next = new Uint8Array(capacity)
427 next.set(this.bytes.subarray(this.start, this.offset))
428 this.bytes = next
429 this.view = new DataView(next.buffer)
430 this.start = 0
431 this.offset = pending
432 }
433
434 /** Starts a message, dropping anything a failed write left behind. */
435 begin(): void {
436 this.start = this.offset
437 }
438
439 uint8(value: number): void {
440 this.reserve(1)
441 this.bytes[this.offset++] = value
442 }
443
444 int16(value: number): void {
445 this.reserve(2)
446 const bytes = this.bytes
447 const offset = this.offset
448 bytes[offset] = value >>> 8
449 bytes[offset + 1] = value
450 this.offset = offset + 2
451 }
452
453 int32(value: number): void {
454 this.reserve(4)
455 this.setInt32(this.offset, value)
456 this.offset += 4
457 }
458
459 setInt32(offset: number, value: number): void {
460 const bytes = this.bytes
461 bytes[offset] = value >>> 24
462 bytes[offset + 1] = value >>> 16
463 bytes[offset + 2] = value >>> 8
464 bytes[offset + 3] = value
465 }
466
467 float32(value: number): void {
468 this.reserve(4)
469 this.view.setFloat32(this.offset, value)
470 this.offset += 4
471 }
472
473 float64(value: number): void {
474 this.reserve(8)
475 this.view.setFloat64(this.offset, value)
476 this.offset += 8
477 }
478
479 bigInt64(value: bigint): void {
480 this.reserve(8)
481 this.view.setBigInt64(this.offset, value)
482 this.offset += 8
483 }
484
485 raw(value: Uint8Array): void {
486 const length = value.length
487 this.reserve(length)
488 const bytes = this.bytes
489 const offset = this.offset
490 if (length <= smallCopyLimit) {
491 for (let index = 0; index < length; index++) bytes[offset + index] = value[index]
492 } else {
493 bytes.set(value, offset)
494 }
495 this.offset = offset + length
496 }
497
498 sqlNull(): void {
499 this.isNull = true
500 }
501
502 beginLength(): number {
503 // Relative to `start`, because a later write may move the message to a new
504 // pool buffer, which rebases `start` and `offset` but not the distance
505 // between them.
506 const token = this.offset - this.start
507 this.int32(0)
508 return token
509 }
510
511 endLength(token: number): void {
512 this.setInt32(this.start + token, this.offset - this.start - token - 4)
513 }
514
515 utf8(value: string, nul = false): void {
516 const length = value.length
517 if (length <= asciiEncodeLimit) {
518 this.reserve(length + (nul ? 1 : 0))
519 const bytes = this.bytes
520 const start = this.offset
521 let i = 0
522 for (; i < length; i++) {
523 const code = value.charCodeAt(i)
524 if (code > 0x7f) break
525 bytes[start + i] = code
526 }
527 if (i === length) {
528 const offset = start + length
529 if (nul) bytes[offset] = 0
530 this.offset = offset + (nul ? 1 : 0)
531 return
532 }
533 }
534 // UTF-8 takes at most three bytes per UTF-16 code unit, and four for the
535 // two units of a surrogate pair, so this covers any string.
536 this.reserve(length * 3 + (nul ? 1 : 0))
537 this.offset += textEncoder.encodeInto(value, this.bytes.subarray(this.offset)).written
538 if (nul) this.bytes[this.offset++] = 0
539 }
540
541 cString(value: string): void {
542 this.utf8(value, true)
543 }
544
545 finish(): Uint8Array {
546 const value = view(this.bytes.buffer, this.bytes.byteOffset + this.start, this.offset - this.start)
547 if (this.bytes.length > this.poolSize) {
548 // An oversized message grew the pool; do not keep the rest of it around.
549 this.bytes = new Uint8Array(this.poolSize)
550 this.view = new DataView(this.bytes.buffer)
551 this.start = 0
552 this.offset = 0
553 } else {
554 this.start = this.offset
555 }
556 return value
557 }
558 }
559
560 const emptyBytes = new Uint8Array(0)
561
562 /**
563 * A cursor over a message payload. The parser reuses one instance pointed at a
564 * window of its own buffer, so decoding a message allocates nothing beyond the
565 * message itself.
566 */
567 class Reader {
568 bytes: Uint8Array = emptyBytes
569 /** The backing store of `bytes` and its offset into it, resolved per message. */
570 store: ArrayBufferLike = emptyBytes.buffer
571 base = 0
572 offset = 0
573 limit = 0
574
575 reset(bytes: Uint8Array, offset: number, limit: number): void {
576 this.bytes = bytes
577 this.store = bytes.buffer
578 this.base = bytes.byteOffset
579 this.offset = offset
580 this.limit = limit
581 }
582
583 require(size: number): void {
584 if (size < 0) {
585 throw new ParseError({ message: `Invalid read of ${size} byte(s)` })
586 }
587 if (this.offset + size > this.limit) {
588 throw new ParseError({ message: `Truncated message: expected ${size} more byte(s)` })
589 }
590 }
591
592 uint8(): number {
593 this.require(1)
594 return this.bytes[this.offset++]
595 }
596
597 int16(): number {
598 this.require(2)
599 const bytes = this.bytes
600 const offset = this.offset
601 this.offset = offset + 2
602 return ((bytes[offset] << 8) | bytes[offset + 1]) << 16 >> 16
603 }
604
605 int32(): number {
606 this.require(4)
607 const bytes = this.bytes
608 const offset = this.offset
609 this.offset = offset + 4
610 return (bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]
611 }
612
613 uint32(): number {
614 return this.int32() >>> 0
615 }
616
617 raw(size: number): Uint8Array {
618 this.require(size)
619 const value = view(this.store, this.base + this.offset, size)
620 this.offset += size
621 return value
622 }
623
624 rest(): Uint8Array {
625 return this.raw(this.limit - this.offset)
626 }
627
628 cString(): string {
629 const end = this.bytes.indexOf(0, this.offset)
630 if (end === -1 || end >= this.limit) {
631 throw new ParseError({ message: "Unterminated string" })
632 }
633 const value = decodeUtf8(this.bytes, this.offset, end - this.offset)
634 this.offset = end + 1
635 return value
636 }
637 }
638
639 /** Below this length a per-character loop beats `TextDecoder.decode`. */
640 const asciiDecodeLimit = 10
641
642 /**
643 * Node's own UTF-8 decoder; see the note on its `PgTypes` counterpart. A
644 * result containing a replacement character goes to the strict decoder, so
645 * invalid bytes still fail exactly as they did.
646 */
647 const utf8Slice: ((this: Uint8Array, start: number, end: number) => string) | undefined = (globalThis as any).Buffer
648 ?.prototype?.utf8Slice
649
650 const decodeUtf8 = (bytes: Uint8Array, offset: number, size: number): string => {
651 if (size <= asciiDecodeLimit) {
652 let text = ""
653 let index = 0
654 for (; index < size; index++) {
655 const code = bytes[offset + index]
656 if (code > 0x7f) break
657 text += String.fromCharCode(code)
658 }
659 if (index === size) return text
660 }
661 if (utf8Slice !== undefined) {
662 const text = utf8Slice.call(bytes, offset, offset + size)
663 if (text.indexOf("\ufffd") === -1) return text
664 }
665 try {
666 return textDecoder.decode(view(bytes.buffer, bytes.byteOffset + offset, size))
667 } catch {
668 throw new ParseError({ message: "Invalid UTF-8 in message" })
669 }
670 }
671
672 const sharedWriter = new Writer(8192)
673
674 /**
675 * Opens a typed message and leaves room for its length. Paired with `end`,
676 * which backfills it. A pair rather than a `write` callback, because a
677 * callback allocates a closure over the caller's options on every message.
678 */
679 const begin = (type: number): Writer => {
680 const writer = sharedWriter
681 writer.begin()
682 writer.reserve(5)
683 const bytes = writer.bytes
684 const offset = writer.offset
685 bytes[offset] = type
686 writer.offset = offset + 5
687 return writer
688 }
689
690 const end = (): Uint8Array => {
691 // Relative to `start`, because writing may have moved the message to a new
692 // pool buffer. The length counts itself but not the type byte.
693 sharedWriter.setInt32(sharedWriter.start + 1, sharedWriter.offset - sharedWriter.start - 1)
694 return sharedWriter.finish()
695 }
696
697 const empty = (type: number): Uint8Array => {
698 const writer = begin(type)
699 writer.setInt32(writer.start + 1, 4)
700 return writer.finish()
701 }
702
703 const targetByte = (target: DescribeTarget): number => target === "statement" ? 0x53 : 0x50
704
705 const requireUint16Count = (count: number, name: string): number => {
706 if (count > 0xffff) throw new EncodeError({ message: `${name} count exceeds 65535: ${count}` })
707 return count
708 }
709
710 const encodeResult = <A>(evaluate: () => A): Result.Result<A, EncodeError> => {
711 try {
712 return Result.succeed(evaluate())
713 } catch (error) {
714 if (error instanceof EncodeError) return Result.fail(error)
715 throw error
716 }
717 }
718
719 /**
720 * Encodes a `Parse` message, returning `EncodeError` when its parameter count
721 * is outside the unsigned int16 wire range.
722 *
723 * @category encoding
724 * @since 4.0.0
725 */
726 const encodeParseUnsafe = (options: Omit<Parse, "_tag">): Uint8Array => {
727 const writer = begin(0x50)
728 writer.cString(options.name)
729 writer.cString(options.query)
730 const parameterTypes = options.parameterTypes
731 const count = requireUint16Count(parameterTypes.length, "Parse parameter type")
732 writer.reserve(2 + count * 4)
733 const bytes = writer.bytes
734 let offset = writer.offset
735 bytes[offset] = count >>> 8
736 bytes[offset + 1] = count
737 offset += 2
738 for (let index = 0; index < count; index++) {
739 const oid = parameterTypes[index]
740 bytes[offset] = oid >>> 24
741 bytes[offset + 1] = oid >>> 16
742 bytes[offset + 2] = oid >>> 8
743 bytes[offset + 3] = oid
744 offset += 4
745 }
746 writer.offset = offset
747 return end()
748 }
749
750 /**
751 * Encodes a `Parse` message.
752 *
753 * @stability unstable
754 * @category encoding
755 * @since 4.0.0
756 */
757 export const encodeParse = (options: Omit<Parse, "_tag">): Result.Result<Uint8Array, EncodeError> =>
758 encodeResult(() => encodeParseUnsafe(options))
759
760 /**
761 * Encodes a `Bind` message using the binary format code for parameters and
762 * results, returning `EncodeError` when its parameter count is outside the
763 * unsigned int16 wire range.
764 *
765 * @category encoding
766 * @since 4.0.0
767 */
768 const encodeBindUnsafe = (options: Omit<Bind, "_tag">): Uint8Array => {
769 const writer = begin(0x42)
770 writer.cString(options.portal)
771 writer.cString(options.statement)
772 const parameters = options.parameters
773 const count = requireUint16Count(parameters.length, "Bind parameter")
774 // Sizing the rest of the frame up front turns every remaining write into a
775 // plain store: one bounds check for the message instead of one per field.
776 let size = 10 + count * 4
777 for (let index = 0; index < count; index++) {
778 const parameter = parameters[index]
779 if (parameter !== null) size += parameter.length
780 }
781 writer.reserve(size)
782 const bytes = writer.bytes
783 let offset = writer.offset
784 // One parameter format code, binary, for every parameter.
785 bytes[offset] = 0
786 bytes[offset + 1] = 1
787 bytes[offset + 2] = 0
788 bytes[offset + 3] = 1
789 bytes[offset + 4] = count >>> 8
790 bytes[offset + 5] = count
791 offset += 6
792 for (let index = 0; index < count; index++) {
793 const parameter = parameters[index]
794 if (parameter === null) {
795 bytes[offset] = 0xff
796 bytes[offset + 1] = 0xff
797 bytes[offset + 2] = 0xff
798 bytes[offset + 3] = 0xff
799 offset += 4
800 } else {
801 const length = parameter.length
802 bytes[offset] = length >>> 24
803 bytes[offset + 1] = length >>> 16
804 bytes[offset + 2] = length >>> 8
805 bytes[offset + 3] = length
806 offset += 4
807 if (length <= smallCopyLimit) {
808 for (let byte = 0; byte < length; byte++) bytes[offset + byte] = parameter[byte]
809 } else {
810 bytes.set(parameter, offset)
811 }
812 offset += length
813 }
814 }
815 // One result format code, binary, for every column.
816 bytes[offset] = 0
817 bytes[offset + 1] = 1
818 bytes[offset + 2] = 0
819 bytes[offset + 3] = 1
820 writer.offset = offset + 4
821 return end()
822 }
823
824 /**
825 * Encodes a `Bind` message.
826 *
827 * @stability unstable
828 * @category encoding
829 * @since 4.0.0
830 */
831 export const encodeBind = (options: Omit<Bind, "_tag">): Result.Result<Uint8Array, EncodeError> =>
832 encodeResult(() => encodeBindUnsafe(options))
833
834 /**
835 * A sink for writing parameter bytes into a `Bind` frame. The frame reserves
836 * and backfills each parameter length. `PgTypes.writeParameter` supports
837 * OID-typed values.
838 *
839 * @stability unstable
840 * @category models
841 * @since 4.0.0
842 */
843 export interface ValueSink {
844 readonly uint8: (value: number) => void
845 readonly int16: (value: number) => void
846 readonly int32: (value: number) => void
847 readonly float32: (value: number) => void
848 readonly float64: (value: number) => void
849 readonly bigInt64: (value: bigint) => void
850 readonly raw: (value: Uint8Array) => void
851 readonly utf8: (value: string) => void
852 /** Writes SQL NULL. The value must write nothing else. */
853 readonly sqlNull: () => void
854 /**
855 * Leaves room for an int32 length and returns a token for `endLength`, so a
856 * value that contains other values can frame them without knowing their
857 * sizes up front. Tokens nest, and must be closed in the order they were
858 * opened.
859 */
860 readonly beginLength: () => number
861 /** Backfills the length of everything written since its `beginLength`. */
862 readonly endLength: (token: number) => void
863 }
864
865 const valueWriterUnsafe = Symbol.for("@effect/sql-pg/PgProtocol/ValueWriter/unsafe")
866
867 /**
868 * Creates a `Bind` encoder that writes parameters directly into the frame.
869 *
870 * **Details**
871 *
872 * `textFormat` identifies parameters encoded as text. All other parameters
873 * use the binary format.
874 *
875 * **Example** (Encoding a `Bind` message)
876 *
877 * ```ts
878 * import { PgProtocol, PgTypes } from "@effect/sql-pg"
879 *
880 * const encodeBind = PgProtocol.makeBindEncoder(PgTypes.writeParameter, PgTypes.isTextFormat)
881 * const frame = encodeBind({ portal: "", statement: "s1", parameters: [PgTypes.int4(1)] })
882 * ```
883 *
884 * @stability unstable
885 * @category encoding
886 * @since 4.0.0
887 */
888 export const makeBindEncoder = <A, E = never>(
889 writeParameter: (sink: ValueSink, value: A) => Result.Result<void, E>,
890 textFormat?: (value: A) => boolean
891 ) =>
892 (options: {
893 readonly portal: string
894 readonly statement: string
895 readonly parameters: ReadonlyArray<A>
896 }): Result.Result<Uint8Array, EncodeError | E> => {
897 try {
898 const writer = begin(0x42)
899 writer.cString(options.portal)
900 writer.cString(options.statement)
901 const parameters = options.parameters
902 const count = requireUint16Count(parameters.length, "Bind parameter")
903 let textCount = 0
904 if (textFormat !== undefined) {
905 for (let index = 0; index < count; index++) {
906 if (textFormat(parameters[index])) textCount++
907 }
908 }
909 if (textCount === 0 || textCount === count) {
910 // One format code covering every parameter: binary, or all-text.
911 const code = textCount === 0 ? 1 : 0
912 writer.reserve(6)
913 const header = writer.bytes
914 const headerOffset = writer.offset
915 header[headerOffset] = 0
916 header[headerOffset + 1] = 1
917 header[headerOffset + 2] = 0
918 header[headerOffset + 3] = code
919 header[headerOffset + 4] = count >>> 8
920 header[headerOffset + 5] = count
921 writer.offset = headerOffset + 6
922 } else {
923 writer.int16(count)
924 for (let index = 0; index < count; index++) {
925 writer.int16(textFormat!(parameters[index]) ? 0 : 1)
926 }
927 writer.int16(count)
928 }
929 const writeUnsafe = (writeParameter as any)[valueWriterUnsafe] as
930 | ((sink: ValueSink, value: A) => void)
931 | undefined
932 for (let index = 0; index < count; index++) {
933 const token = writer.beginLength()
934 writer.isNull = false
935 if (writeUnsafe === undefined) {
936 const written = writeParameter(writer, parameters[index])
937 if (Result.isFailure(written)) return Result.fail(written.failure)
938 } else {
939 writeUnsafe(writer, parameters[index])
940 }
941 if (writer.isNull) {
942 writer.isNull = false
943 writer.offset = writer.start + token
944 writer.int32(-1)
945 } else {
946 writer.endLength(token)
947 }
948 }
949 writer.reserve(4)
950 const trailer = writer.bytes
951 const trailerOffset = writer.offset
952 trailer[trailerOffset] = 0
953 trailer[trailerOffset + 1] = 1
954 trailer[trailerOffset + 2] = 0
955 trailer[trailerOffset + 3] = 1
956 writer.offset = trailerOffset + 4
957 return Result.succeed(end())
958 } catch (error) {
959 if (error instanceof EncodeError) return Result.fail(error)
960 throw error
961 }
962 }
963
964 /**
965 * Encodes an `Execute` message.
966 *
967 * @stability unstable
968 * @category encoding
969 * @since 4.0.0
970 */
971 export const encodeExecute = (options: Omit<Execute, "_tag">): Uint8Array => {
972 const writer = begin(0x45)
973 writer.cString(options.portal)
974 writer.int32(options.maxRows)
975 return end()
976 }
977
978 /**
979 * Encodes a `Describe` message.
980 *
981 * @stability unstable
982 * @category encoding
983 * @since 4.0.0
984 */
985 export const encodeDescribe = (options: Omit<Describe, "_tag">): Uint8Array => {
986 const writer = begin(0x44)
987 writer.uint8(targetByte(options.target))
988 writer.cString(options.name)
989 return end()
990 }
991
992 /**
993 * Encodes a `Close` message.
994 *
995 * @stability unstable
996 * @category encoding
997 * @since 4.0.0
998 */
999 export const encodeClose = (options: Omit<Close, "_tag">): Uint8Array => {
1000 const writer = begin(0x43)
1001 writer.uint8(targetByte(options.target))
1002 writer.cString(options.name)
1003 return end()
1004 }
1005
1006 /**
1007 * Encodes a `Sync` message.
1008 *
1009 * @stability unstable
1010 * @category encoding
1011 * @since 4.0.0
1012 */
1013 export const encodeSync = (): Uint8Array => empty(0x53)
1014
1015 /**
1016 * Encodes a `Flush` message.
1017 *
1018 * @stability unstable
1019 * @category encoding
1020 * @since 4.0.0
1021 */
1022 export const encodeFlush = (): Uint8Array => empty(0x48)
1023
1024 /**
1025 * Encodes a `Terminate` message.
1026 *
1027 * @stability unstable
1028 * @category encoding
1029 * @since 4.0.0
1030 */
1031 export const encodeTerminate = (): Uint8Array => empty(0x58)
1032
1033 /**
1034 * Encodes a `PasswordMessage`. The password is sent verbatim, so MD5 hashing
1035 * belongs to the caller - see `PgAuth.md5Password`.
1036 *
1037 * @stability unstable
1038 * @category encoding
1039 * @since 4.0.0
1040 */
1041 export const encodePasswordMessage = (options: Omit<PasswordMessage, "_tag">): Uint8Array => {
1042 const writer = begin(0x70)
1043 writer.cString(options.password)
1044 return end()
1045 }
1046
1047 /**
1048 * Encodes a `SASLInitialResponse` message.
1049 *
1050 * @stability unstable
1051 * @category encoding
1052 * @since 4.0.0
1053 */
1054 export const encodeSASLInitialResponse = (options: Omit<SASLInitialResponse, "_tag">): Uint8Array => {
1055 const writer = begin(0x70)
1056 writer.cString(options.mechanism)
1057 if (options.initialResponse === null) {
1058 writer.int32(-1)
1059 } else {
1060 writer.int32(options.initialResponse.length)
1061 writer.raw(options.initialResponse)
1062 }
1063 return end()
1064 }
1065
1066 /**
1067 * Encodes a `SASLResponse` message.
1068 *
1069 * @stability unstable
1070 * @category encoding
1071 * @since 4.0.0
1072 */
1073 export const encodeSASLResponse = (options: Omit<SASLResponse, "_tag">): Uint8Array => {
1074 const writer = begin(0x70)
1075 writer.raw(options.data)
1076 return end()
1077 }
1078
1079 /**
1080 * Encodes any frontend message.
1081 *
1082 * @stability unstable
1083 * @category encoding
1084 * @since 4.0.0
1085 */
1086 export const encode = (message: FrontendMessage): Result.Result<Uint8Array, EncodeError> => {
1087 switch (message._tag) {
1088 case "Parse":
1089 return encodeParse(message)
1090 case "Bind":
1091 return encodeBind(message)
1092 case "Execute":
1093 return Result.succeed(encodeExecute(message))
1094 case "Describe":
1095 return Result.succeed(encodeDescribe(message))
1096 case "Close":
1097 return Result.succeed(encodeClose(message))
1098 case "Sync":
1099 return Result.succeed(encodeSync())
1100 case "Flush":
1101 return Result.succeed(encodeFlush())
1102 case "Terminate":
1103 return Result.succeed(encodeTerminate())
1104 case "PasswordMessage":
1105 return Result.succeed(encodePasswordMessage(message))
1106 case "SASLInitialResponse":
1107 return Result.succeed(encodeSASLInitialResponse(message))
1108 case "SASLResponse":
1109 return Result.succeed(encodeSASLResponse(message))
1110 }
1111 }
1112
1113 // -----------------------------------------------------------------------------
1114 // special messages
1115 // -----------------------------------------------------------------------------
1116
1117 const PROTOCOL_VERSION_3_0 = 196608
1118 const SSL_REQUEST_CODE = 80877103
1119 const CANCEL_REQUEST_CODE = 80877102
1120
1121 /**
1122 * Startup parameters. `user` is required; any other run-time parameter the
1123 * server accepts may be passed alongside it.
1124 *
1125 * @stability unstable
1126 * @category models
1127 * @since 4.0.0
1128 */
1129 export interface StartupParameters {
1130 readonly [key: string]: string | undefined
1131 readonly user: string
1132 readonly database?: string | undefined
1133 readonly application_name?: string | undefined
1134 }
1135
1136 /**
1137 * Encodes an `SSLRequest`. It has no type byte and is only valid before
1138 * startup.
1139 *
1140 * @stability unstable
1141 * @category encoding
1142 * @since 4.0.0
1143 */
1144 export const encodeSslRequest = (): Uint8Array => {
1145 sharedWriter.begin()
1146 sharedWriter.int32(8)
1147 sharedWriter.int32(SSL_REQUEST_CODE)
1148 return sharedWriter.finish()
1149 }
1150
1151 /**
1152 * Decodes the single byte the server sends in reply to an `SSLRequest`. `"S"`
1153 * means the server will speak TLS, `"N"` means it will not.
1154 *
1155 * @stability unstable
1156 * @category decoding
1157 * @since 4.0.0
1158 */
1159 export const decodeSslResponse = (byte: number): Result.Result<"S" | "N", ParseError> =>
1160 byte === 0x53
1161 ? Result.succeed("S")
1162 : byte === 0x4e
1163 ? Result.succeed("N")
1164 : Result.fail(new ParseError({ message: `Invalid SSLRequest response byte: ${byte}` }))
1165
1166 /**
1167 * Encodes a `StartupMessage` for protocol 3.0. It has no type byte.
1168 * `client_encoding` defaults to `UTF8` because this codec always writes UTF-8.
1169 *
1170 * @stability unstable
1171 * @category encoding
1172 * @since 4.0.0
1173 */
1174 export const encodeStartupMessage = (parameters: StartupParameters): Uint8Array => {
1175 const writer = sharedWriter
1176 writer.begin()
1177 writer.int32(0)
1178 writer.int32(PROTOCOL_VERSION_3_0)
1179 for (const [key, value] of Object.entries(parameters)) {
1180 if (value === undefined) continue
1181 writer.cString(key)
1182 writer.cString(value)
1183 }
1184 if (parameters.client_encoding === undefined) {
1185 writer.cString("client_encoding")
1186 writer.cString("UTF8")
1187 }
1188 writer.uint8(0)
1189 writer.setInt32(writer.start, writer.offset - writer.start)
1190 return writer.finish()
1191 }
1192
1193 /**
1194 * Encodes a `CancelRequest`. It has no type byte and is sent on a separate
1195 * connection, using the `pid` and `secret` from `BackendKeyData`.
1196 *
1197 * @stability unstable
1198 * @category encoding
1199 * @since 4.0.0
1200 */
1201 export const encodeCancelRequest = (options: {
1202 readonly pid: number
1203 readonly secret: number
1204 }): Uint8Array => {
1205 const writer = sharedWriter
1206 writer.begin()
1207 writer.int32(16)
1208 writer.int32(CANCEL_REQUEST_CODE)
1209 writer.int32(options.pid)
1210 writer.int32(options.secret)
1211 return writer.finish()
1212 }
1213
1214 // -----------------------------------------------------------------------------
1215 // backend messages
1216 // -----------------------------------------------------------------------------
1217
1218 /**
1219 * Authentication succeeded.
1220 *
1221 * @stability unstable
1222 * @category models
1223 * @since 4.0.0
1224 */
1225 export interface AuthenticationOk {
1226 readonly _tag: "AuthenticationOk"
1227 }
1228
1229 /**
1230 * The server wants the password in the clear.
1231 *
1232 * @stability unstable
1233 * @category models
1234 * @since 4.0.0
1235 */
1236 export interface AuthenticationCleartextPassword {
1237 readonly _tag: "AuthenticationCleartextPassword"
1238 }
1239
1240 /**
1241 * The server wants an MD5-hashed password, salted with these four bytes.
1242 *
1243 * @stability unstable
1244 * @category models
1245 * @since 4.0.0
1246 */
1247 export interface AuthenticationMD5Password {
1248 readonly _tag: "AuthenticationMD5Password"
1249 readonly salt: Uint8Array
1250 }
1251
1252 /**
1253 * The server offers these SASL mechanisms.
1254 *
1255 * @stability unstable
1256 * @category models
1257 * @since 4.0.0
1258 */
1259 export interface AuthenticationSASL {
1260 readonly _tag: "AuthenticationSASL"
1261 readonly mechanisms: ReadonlyArray<string>
1262 }
1263
1264 /**
1265 * An opaque SASL challenge.
1266 *
1267 * @stability unstable
1268 * @category models
1269 * @since 4.0.0
1270 */
1271 export interface AuthenticationSASLContinue {
1272 readonly _tag: "AuthenticationSASLContinue"
1273 readonly data: Uint8Array
1274 }
1275
1276 /**
1277 * The opaque final SASL payload, carrying the server signature.
1278 *
1279 * @stability unstable
1280 * @category models
1281 * @since 4.0.0
1282 */
1283 export interface AuthenticationSASLFinal {
1284 readonly _tag: "AuthenticationSASLFinal"
1285 readonly data: Uint8Array
1286 }
1287
1288 /**
1289 * An authentication request this codec does not model, such as GSSAPI or
1290 * SSPI. The `method` is the raw sub-type integer.
1291 *
1292 * @stability unstable
1293 * @category models
1294 * @since 4.0.0
1295 */
1296 export interface AuthenticationUnsupported {
1297 readonly _tag: "AuthenticationUnsupported"
1298 readonly method: number
1299 readonly payload: Uint8Array
1300 }
1301
1302 /**
1303 * Reports a run-time parameter value, at startup or whenever it changes.
1304 *
1305 * @stability unstable
1306 * @category models
1307 * @since 4.0.0
1308 */
1309 export interface ParameterStatus {
1310 readonly _tag: "ParameterStatus"
1311 readonly name: string
1312 readonly value: string
1313 }
1314
1315 /**
1316 * The identity a `CancelRequest` needs.
1317 *
1318 * @stability unstable
1319 * @category models
1320 * @since 4.0.0
1321 */
1322 export interface BackendKeyData {
1323 readonly _tag: "BackendKeyData"
1324 readonly pid: number
1325 readonly secret: number
1326 }
1327
1328 /**
1329 * Transaction status: idle, in a transaction block, or in a failed
1330 * transaction block.
1331 *
1332 * @stability unstable
1333 * @category models
1334 * @since 4.0.0
1335 */
1336 export type TransactionStatus = "I" | "T" | "E"
1337
1338 /**
1339 * The backend is ready for a new query cycle.
1340 *
1341 * @stability unstable
1342 * @category models
1343 * @since 4.0.0
1344 */
1345 export interface ReadyForQuery {
1346 readonly _tag: "ReadyForQuery"
1347 readonly status: TransactionStatus
1348 }
1349
1350 /**
1351 * One column of a `RowDescription`.
1352 *
1353 * @stability unstable
1354 * @category models
1355 * @since 4.0.0
1356 */
1357 export interface FieldDescription {
1358 readonly name: string
1359 readonly tableOid: number
1360 readonly columnAttributeNumber: number
1361 readonly dataTypeOid: number
1362 readonly dataTypeSize: number
1363 readonly typeModifier: number
1364 readonly format: number
1365 }
1366
1367 /**
1368 * Describes the columns a portal will return.
1369 *
1370 * @stability unstable
1371 * @category models
1372 * @since 4.0.0
1373 */
1374 export interface RowDescription {
1375 readonly _tag: "RowDescription"
1376 readonly fields: ReadonlyArray<FieldDescription>
1377 }
1378
1379 /**
1380 * One result row. Values stay raw bytes; `null` is SQL NULL. Decoding them
1381 * requires the OIDs from the matching `RowDescription`.
1382 *
1383 * @stability unstable
1384 * @category models
1385 * @since 4.0.0
1386 */
1387 export interface DataRow<out A = Uint8Array | null> {
1388 readonly _tag: "DataRow"
1389 readonly values: ReadonlyArray<A>
1390 }
1391
1392 /**
1393 * Reads one `DataRow` field from the parser buffer.
1394 *
1395 * **Details**
1396 *
1397 * `size` is `-1` for SQL `NULL`, and `column` is the field index. Only bytes
1398 * from `offset` through `offset + size` belong to the field. A thrown error
1399 * permanently fails the parser.
1400 *
1401 * @stability unstable
1402 * @category models
1403 * @since 4.0.0
1404 */
1405 export type FieldReader<A> = (bytes: Uint8Array, offset: number, size: number, column: number) => A
1406
1407 /**
1408 * A command finished, reporting its tag such as `SELECT 3`.
1409 *
1410 * @stability unstable
1411 * @category models
1412 * @since 4.0.0
1413 */
1414 export interface CommandComplete {
1415 readonly _tag: "CommandComplete"
1416 readonly commandTag: string
1417 }
1418
1419 /**
1420 * The query string was empty.
1421 *
1422 * @stability unstable
1423 * @category models
1424 * @since 4.0.0
1425 */
1426 export interface EmptyQueryResponse {
1427 readonly _tag: "EmptyQueryResponse"
1428 }
1429
1430 /**
1431 * The statement or portal returns no rows.
1432 *
1433 * @stability unstable
1434 * @category models
1435 * @since 4.0.0
1436 */
1437 export interface NoData {
1438 readonly _tag: "NoData"
1439 }
1440
1441 /**
1442 * A `Parse` succeeded.
1443 *
1444 * @stability unstable
1445 * @category models
1446 * @since 4.0.0
1447 */
1448 export interface ParseComplete {
1449 readonly _tag: "ParseComplete"
1450 }
1451
1452 /**
1453 * A `Bind` succeeded.
1454 *
1455 * @stability unstable
1456 * @category models
1457 * @since 4.0.0
1458 */
1459 export interface BindComplete {
1460 readonly _tag: "BindComplete"
1461 }
1462
1463 /**
1464 * A `Close` succeeded.
1465 *
1466 * @stability unstable
1467 * @category models
1468 * @since 4.0.0
1469 */
1470 export interface CloseComplete {
1471 readonly _tag: "CloseComplete"
1472 }
1473
1474 /**
1475 * An `Execute` stopped at its row limit; the portal can be executed again.
1476 *
1477 * @stability unstable
1478 * @category models
1479 * @since 4.0.0
1480 */
1481 export interface PortalSuspended {
1482 readonly _tag: "PortalSuspended"
1483 }
1484
1485 /**
1486 * The parameter OIDs of a described statement.
1487 *
1488 * @stability unstable
1489 * @category models
1490 * @since 4.0.0
1491 */
1492 export interface ParameterDescription {
1493 readonly _tag: "ParameterDescription"
1494 readonly parameterTypes: ReadonlyArray<number>
1495 }
1496
1497 /**
1498 * The fields of an `ErrorResponse` or `NoticeResponse`. Unrecognised field
1499 * codes are kept under their raw single-character key.
1500 *
1501 * @stability unstable
1502 * @category models
1503 * @since 4.0.0
1504 */
1505 export interface ErrorFields {
1506 readonly [key: string]: string | undefined
1507 readonly severity?: string | undefined
1508 readonly severityUnlocalized?: string | undefined
1509 readonly code?: string | undefined
1510 readonly message?: string | undefined
1511 readonly detail?: string | undefined
1512 readonly hint?: string | undefined
1513 readonly position?: string | undefined
1514 readonly internalPosition?: string | undefined
1515 readonly internalQuery?: string | undefined
1516 readonly where?: string | undefined
1517 readonly schema?: string | undefined
1518 readonly table?: string | undefined
1519 readonly column?: string | undefined
1520 readonly dataType?: string | undefined
1521 readonly constraint?: string | undefined
1522 readonly file?: string | undefined
1523 readonly line?: string | undefined
1524 readonly routine?: string | undefined
1525 }
1526
1527 /**
1528 * An error. `code` is the SQLSTATE.
1529 *
1530 * @stability unstable
1531 * @category models
1532 * @since 4.0.0
1533 */
1534 export interface ErrorResponse {
1535 readonly _tag: "ErrorResponse"
1536 readonly fields: ErrorFields
1537 }
1538
1539 /**
1540 * A warning or notice. Same field set as `ErrorResponse`.
1541 *
1542 * @stability unstable
1543 * @category models
1544 * @since 4.0.0
1545 */
1546 export interface NoticeResponse {
1547 readonly _tag: "NoticeResponse"
1548 readonly fields: ErrorFields
1549 }
1550
1551 /**
1552 * A `LISTEN`/`NOTIFY` message.
1553 *
1554 * @stability unstable
1555 * @category models
1556 * @since 4.0.0
1557 */
1558 export interface NotificationResponse {
1559 readonly _tag: "NotificationResponse"
1560 readonly pid: number
1561 readonly channel: string
1562 readonly payload: string
1563 }
1564
1565 /**
1566 * The server speaks an older minor protocol version, or did not recognise
1567 * some startup options.
1568 *
1569 * @stability unstable
1570 * @category models
1571 * @since 4.0.0
1572 */
1573 export interface NegotiateProtocolVersion {
1574 readonly _tag: "NegotiateProtocolVersion"
1575 readonly minorVersion: number
1576 readonly unrecognizedOptions: ReadonlyArray<string>
1577 }
1578
1579 /**
1580 * The server is ready to receive `COPY` data.
1581 *
1582 * @stability unstable
1583 * @category models
1584 * @since 4.0.0
1585 */
1586 export interface CopyInResponse {
1587 readonly _tag: "CopyInResponse"
1588 readonly format: number
1589 readonly columnFormats: ReadonlyArray<number>
1590 }
1591
1592 /**
1593 * The server is about to send `COPY` data.
1594 *
1595 * @stability unstable
1596 * @category models
1597 * @since 4.0.0
1598 */
1599 export interface CopyOutResponse {
1600 readonly _tag: "CopyOutResponse"
1601 readonly format: number
1602 readonly columnFormats: ReadonlyArray<number>
1603 }
1604
1605 /**
1606 * The connection entered bidirectional `COPY` mode, as used by replication.
1607 *
1608 * @stability unstable
1609 * @category models
1610 * @since 4.0.0
1611 */
1612 export interface CopyBothResponse {
1613 readonly _tag: "CopyBothResponse"
1614 readonly format: number
1615 readonly columnFormats: ReadonlyArray<number>
1616 }
1617
1618 /**
1619 * A chunk of `COPY` data.
1620 *
1621 * @stability unstable
1622 * @category models
1623 * @since 4.0.0
1624 */
1625 export interface CopyData {
1626 readonly _tag: "CopyData"
1627 readonly data: Uint8Array
1628 }
1629
1630 /**
1631 * The `COPY` stream ended.
1632 *
1633 * @stability unstable
1634 * @category models
1635 * @since 4.0.0
1636 */
1637 export interface CopyDone {
1638 readonly _tag: "CopyDone"
1639 }
1640
1641 /**
1642 * A message whose type byte this codec does not know. The payload excludes
1643 * the type byte and the length prefix.
1644 *
1645 * @stability unstable
1646 * @category models
1647 * @since 4.0.0
1648 */
1649 export interface Unknown {
1650 readonly _tag: "Unknown"
1651 readonly type: number
1652 readonly payload: Uint8Array
1653 }
1654
1655 /**
1656 * Any message the server sends after startup.
1657 *
1658 * @stability unstable
1659 * @category models
1660 * @since 4.0.0
1661 */
1662 export type BackendMessage<A = Uint8Array | null> =
1663 | AuthenticationOk
1664 | AuthenticationCleartextPassword
1665 | AuthenticationMD5Password
1666 | AuthenticationSASL
1667 | AuthenticationSASLContinue
1668 | AuthenticationSASLFinal
1669 | AuthenticationUnsupported
1670 | ParameterStatus
1671 | BackendKeyData
1672 | ReadyForQuery
1673 | RowDescription
1674 | DataRow<A>
1675 | CommandComplete
1676 | EmptyQueryResponse
1677 | NoData
1678 | ParseComplete
1679 | BindComplete
1680 | CloseComplete
1681 | PortalSuspended
1682 | ParameterDescription
1683 | ErrorResponse
1684 | NoticeResponse
1685 | NotificationResponse
1686 | NegotiateProtocolVersion
1687 | CopyInResponse
1688 | CopyOutResponse
1689 | CopyBothResponse
1690 | CopyData
1691 | CopyDone
1692 | Unknown
1693
1694 const BackendType = {
1695 NotificationResponse: 0x41, // A
1696 CommandComplete: 0x43, // C
1697 DataRow: 0x44, // D
1698 ErrorResponse: 0x45, // E
1699 CopyInResponse: 0x47, // G
1700 CopyOutResponse: 0x48, // H
1701 EmptyQueryResponse: 0x49, // I
1702 BackendKeyData: 0x4b, // K
1703 NoticeResponse: 0x4e, // N
1704 Authentication: 0x52, // R
1705 ParameterStatus: 0x53, // S
1706 RowDescription: 0x54, // T
1707 CopyBothResponse: 0x57, // W
1708 ReadyForQuery: 0x5a, // Z
1709 CopyDone: 0x63, // c
1710 CopyData: 0x64, // d
1711 NoData: 0x6e, // n
1712 PortalSuspended: 0x73, // s
1713 ParameterDescription: 0x74, // t
1714 NegotiateProtocolVersion: 0x76, // v
1715 ParseComplete: 0x31, // 1
1716 BindComplete: 0x32, // 2
1717 CloseComplete: 0x33 // 3
1718 } as const
1719
1720 const errorFieldNames: Record<string, string> = {
1721 S: "severity",
1722 V: "severityUnlocalized",
1723 C: "code",
1724 M: "message",
1725 D: "detail",
1726 H: "hint",
1727 P: "position",
1728 p: "internalPosition",
1729 q: "internalQuery",
1730 W: "where",
1731 s: "schema",
1732 t: "table",
1733 c: "column",
1734 d: "dataType",
1735 n: "constraint",
1736 F: "file",
1737 L: "line",
1738 R: "routine"
1739 }
1740
1741 const decodeAuthentication = (reader: Reader): BackendMessage => {
1742 const method = reader.int32()
1743 switch (method) {
1744 case 0:
1745 return { _tag: "AuthenticationOk" }
1746 case 3:
1747 return { _tag: "AuthenticationCleartextPassword" }
1748 case 5:
1749 return { _tag: "AuthenticationMD5Password", salt: reader.raw(4) }
1750 case 10: {
1751 const mechanisms: Array<string> = []
1752 for (;;) {
1753 const mechanism = reader.cString()
1754 if (mechanism === "") break
1755 mechanisms.push(mechanism)
1756 }
1757 return { _tag: "AuthenticationSASL", mechanisms }
1758 }
1759 case 11:
1760 return { _tag: "AuthenticationSASLContinue", data: reader.rest() }
1761 case 12:
1762 return { _tag: "AuthenticationSASLFinal", data: reader.rest() }
1763 default:
1764 return { _tag: "AuthenticationUnsupported", method, payload: reader.rest() }
1765 }
1766 }
1767
1768 const decodeErrorFields = (reader: Reader): ErrorFields => {
1769 const fields: Record<string, string> = {}
1770 for (;;) {
1771 const code = reader.uint8()
1772 if (code === 0) break
1773 const key = String.fromCharCode(code)
1774 fields[errorFieldNames[key] ?? key] = reader.cString()
1775 }
1776 return fields
1777 }
1778
1779 const requireNonNegativeCount = (count: number, name: string): number => {
1780 if (count < 0) {
1781 throw new ParseError({ message: `Invalid ${name} count: ${count}` })
1782 }
1783 return count
1784 }
1785
1786 const decodeCopyResponse = (
1787 reader: Reader
1788 ): { readonly format: number; readonly columnFormats: ReadonlyArray<number> } => {
1789 const format = reader.uint8()
1790 const count = requireNonNegativeCount(reader.int16(), "COPY column")
1791 const columnFormats: Array<number> = new Array(count)
1792 for (let i = 0; i < count; i++) {
1793 columnFormats[i] = reader.int16()
1794 }
1795 return { format, columnFormats }
1796 }
1797
1798 // The one message that arrives per result row, so it reads the frame directly
1799 // instead of going through `Reader`. Callers have already checked that the
1800 // whole frame is buffered, which turns every field read into one bounds check
1801 // against `limit`.
1802 const decodeDataRow = <A>(
1803 bytes: Uint8Array,
1804 store: ArrayBufferLike,
1805 base: number,
1806 offset: number,
1807 limit: number,
1808 readField: FieldReader<A> | undefined
1809 ): DataRow<A> => {
1810 if (offset + 2 > limit) {
1811 throw new ParseError({ message: "Truncated message: expected 2 more byte(s)" })
1812 }
1813 const count = ((bytes[offset] << 8) | bytes[offset + 1]) << 16 >> 16
1814 if (count < 0) {
1815 throw new ParseError({ message: `Invalid DataRow field count: ${count}` })
1816 }
1817 const values: Array<any> = new Array(count)
1818 let position = offset + 2
1819 for (let i = 0; i < count; i++) {
1820 if (position + 4 > limit) {
1821 throw new ParseError({ message: "Truncated message: expected 4 more byte(s)" })
1822 }
1823 const size = (bytes[position] << 24) | (bytes[position + 1] << 16) | (bytes[position + 2] << 8) |
1824 bytes[position + 3]
1825 position += 4
1826 if (size < 0) {
1827 if (size < -1) {
1828 throw new ParseError({ message: `Invalid DataRow field length: ${size}` })
1829 }
1830 values[i] = readField === undefined ? null : readField(bytes, position, -1, i)
1831 continue
1832 }
1833 const next = position + size
1834 if (next > limit) {
1835 throw new ParseError({ message: `Truncated message: expected ${size} more byte(s)` })
1836 }
1837 values[i] = readField === undefined
1838 ? view(store, base + position, size)
1839 : readField(bytes, position, size, i)
1840 position = next
1841 }
1842 if (position !== limit) {
1843 throw new ParseError({ message: `DataRow has ${limit - position} trailing byte(s)` })
1844 }
1845 return { _tag: "DataRow", values }
1846 }
1847
1848 const decodeBackend = (type: number, reader: Reader): BackendMessage => {
1849 switch (type) {
1850 case BackendType.Authentication:
1851 return decodeAuthentication(reader)
1852 case BackendType.ParameterStatus:
1853 return { _tag: "ParameterStatus", name: reader.cString(), value: reader.cString() }
1854 case BackendType.BackendKeyData:
1855 return { _tag: "BackendKeyData", pid: reader.int32(), secret: reader.int32() }
1856 case BackendType.ReadyForQuery: {
1857 const status = String.fromCharCode(reader.uint8())
1858 if (status !== "I" && status !== "T" && status !== "E") {
1859 throw new ParseError({ message: `Invalid ReadyForQuery status: ${status}` })
1860 }
1861 return { _tag: "ReadyForQuery", status }
1862 }
1863 case BackendType.RowDescription: {
1864 const count = requireNonNegativeCount(reader.int16(), "RowDescription field")
1865 const fields: Array<FieldDescription> = new Array(count)
1866 for (let i = 0; i < count; i++) {
1867 fields[i] = {
1868 name: reader.cString(),
1869 tableOid: reader.uint32(),
1870 columnAttributeNumber: reader.int16(),
1871 dataTypeOid: reader.uint32(),
1872 dataTypeSize: reader.int16(),
1873 typeModifier: reader.int32(),
1874 format: reader.int16()
1875 }
1876 }
1877 return { _tag: "RowDescription", fields }
1878 }
1879 case BackendType.DataRow:
1880 return decodeDataRow(reader.bytes, reader.store, reader.base, reader.offset, reader.limit, undefined)
1881 case BackendType.CommandComplete:
1882 return { _tag: "CommandComplete", commandTag: reader.cString() }
1883 case BackendType.EmptyQueryResponse:
1884 return { _tag: "EmptyQueryResponse" }
1885 case BackendType.NoData:
1886 return { _tag: "NoData" }
1887 case BackendType.ParseComplete:
1888 return { _tag: "ParseComplete" }
1889 case BackendType.BindComplete:
1890 return { _tag: "BindComplete" }
1891 case BackendType.CloseComplete:
1892 return { _tag: "CloseComplete" }
1893 case BackendType.PortalSuspended:
1894 return { _tag: "PortalSuspended" }
1895 case BackendType.ParameterDescription: {
1896 const count = requireNonNegativeCount(reader.int16(), "ParameterDescription parameter")
1897 const parameterTypes: Array<number> = new Array(count)
1898 for (let i = 0; i < count; i++) {
1899 parameterTypes[i] = reader.uint32()
1900 }
1901 return { _tag: "ParameterDescription", parameterTypes }
1902 }
1903 case BackendType.ErrorResponse:
1904 return { _tag: "ErrorResponse", fields: decodeErrorFields(reader) }
1905 case BackendType.NoticeResponse:
1906 return { _tag: "NoticeResponse", fields: decodeErrorFields(reader) }
1907 case BackendType.NotificationResponse:
1908 return {
1909 _tag: "NotificationResponse",
1910 pid: reader.int32(),
1911 channel: reader.cString(),
1912 payload: reader.cString()
1913 }
1914 case BackendType.NegotiateProtocolVersion: {
1915 const minorVersion = reader.int32()
1916 const count = requireNonNegativeCount(reader.int32(), "NegotiateProtocolVersion option")
1917 const unrecognizedOptions: Array<string> = new Array(count)
1918 for (let i = 0; i < count; i++) {
1919 unrecognizedOptions[i] = reader.cString()
1920 }
1921 return { _tag: "NegotiateProtocolVersion", minorVersion, unrecognizedOptions }
1922 }
1923 case BackendType.CopyInResponse:
1924 return { _tag: "CopyInResponse", ...decodeCopyResponse(reader) }
1925 case BackendType.CopyOutResponse:
1926 return { _tag: "CopyOutResponse", ...decodeCopyResponse(reader) }
1927 case BackendType.CopyBothResponse:
1928 return { _tag: "CopyBothResponse", ...decodeCopyResponse(reader) }
1929 case BackendType.CopyData:
1930 return { _tag: "CopyData", data: reader.rest() }
1931 case BackendType.CopyDone:
1932 return { _tag: "CopyDone" }
1933 default:
1934 return { _tag: "Unknown", type, payload: reader.rest() }
1935 }
1936 }