Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PgPool.ts

386 lines15.5 KB

1/**
2 * Pools of native `PgConnection` sessions.
3 *
4 * @stability unstable
5 * @since 4.0.0
6 */
7import * as Clock from "effect/Clock"
8import * as Context from "effect/Context"
9import * as Duration from "effect/Duration"
10import * as Effect from "effect/Effect"
11import * as Exit from "effect/Exit"
12import * as Option from "effect/Option"
13import * as Pool from "effect/Pool"
14import { TracerTimingEnabled } from "effect/References"
15import * as Scope from "effect/Scope"
16import * as Semaphore from "effect/Semaphore"
17import { ConnectionError, SqlError } from "effect/sql/SqlError"
18import { SpanPropagationEnabled } from "effect/sql/Statement"
19import * as Tracer from "effect/Tracer"
20import { connectionInternals } from "./internal/connection.ts"
21import * as PgConnection from "./PgConnection.ts"
22​
23const defaultMultiplexConcurrency = 32
24​
25/**
26 * The runtime type identifier for `PgPool`.
27 *
28 * @stability unstable
29 * @category type IDs
30 * @since 4.0.0
31 */
32export const TypeId: TypeId = "~@effect/sql-pg/PgPool"
33​
34/**
35 * The type-level identifier for `PgPool`.
36 *
37 * @stability unstable
38 * @category type IDs
39 * @since 4.0.0
40 */
41export type TypeId = "~@effect/sql-pg/PgPool"
42​
43/**
44 * Connection and sizing settings for a PostgreSQL session pool.
45 *
46 * **Details**
47 *
48 * The defaults are 0 to 10 connections and a 60-second idle timeout.
49 * `connectionTTL` replaces connections that exceed the configured lifetime.
50 * A retired session keeps its `maxConnections` slot until its transport closes.
51 * Every connection is used at least once, so a TTL of zero disables reuse.
52 * `acquireTimeout` bounds how long a checkout takes to acquire a connection,
53 * including opening a new one; by default it waits indefinitely.
54 *
55 * With `multiplex` enabled, fibers may share pooled connections for pipelined
56 * queries. Reserved connections remain exclusive. Without multiplexing, every
57 * checkout is exclusive.
58 *
59 * @stability unstable
60 * @category models
61 * @since 4.0.0
62 */
63export interface Config extends PgConnection.Config {
64 readonly idleTimeout?: Duration.Input | undefined
65 readonly maxConnections?: number | undefined
66 readonly minConnections?: number | undefined
67 readonly connectionTTL?: Duration.Input | undefined
68 /**
69 * How long a checkout may take to acquire a connection before failing with
70 * a `ConnectionError`. Acquisition includes waiting for a free connection
71 * and opening a new one when the pool needs it. With `multiplex` on,
72 * `reserve` also waits for statements already sent on the shared connection
73 * to finish, and that wait counts too. Work done with the connection after
74 * it is acquired is not bounded. Unbounded by default.
75 */
76 readonly acquireTimeout?: Duration.Input | undefined
77 /**
78 * How many statements may share one connection when `multiplex` is on.
79 * Defaults to `32`. Statements are pipelined into one write, so a higher
80 * number means fewer round trips, but it also means a slow statement holds
81 * up more of the statements queued behind it.
82 */
83 readonly multiplexConcurrency?: number | undefined
85​
86/**
87 * A PostgreSQL session pool.
88 *
89 * @stability unstable
90 * @category models
91 * @since 4.0.0
92 */
93export interface PgPool {
94 readonly [TypeId]: TypeId
95 readonly config: Config
96 /**
97 * Checks out a session until the scope closes. Without multiplexing the
98 * checkout is exclusive. With multiplexing the
99 * session may be shared with other fibers, so multi-statement work should
100 * use `reserve` instead.
101 */
102 readonly get: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope>
103 /**
104 * Checks out a session for exclusive use until the scope closes. Use this for
105 * transactions and listeners on a multiplexed pool.
106 */
107 readonly reserve: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope>
108 /**
109 * Removes a session so the pool can replace it. Fatal protocol and socket
110 * errors invalidate sessions automatically.
111 */
112 /**
113 * Lends a session for the duration of one effect and takes it back on any
114 * exit, without opening a scope for it.
115 *
116 * **Details**
117 *
118 * For work that finishes with the effect that runs it. A lease that has to
119 * outlive its effect - a stream, a transaction - takes `get` or `reserve`.
120 */
121 readonly use: <A, E, R>(
122 f: (connection: PgConnection.PgConnection) => Effect.Effect<A, E, R>
123 ) => Effect.Effect<A, E | SqlError, R>
124 readonly invalidate: (connection: PgConnection.PgConnection) => Effect.Effect<void>
125 /**
126 * Returns a snapshot of session occupancy. Counts sessions rather than
127 * statements, so a multiplexed session shared by many fibers counts once. A
128 * session that has just failed can show as idle until the pool removes it.
129 */
130 readonly stats: Effect.Effect<Pool.Stats>
132​
133/**
134 * The service tag for `PgPool`.
135 *
136 * @stability unstable
137 * @category services
138 * @since 4.0.0
139 */
140export const PgPool = Context.Service<PgPool>("@effect/sql-pg/PgPool")
141​
142/**
143 * Creates a scoped PostgreSQL session pool.
144 *
145 * **Details**
146 *
147 * Connections are opened lazily up to `maxConnections` and released down to
148 * `minConnections` after `idleTimeout` without use. A retired session stops
149 * being handed out immediately, but its slot is held until its transport
150 * closes. Closing the scope shuts the pool down and releases every session.
151 *
152 * With `SpanPropagationEnabled`, a statement that waited for a new session gets
153 * a `db.connect` child span covering the part of the connect it waited for.
154 *
155 * @stability unstable
156 * @category constructors
157 * @since 4.0.0
158 */
159export const make = Effect.fnUntraced(function*(options: Config): Effect.fn.Return<PgPool, SqlError, Scope.Scope> {
160 const clock = yield* Clock.Clock
161 const runFork = Effect.runForkWith(yield* Effect.context())
162​
163 const multiplex = options.multiplex ?? false
164 const connectionTTL = options.connectionTTL !== undefined
165 ? Duration.toMillis(Duration.fromInputUnsafe(options.connectionTTL))
166 : undefined
167 const acquireTimeout = options.acquireTimeout !== undefined
168 ? Duration.fromInputUnsafe(options.acquireTimeout)
169 : undefined
170 const deadConnections = new Set<PgConnection.PgConnection>()
171 const createdAt = new WeakMap<PgConnection.PgConnection, number>()
172 const checkedOut = new WeakSet<PgConnection.PgConnection>()
173​
174 // The pool opens sessions on its own fiber, where a span would have no
175 // statement parent. Each connect is recorded here instead and reported on the
176 // session's first checkout, under the statement that waited for it.
177 const connects = new WeakMap<PgConnection.PgConnection, readonly [startTime: bigint, endTime: bigint]>()
178​
179 const reportConnect = (connection: PgConnection.PgConnection): Effect.Effect<void> =>
180 Effect.withFiber((fiber) => {
181 const opened = connects.get(connection)
182 if (opened === undefined) return Effect.void
183 connects.delete(connection)
184 const statement = fiber.cache.span
185 // Without span timing the statement span has no start time to measure from.
186 if (
187 !fiber.cache.tracerEnabled || statement?._tag !== "Span" || !fiber.getRef(SpanPropagationEnabled) ||
188 !fiber.getRef(TracerTimingEnabled)
189 ) {
190 return Effect.void
191 }
192 const [startTime, endTime] = opened
193 const waitedFrom = statement.status.startTime
194 if (endTime < waitedFrom) return Effect.void
195 const span = fiber.getRef(Tracer.Tracer).span({
196 name: "db.connect",
197 parent: Option.some(statement),
198 annotations: Context.empty(),
199 links: [],
200 startTime: startTime > waitedFrom ? startTime : waitedFrom,
201 kind: "client",
202 root: false,
203 sampled: statement.sampled
204 })
205 span.attribute("db.system.name", "postgresql")
206 span.attribute("db.client.connection.connect_time_ms", Number(endTime - startTime) / 1e6)
207 span.end(endTime, Exit.void)
208 return Effect.void
209 })
210​
211 const handOut = (connection: PgConnection.PgConnection) =>
212 connects.has(connection) ? Effect.as(reportConnect(connection), connection) : Effect.succeed(connection)
213​
214 // Assigned below, once the pool exists. `acquire` only runs when the pool
215 // opens a connection, which is always after that.
216 let pool: Pool.Pool<PgConnection.PgConnection, SqlError>
217 const maxConnections = options.maxConnections ?? 10
218 // One permit per open transport. The pool replaces a retired session at
219 // once, but the replacement only connects after the old transport closes.
220 const transports = Semaphore.makeUnsafe(maxConnections)
221 const acquire = Effect.uninterruptibleMask((restore) => {
222 // Closed once: on connect failure/interruption or when the transport closes.
223 const permit = Scope.makeUnsafe()
224 return Effect.onError(
225 Effect.flatMap(restore(Scope.provide(transports.takeScoped(1), permit)), () => {
226 const startTime = clock.currentTimeNanosUnsafe()
227 return Effect.map(restore(PgConnection.make(options)), (connection) => {
228 connects.set(connection, [startTime, clock.currentTimeNanosUnsafe()])
229 createdAt.set(connection, clock.currentTimeMillisUnsafe())
230 const internals = connectionInternals(connection)
231 internals.onTransportClose(() => runFork(Scope.close(permit, Exit.void)))
232 internals.retireHooks.add(() => {
233 deadConnections.add(connection)
234 // `deadConnections` is only read by the next checkout, and a checkout
235 // already waiting for this connection would never get that far. Tell
236 // the pool now so it can replace the connection and admit them.
237 runFork(Pool.invalidate(pool, connection))
238 })
239 // Pinning a shared session has to take it out of circulation, or a
240 // second checkout lands on the connection its own stream is holding.
241 if (multiplex) internals.reserve = Pool.reserve(pool, connection)
242 return connection
243 })
244 }),
245 (cause) => Scope.close(permit, Exit.failCause(cause))
246 )
247 })
248​
249 pool = yield* Pool.makeWithTTL({
250 acquire,
251 min: options.minConnections ?? 0,
252 max: maxConnections,
253 concurrency: multiplex
254 ? Math.max(1, options.multiplexConcurrency ?? defaultMultiplexConcurrency)
255 : 1,
256 timeToLive: options.idleTimeout ?? Duration.seconds(60),
257 timeToLiveStrategy: "usage"
258 })
259​
260 const expired = (connection: PgConnection.PgConnection): boolean => {
261 if (connectionInternals(connection).deadError() !== undefined) return true
262 if (connectionTTL === undefined) return false
263 if (!checkedOut.has(connection)) {
264 checkedOut.add(connection)
265 return false
266 }
267 const openedAt = createdAt.get(connection)
268 return openedAt !== undefined && clock.currentTimeMillisUnsafe() - openedAt >= connectionTTL
269 }
270​
271 // Runs `f` uninterruptibly in a child scope, closing it on failure or
272 // interruption so acquired resources are returned instead of left on the caller.
273 const withChildScope = <A>(
274 f: (
275 scope: Scope.Closeable,
276 restore: <X, E, R>(effect: Effect.Effect<X, E, R>) => Effect.Effect<X, E, R>
277 ) => Effect.Effect<A, SqlError>
278 ): Effect.Effect<A, SqlError, Scope.Scope> =>
279 Effect.uninterruptibleMask((restore) =>
280 Effect.withFiber((fiber) => {
281 const scope = Scope.forkUnsafe(Context.getUnsafe(fiber.context, Scope.Scope))
282 return Effect.onError(f(scope, restore), (cause) => Scope.close(scope, Exit.failCause(cause)))
283 })
284 )
285​
286 // One checkout attempt (`undefined` if rejected). Closes the attempt scope
287 // before retrying so the rejected transport frees its slot first.
288 const attempt = withChildScope((scope, restore) =>
289 Effect.flatMap(restore(Scope.provide(Pool.get(pool), scope)), (connection) =>
290 expired(connection)
291 ? Effect.andThen(Pool.invalidate(pool, connection), Effect.as(Scope.close(scope, Exit.void), undefined))
292 : Effect.succeed(connection))
293 )
294​
295 const retry: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> = Effect.gen(function*() {
296 while (true) {
297 if (deadConnections.size > 0) {
298 const dead = Array.from(deadConnections)
299 deadConnections.clear()
300 yield* Effect.forEach(dead, (connection) => Pool.invalidate(pool, connection), { discard: true })
301 }
302 const connection = yield* attempt
303 if (connection !== undefined) return connection
304 }
305 })
306​
307 // Without a TTL, only dead sessions are rejected so the common path stays a
308 // plain flatMap. With a TTL, an expired session's transport may still be
309 // open, so every attempt leases into its own scope and a rejected lease is
310 // released before the next attempt.
311 const first: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> = connectionTTL !== undefined
312 ? Effect.flatMap(attempt, (connection) => connection === undefined ? retry : Effect.succeed(connection))
313 : Effect.flatMap(Pool.get(pool), (connection) =>
314 expired(connection)
315 ? Effect.andThen(Pool.invalidate(pool, connection), retry)
316 : Effect.succeed(connection))
317 const checkout: Effect.Effect<PgConnection.PgConnection, SqlError, Scope.Scope> = Effect.suspend(() =>
318 deadConnections.size > 0 ? retry : first
319 )
320​
321 const acquireTimedOut = () =>
322 Effect.fail(
323 new SqlError({
324 reason: new ConnectionError({
325 cause: new Error("Timed out waiting for a pooled connection"),
326 message: "PgPool: Timed out waiting for a pooled connection",
327 operation: "acquireConnection"
328 })
329 })
330 )
331​
332 const withAcquireTimeout = <A>(
333 effect: Effect.Effect<A, SqlError, Scope.Scope>
334 ): Effect.Effect<A, SqlError, Scope.Scope> =>
335 acquireTimeout === undefined ?
336 effect :
337 withChildScope((scope, restore) =>
338 restore(Effect.timeoutOrElse(Scope.provide(effect, scope), {
339 duration: acquireTimeout,
340 orElse: acquireTimedOut
341 }))
342 )
343​
344 const rejected: unique symbol = Symbol()
345 const handedOut = Effect.flatMap(checkout, handOut)
346 const get = withAcquireTimeout(handedOut)
347​
348 // `pin` reserves the pool item itself. On a multiplexed pool it also waits
349 // for shared statements to drain, so the acquire timeout covers it too.
350 const reserve = withAcquireTimeout(Effect.flatMap(handedOut, (connection) => connection.pin))
351​
352 // `Pool.use` cannot bound its wait, so it is used only when no acquire
353 // timeout applies and no connection awaits retirement.
354 const use = <A, E, R>(
355 f: (connection: PgConnection.PgConnection) => Effect.Effect<A, E, R>
356 ): Effect.Effect<A, E | SqlError, R> =>
357 Effect.suspend(() => {
358 if (acquireTimeout !== undefined || deadConnections.size > 0) return Effect.scoped(Effect.flatMap(get, f))
359 const run = (connection: PgConnection.PgConnection) =>
360 connects.has(connection) ? Effect.andThen(reportConnect(connection), f(connection)) : f(connection)
361 if (connectionTTL === undefined) return Pool.use(pool, run)
362 // An expired session is rejected inside the lease and replaced after it:
363 // requesting the replacement while holding the lease can deadlock a
364 // size-one pool. The callback keeps its own scope, as on the scoped path.
365 return Effect.flatMap(
366 Pool.use(pool, (connection): Effect.Effect<A | typeof rejected, E, R> =>
367 expired(connection)
368 ? Effect.as(Pool.invalidate(pool, connection), rejected)
369 : Effect.scoped(run(connection))),
370 (a): Effect.Effect<A, E | SqlError, R> =>
371 a === rejected ? Effect.scoped(Effect.flatMap(get, f)) : Effect.succeed(a)
372 )
373 })
374​
375 const pgPool: PgPool = {
376 [TypeId]: TypeId,
377 config: options,
378 get,
379 reserve,
380 use,
381 invalidate: (connection) =>
382 Pool.invalidate(pool, connectionInternals(connection).base as PgConnection.PgConnection),
383 stats: Pool.stats(pool)
384 }
385 return pgPool
386})