mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-03 03:25:40 +08:00
Co-authored-by: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com>
210 lines
7.8 KiB
TypeScript
210 lines
7.8 KiB
TypeScript
import { PgConnection } from "@effect/sql-pg"
|
|
import { assert, describe, it } from "@effect/vitest"
|
|
import { Cause, Effect, Exit, Fiber, Option, Redacted, Tracer } from "effect"
|
|
import * as TestClock from "effect/testing/TestClock"
|
|
import { Buffer } from "node:buffer"
|
|
import { Duplex } from "node:stream"
|
|
|
|
const recording = () => {
|
|
const spans: Array<Tracer.NativeSpan> = []
|
|
const tracer = Tracer.make({
|
|
span(options) {
|
|
const span = new Tracer.NativeSpan(options)
|
|
spans.push(span)
|
|
return span
|
|
}
|
|
})
|
|
return { tracer, named: (name: string) => spans.filter((span) => span.name === name) }
|
|
}
|
|
|
|
const backendMessage = (tag: string, payload: Buffer): Buffer => {
|
|
const length = Buffer.allocUnsafe(4)
|
|
length.writeInt32BE(payload.length + 4)
|
|
return Buffer.concat([Buffer.from(tag), length, payload])
|
|
}
|
|
|
|
const replyingWith = (message: Buffer) => () => {
|
|
const socket = new Duplex({
|
|
read() {},
|
|
write(_chunk: Buffer, _encoding, callback) {
|
|
queueMicrotask(() => socket.push(message))
|
|
callback()
|
|
}
|
|
})
|
|
return socket
|
|
}
|
|
|
|
const errorResponse = (code: string) => backendMessage("E", Buffer.from(`SFATAL\0C${code}\0Msecret-server-msg\0\0`))
|
|
|
|
describe("PgConnection config", () => {
|
|
it.effect("rejects sub-second keepalive before connecting", () =>
|
|
Effect.gen(function*() {
|
|
let connected = false
|
|
const error = yield* Effect.flip(PgConnection.make({
|
|
username: "test",
|
|
keepAlive: "999 millis",
|
|
stream: () => {
|
|
connected = true
|
|
throw new Error("unexpected connection")
|
|
}
|
|
}))
|
|
assert.isFalse(connected)
|
|
assert.strictEqual(error.reason._tag, "ConnectionError")
|
|
}))
|
|
|
|
it.effect.each([
|
|
{ startupParameters: { REPLICATION: "database" } },
|
|
{ startupParameters: { client_encoding: "LATIN1" } },
|
|
{ startupParameters: { "": "value" } },
|
|
{ startupParameters: { search_path: "public\0private" } },
|
|
{ startupOptions: "-c lock_timeout=2345\0" },
|
|
{ url: Redacted.make("postgres://test@localhost/db?options=%00") }
|
|
])("rejects invalid startup config %j before connecting", (config) =>
|
|
Effect.gen(function*() {
|
|
let connected = false
|
|
const error = yield* Effect.flip(PgConnection.make({
|
|
...config,
|
|
username: "test",
|
|
stream: () => {
|
|
connected = true
|
|
throw new Error("unexpected connection")
|
|
}
|
|
}))
|
|
assert.isFalse(connected)
|
|
assert.strictEqual(error.reason._tag, "ConnectionError")
|
|
}))
|
|
|
|
it.effect("interrupts a stalled password provider when connectTimeout expires", () => {
|
|
const { named, tracer } = recording()
|
|
return Effect.gen(function*() {
|
|
let connected = false
|
|
let interrupted = false
|
|
const fiber = yield* PgConnection.make({
|
|
username: "test",
|
|
password: Effect.never.pipe(
|
|
Effect.withSpan("resolve password"),
|
|
Effect.onInterrupt(() =>
|
|
Effect.sync(() => {
|
|
interrupted = true
|
|
})
|
|
)
|
|
),
|
|
connectTimeout: "1 second",
|
|
stream: () => {
|
|
connected = true
|
|
throw new Error("unexpected connection")
|
|
}
|
|
}).pipe(Effect.withSpan("caller"), Effect.flip, Effect.forkScoped)
|
|
|
|
yield* TestClock.adjust("1 second")
|
|
const error = yield* Fiber.join(fiber)
|
|
|
|
assert.isFalse(connected)
|
|
assert.isTrue(interrupted)
|
|
assert.strictEqual(error.reason._tag, "ConnectionError")
|
|
assert.strictEqual(error.reason.message, "PgConnection: Connection timed out")
|
|
assert.isTrue(error.isRetryable)
|
|
|
|
const [attempt] = named("sql.connect")
|
|
assert.strictEqual(attempt.kind, "client")
|
|
assert.strictEqual(Option.getOrThrow(attempt.parent).spanId, named("caller")[0].spanId)
|
|
assert.strictEqual(Option.getOrThrow(named("resolve password")[0].parent).spanId, attempt.spanId)
|
|
assert.isTrue(attempt.status._tag === "Ended" && Exit.isFailure(attempt.status.exit))
|
|
assert.strictEqual(attempt.attributes.get("db.system.name"), "postgresql")
|
|
assert.strictEqual(attempt.attributes.get("db.namespace"), "test")
|
|
assert.strictEqual(attempt.attributes.get("error.type"), "timeout")
|
|
assert.isFalse(attempt.attributes.has("server.address"))
|
|
}).pipe(Effect.withTracer(tracer))
|
|
})
|
|
|
|
it.effect.each([
|
|
{ name: "auth", stream: replyingWith(errorResponse("28P01")), type: "auth", code: "28P01" },
|
|
{ name: "startup rejection", stream: replyingWith(errorResponse("53300")), type: "refused", code: "53300" },
|
|
{
|
|
name: "socket error",
|
|
stream: () => {
|
|
const socket = new Duplex({ read() {}, write() {} })
|
|
queueMicrotask(() => socket.destroy(new Error("secret-socket-msg")))
|
|
return socket
|
|
},
|
|
type: "refused",
|
|
code: undefined
|
|
},
|
|
{
|
|
name: "protocol desync",
|
|
stream: replyingWith(backendMessage("C", Buffer.from("SELECT 1\0"))),
|
|
type: "other",
|
|
code: undefined
|
|
}
|
|
])("classifies connect failures ($name) without exporting secrets", ({ code, stream, type }) => {
|
|
const { named, tracer } = recording()
|
|
return Effect.gen(function*() {
|
|
yield* Effect.flip(PgConnection.make({
|
|
url: Redacted.make("postgres://user:super-secret@localhost:5432/app"),
|
|
stream
|
|
}))
|
|
const [attempt] = named("sql.connect")
|
|
assert.strictEqual(attempt.attributes.get("error.type"), type)
|
|
assert.strictEqual(attempt.attributes.get("db.response.status_code"), code)
|
|
assert.isTrue(attempt.status._tag === "Ended" && Exit.isFailure(attempt.status.exit))
|
|
if (attempt.status._tag === "Ended" && Exit.isFailure(attempt.status.exit)) {
|
|
const exported = JSON.stringify([...attempt.attributes]) + Cause.pretty(attempt.status.exit.cause)
|
|
assert.notInclude(exported, "secret")
|
|
}
|
|
}).pipe(Effect.withTracer(tracer))
|
|
})
|
|
|
|
it.effect("ends sql.connect without error.type when the caller interrupts", () => {
|
|
const { named, tracer } = recording()
|
|
return Effect.gen(function*() {
|
|
const fiber = yield* PgConnection.make({ username: "test", password: Effect.never }).pipe(Effect.forkScoped)
|
|
yield* Effect.yieldNow
|
|
yield* Fiber.interrupt(fiber)
|
|
const [attempt] = named("sql.connect")
|
|
assert.isTrue(
|
|
attempt.status._tag === "Ended" && Exit.isFailure(attempt.status.exit) &&
|
|
Cause.hasInterruptsOnly(attempt.status.exit.cause)
|
|
)
|
|
assert.isFalse(attempt.attributes.has("error.type"))
|
|
}).pipe(Effect.withTracer(tracer))
|
|
})
|
|
|
|
it.effect.each(["prefer", "allow"])("accepts sslmode=%s in a URL", (sslmode) =>
|
|
Effect.gen(function*() {
|
|
let connected = false
|
|
const error = yield* Effect.flip(PgConnection.make({
|
|
url: Redacted.make(`postgres://user@localhost/db?sslmode=${sslmode}`),
|
|
stream: () => {
|
|
connected = true
|
|
throw new Error("test connection")
|
|
}
|
|
}))
|
|
assert.isTrue(connected)
|
|
assert.strictEqual(error.reason._tag, "ConnectionError")
|
|
assert.strictEqual(error.reason.message, "PgConnection: Failed to connect")
|
|
}))
|
|
|
|
it.effect("rejects an unrecognized sslmode before connecting", () =>
|
|
Effect.gen(function*() {
|
|
let connected = false
|
|
const error = yield* Effect.flip(PgConnection.make({
|
|
url: Redacted.make("postgresql://user@localhost/db?sslmode=invalid"),
|
|
stream: () => {
|
|
connected = true
|
|
throw new Error("test connection")
|
|
}
|
|
}))
|
|
assert.isFalse(connected)
|
|
assert.strictEqual(error.reason._tag, "ConnectionError")
|
|
assert.strictEqual(error.reason.message, "PgConnection: Unrecognized sslmode in URL: \"invalid\"")
|
|
}))
|
|
|
|
it.effect("rejects a non-postgres URL protocol", () =>
|
|
Effect.gen(function*() {
|
|
const error = yield* Effect.flip(PgConnection.make({
|
|
url: Redacted.make("mysql://user@localhost/db")
|
|
}))
|
|
assert.strictEqual(error.reason._tag, "ConnectionError")
|
|
}))
|
|
})
|