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

Function sendCancelRequest

packages/sql/pg/src/PgConnection.ts:2379–2435  ·  view source on GitHub ↗
(config: ResolvedConfig, session: Session)

Source from the content-addressed store, hash-verified

2377 Effect.provideService(effect, Scheduler.PreventSchedulerYield, true)
2378
2379const sendCancelRequest = (config: ResolvedConfig, session: Session): Effect.Effect<void> =>
2380 Effect.callback<void>((resume) => {
2381 let done = false
2382 let socket: Duplex
2383 let timer: ReturnType<typeof setTimeout> | undefined
2384 const finish = (): void => {
2385 if (done) return
2386 done = true
2387 if (timer !== undefined) clearTimeout(timer)
2388 socket?.destroy()
2389 resume(Effect.void)
2390 }
2391 const frame = PgProtocol.encodeCancelRequest({ pid: session.processId, secret: session.secretKey })
2392 // After the frame is written the server processes the request and closes
2393 // the connection, which lands in the `close` handler.
2394 const send = (): void => {
2395 socket.write(frame)
2396 }
2397 const begin = (): void => {
2398 if (config.ssl === false) return send()
2399 socket.once("data", (chunk: Uint8Array) => {
2400 if (done) return
2401 // A TLS session's cancel secret must stay encrypted.
2402 if (chunk.length === 1 && chunk[0] === 0x4e && config.sslOptional && !session.encrypted) return send()
2403 if (chunk.length !== 1 || chunk[0] !== 0x53) return finish()
2404 const raw = socket
2405 raw.off("error", finish)
2406 raw.off("close", finish)
2407 socket = Tls.connect({
2408 host: config.host,
2409 servername: Net.isIP(config.host) === 0 ? config.host : undefined,
2410 ...(typeof config.ssl === "object" ? config.ssl : {}),
2411 socket: raw as Net.Socket
2412 })
2413 socket.on("error", finish)
2414 socket.on("close", finish)
2415 socket.once("secureConnect", send)
2416 })
2417 socket.write(PgProtocol.encodeSslRequest())
2418 }
2419 try {
2420 socket = config.stream !== undefined
2421 ? config.stream()
2422 : config.path !== undefined
2423 ? Net.connect({ path: config.path })
2424 : Net.connect({ host: config.host, port: config.port, noDelay: true })
2425 } catch {
2426 resume(Effect.void)
2427 return
2428 }
2429 timer = setTimeout(finish, cancelRequestTimeoutMillis)
2430 socket.on("error", finish)
2431 socket.on("close", finish)
2432 if (config.stream !== undefined) begin()
2433 else socket.once("connect", begin)
2434 return Effect.sync(finish)
2435 })
2436

Callers 1

PgConnectionImplClass · 0.85

Calls 7

onceMethod · 0.80
beginFunction · 0.70
streamMethod · 0.65
connectMethod · 0.65
onMethod · 0.65
resumeFunction · 0.50
syncMethod · 0.45

Tested by

no test coverage detected