MCPcopy Create free account
hub / github.com/Effect-TS/effect / Session

Class Session

packages/sql/pg/test/fixtures/regenerate.ts:39–113  ·  view source on GitHub ↗

A connection that records the raw bytes of every backend message.

Source from the content-addressed store, hash-verified

37
38/** A connection that records the raw bytes of every backend message. */
39class Session {
40 readonly socket: net.Socket
41 readonly parser = PgProtocol.makeParser()
42 readonly frames: Array<{ readonly tag: string; readonly hex: string }> = []
43 private buffer = Buffer.alloc(0)
44 private readonly pending: Array<PgProtocol.BackendMessage> = []
45 private readonly waiters: Array<() => void> = []
46
47 constructor(socket: net.Socket) {
48 this.socket = socket
49 socket.on("data", (chunk) => this.onData(chunk as Buffer))
50 }
51
52 /** Connects, negotiates TLS away, and starts recording frames. */
53 static async connect(): Promise<{ readonly session: Session; readonly sslResponse: "S" | "N" }> {
54 const socket = net.connect({ host: HOST, port: PORT })
55 await new Promise<void>((resolve, reject) => {
56 socket.once("connect", resolve)
57 socket.once("error", reject)
58 })
59 socket.write(PgProtocol.encodeSslRequest())
60 const byte = await new Promise<number>((resolve) => socket.once("data", (data) => resolve((data as Buffer)[0])))
61 return { session: new Session(socket), sslResponse: success(PgProtocol.decodeSslResponse(byte)) }
62 }
63
64 private onData(chunk: Buffer): void {
65 this.buffer = Buffer.concat([this.buffer, chunk])
66 while (this.buffer.length >= 5) {
67 const length = this.buffer.readInt32BE(1)
68 if (this.buffer.length < length + 1) break
69 const frame = new Uint8Array(this.buffer.subarray(0, length + 1))
70 this.buffer = this.buffer.subarray(length + 1)
71 for (const message of this.parser.push(frame)) {
72 this.frames.push({ tag: message._tag, hex: toHex(frame) })
73 this.pending.push(message)
74 }
75 }
76 while (this.waiters.length > 0) this.waiters.pop()!()
77 }
78
79 async next(): Promise<PgProtocol.BackendMessage> {
80 while (this.pending.length === 0) {
81 await new Promise<void>((resolve) => this.waiters.push(resolve))
82 }
83 return this.pending.shift()!
84 }
85
86 write(bytes: Uint8Array): void {
87 this.socket.write(bytes)
88 }
89
90 /** The first frame with this tag recorded at or after `from`. */
91 frameFrom(tag: string, from: number): string | undefined {
92 return this.frames.slice(from).find((frame) => frame.tag === tag)?.hex
93 }
94
95 /** Runs an extended-query cycle and returns every message it produced. */
96 async query(

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected