1"""Where `DatabaseConnection` gets its psycopg connection — direct per-use
2(`DirectSource`) or checkout/return against a shared pool (`PoolSource`).
3The wrapper calls `source.acquire()` / `source.release()` / `source.config`
4and is otherwise source-agnostic."""
5
6import threading
7import time
8from abc import ABC, abstractmethod
9from typing import TYPE_CHECKING, Any
10
11import psycopg
12from plain.exceptions import ImproperlyConfigured
13from plain.logs import get_framework_logger
14from plain.postgres.adapters import get_adapters_template
15from plain.postgres.database_url import DatabaseConfig, parse_database_url
16from plain.postgres.dialect import MAX_NAME_LENGTH
17from plain.postgres.otel import (
18 record_connection_acquire,
19 record_connection_release,
20 record_connection_timeout,
21)
22from plain.runtime import settings as plain_settings
23from psycopg_pool import ConnectionPool, PoolTimeout
24
25logger = get_framework_logger()
26
27if TYPE_CHECKING:
28 from psycopg import Connection as PsycopgConnection
29
30
31def build_connection_params(config: DatabaseConfig) -> dict[str, Any]:
32 """Return kwargs suitable for `psycopg.connect()` from a `DatabaseConfig`.
33
34 Every psycopg connection Plain opens — pooled or direct — goes through
35 this function so they all share the same adapters, cursor factory, and
36 validation rules.
37 """
38 options = config.get("OPTIONS", {})
39 db_name = config["DATABASE"]
40 if len(db_name) > MAX_NAME_LENGTH:
41 raise ImproperlyConfigured(
42 f"The database name {db_name!r} ({len(db_name)} characters) is longer "
43 f"than PostgreSQL's limit of {MAX_NAME_LENGTH} characters. Supply a "
44 "shorter database name in POSTGRES_URL."
45 )
46 conn_params: dict[str, Any] = {"dbname": db_name, **options}
47 if config.get("USER"):
48 conn_params["user"] = config["USER"]
49 if config.get("PASSWORD"):
50 conn_params["password"] = config["PASSWORD"]
51 if config.get("HOST"):
52 conn_params["host"] = config["HOST"]
53 if config.get("PORT"):
54 conn_params["port"] = config["PORT"]
55 conn_params["context"] = get_adapters_template()
56 # ClientCursor does client-side parameter binding and issues no
57 # server-side prepared statements — safe behind transaction-mode
58 # poolers like pgbouncer.
59 conn_params["cursor_factory"] = psycopg.ClientCursor
60 conn_params["prepare_threshold"] = conn_params.pop("prepare_threshold", None)
61 return conn_params
62
63
64class ConnectionSource(ABC):
65 @property
66 @abstractmethod
67 def config(self) -> DatabaseConfig:
68 """What server this source connects to. Read by otel, psql helper, maintenance."""
69
70 @abstractmethod
71 def acquire(self) -> PsycopgConnection[Any]: ...
72
73 @abstractmethod
74 def release(self, conn: PsycopgConnection[Any]) -> None: ...
75
76
77class DirectSource(ConnectionSource):
78 """Opens a fresh psycopg connection per acquire; closes on release."""
79
80 def __init__(self, config: DatabaseConfig):
81 self._config = config
82 self._params = build_connection_params(config)
83
84 @property
85 def config(self) -> DatabaseConfig:
86 return self._config
87
88 def acquire(self) -> PsycopgConnection[Any]:
89 return psycopg.connect(**self._params)
90
91 def release(self, conn: PsycopgConnection[Any]) -> None:
92 conn.close()
93
94
95class PoolSource(ConnectionSource):
96 """Lazily-opened `psycopg_pool.ConnectionPool`. `close()` drops the pool
97 so the next acquire rebuilds against current settings.
98
99 The `name` is used as the `db.client.connection.pool.name` attribute on
100 the `db.client.connection.*` OpenTelemetry metric family.
101 """
102
103 def __init__(self, name: str = "runtime") -> None:
104 self.name = name
105 self._pool: ConnectionPool | None = None
106 self._config: DatabaseConfig | None = None
107 self._lock = threading.Lock()
108
109 @property
110 def config(self) -> DatabaseConfig:
111 if self._config is None:
112 # Opening the pool populates _config as a side effect; until then,
113 # parse lazily so callers that only need config (otel on a no-op
114 # request) don't force the pool open.
115 self._config = _parse_runtime_url()
116 return self._config
117
118 def acquire(self) -> PsycopgConnection[Any]:
119 pool = self._get_pool()
120 start = time.perf_counter()
121 try:
122 conn = pool.getconn()
123 except PoolTimeout:
124 record_connection_timeout(self.name)
125 raise
126 checkout_time = time.perf_counter()
127 record_connection_acquire(self.name, conn, checkout_time - start, checkout_time)
128 return conn
129
130 def release(self, conn: PsycopgConnection[Any]) -> None:
131 record_connection_release(self.name, conn, time.perf_counter())
132 pool = self._pool
133 if pool is None:
134 conn.close()
135 return
136 try:
137 pool.putconn(conn)
138 except Exception:
139 logger.debug("Error returning connection to pool", exc_info=True)
140 conn.close()
141
142 def get_stats(self) -> dict[str, int] | None:
143 """Return pool statistics, or None if the pool is closed."""
144 pool = self._pool
145 if pool is None:
146 return None
147 try:
148 return pool.get_stats()
149 except Exception:
150 return None
151
152 def close(self, timeout: float = 5.0) -> None:
153 with self._lock:
154 self._config = None
155 if self._pool is not None:
156 try:
157 self._pool.close(timeout=timeout)
158 finally:
159 self._pool = None
160
161 def _get_pool(self) -> ConnectionPool:
162 if self._pool is None:
163 with self._lock:
164 if self._pool is None:
165 self._pool = self._open_pool()
166 return self._pool
167
168 def _open_pool(self) -> ConnectionPool:
169 self._config = _parse_runtime_url()
170 params = build_connection_params(self._config)
171 pool = ConnectionPool(
172 kwargs=params,
173 open=False,
174 reset=_reset_pooled_connection,
175 # Validate each connection on checkout. One closed server-side
176 # while idle in the pool (server or pooler idle timeout) is
177 # discarded and replaced rather than handed out dead.
178 check=ConnectionPool.check_connection,
179 min_size=plain_settings.POSTGRES_POOL_MIN_SIZE,
180 max_size=plain_settings.POSTGRES_POOL_MAX_SIZE,
181 max_lifetime=plain_settings.POSTGRES_POOL_MAX_LIFETIME,
182 timeout=plain_settings.POSTGRES_POOL_TIMEOUT,
183 )
184 pool.open(wait=False)
185 return pool
186
187
188def _parse_runtime_url() -> DatabaseConfig:
189 """Validate `POSTGRES_URL` and return its parsed config.
190
191 Raises `ImproperlyConfigured` with a friendly message when the URL is
192 empty or explicitly disabled, so callers that only need the config (like
193 `plain postgres shell`) don't fall through to a raw `ValueError`.
194 """
195 url = str(plain_settings.POSTGRES_URL)
196 if not url:
197 raise ImproperlyConfigured(
198 "PostgreSQL database is not configured. Set PLAIN_POSTGRES_URL, or "
199 "POSTGRES_URL in settings, to a postgres://... connection string."
200 )
201 if url.lower() == "none":
202 raise ImproperlyConfigured(
203 "The PostgreSQL database has been disabled (POSTGRES_URL=none). "
204 "No database operations are available in this context."
205 )
206 return parse_database_url(url)
207
208
209def _reset_pooled_connection(conn: PsycopgConnection[Any]) -> None:
210 """Ensure a connection is clean before returning to the pool.
211
212 Rolls back any in-progress transaction and restores autocommit=True so
213 the next checkout starts in a known state. Raising here signals the pool
214 to discard the connection.
215 """
216 if not conn.autocommit:
217 conn.rollback()
218 conn.autocommit = True
219
220
221# Process-wide singleton. Pool is lazy-opened on first acquire.
222runtime_pool_source = PoolSource(name="runtime")