Skip to main content

postgres_mcp/pg/
session.rs

1//! Runs one statement on a pooled connection inside a READ ONLY transaction, then resets the session.
2// RunError holds DbError and WireError by value, which are large (fixed by the wire interface).
3#![allow(clippy::result_large_err)]
4
5use std::time::{Duration, Instant};
6
7use tokio_util::sync::CancellationToken;
8
9use crate::encode::TypeInfo;
10use crate::pg::pool::{Lease, Pool, PoolError};
11use crate::pg::wire::{
12    CancelHandle, Connection, DbError, FetchLimits, QueryResult, TxStatus, WireError,
13};
14use crate::typeinfo::TypeCache;
15
16/// Grace added to the server statement timeout before the client stops waiting for the query.
17const CLIENT_GRACE_MS: u64 = 5_000;
18/// Values the session check must see, in the column order of SESSION_CHECK.
19const SESSION_EXPECTED: [&str; 8] = [
20    "on", "ISO, MDY", "iso_8601", "UTC", "hex", "on", "UTF8", "true",
21];
22const SESSION_CHECK: &str = "SELECT pg_catalog.current_setting('transaction_read_only'), \
23    pg_catalog.current_setting('DateStyle'), pg_catalog.current_setting('IntervalStyle'), \
24    pg_catalog.current_setting('TimeZone'), pg_catalog.current_setting('bytea_output'), \
25    pg_catalog.current_setting('standard_conforming_strings'), \
26    pg_catalog.current_setting('client_encoding'), (current_user = session_user)::text";
27
28#[derive(Debug, Clone)]
29pub struct SessionSettings {
30    pub statement_timeout_ms: u64,
31    pub lock_timeout_ms: u64,
32    pub fetch: FetchLimits,
33    pub pool_wait: Duration,
34    /// Sets search_path to pg_catalog for the transaction; true for the server's own catalog SQL.
35    pub search_path_catalog_only: bool,
36}
37
38#[derive(Debug)]
39pub struct RunOutput {
40    pub result: QueryResult,
41    /// One per result column, same order.
42    pub types: Vec<TypeInfo>,
43    pub server_version_num: u32,
44    /// Time spent in the execute step only.
45    pub elapsed: Duration,
46}
47
48#[derive(Debug, thiserror::Error)]
49pub enum RunError {
50    #[error("{0}")]
51    Refused(String),
52    #[error("{}", .0.message)]
53    Db(DbError),
54    #[error("the query exceeded the {0} ms time limit and was cancelled")]
55    Timeout(u64),
56    #[error("the request was cancelled")]
57    Cancelled,
58    #[error("database unavailable: {0}")]
59    Unavailable(String),
60    #[error("internal error: {0}")]
61    Internal(String),
62}
63
64/// Why a run stopped. Keep means the connection is still in a known state and gets reset.
65enum Failure {
66    Keep(RunError),
67    Drop(RunError),
68    /// The session check hit an I/O error; a reused connection may just have gone stale.
69    Stale(RunError),
70}
71
72enum Race {
73    Cancelled,
74    Deadline,
75    Done(Result<QueryResult, WireError>),
76}
77
78/// What one session runs inside its read-only transaction.
79enum Body<'a> {
80    /// `user_sql` true: the server must report zero parameters. `params` are text-format values.
81    Bound {
82        sql: &'a str,
83        params: &'a [Option<&'a str>],
84        user_sql: bool,
85    },
86    /// An EXPLAIN text with no bind values; see `explain_unbound`.
87    Generic { sql: &'a str },
88}
89
90/// `user_sql` true: the server must report zero parameters. `params` are text-format values.
91pub async fn run_readonly(
92    pool: &Pool,
93    sql: &str,
94    params: &[Option<&str>],
95    user_sql: bool,
96    settings: &SessionSettings,
97    cancel: &CancellationToken,
98) -> Result<RunOutput, RunError> {
99    let body = Body::Bound {
100        sql,
101        params,
102        user_sql,
103    };
104    run_session(pool, body, settings, cancel).await
105}
106
107/// Runs an EXPLAIN GENERIC_PLAN text through the simple protocol behind a server-side preflight.
108/// Bind values would make PostgreSQL plan the value, so the text is sent with none.
109pub async fn run_readonly_explain_generic(
110    pool: &Pool,
111    sql: &str,
112    settings: &SessionSettings,
113    cancel: &CancellationToken,
114) -> Result<RunOutput, RunError> {
115    run_session(pool, Body::Generic { sql }, settings, cancel).await
116}
117
118/// Checkout, BEGIN READ ONLY with the session check, the body, then reset or close.
119async fn run_session(
120    pool: &Pool,
121    body: Body<'_>,
122    settings: &SessionSettings,
123    cancel: &CancellationToken,
124) -> Result<RunOutput, RunError> {
125    let mut lease = pool
126        .checkout(settings.pool_wait)
127        .await
128        .map_err(pool_failure)?;
129    let mut checked = verify_session(&mut lease, settings).await;
130    if matches!(checked, Err(Failure::Stale(_))) && lease.reused() {
131        drop(lease);
132        lease = pool
133            .checkout_fresh(settings.pool_wait)
134            .await
135            .map_err(pool_failure)?;
136        checked = verify_session(&mut lease, settings).await;
137    }
138    let outcome = match checked {
139        Ok(()) => run_held(lease.conn(), body, settings, cancel, pool.type_cache()).await,
140        Err(failure) => Err(failure),
141    };
142    match outcome {
143        Ok(output) => {
144            reset_and_release(lease).await;
145            Ok(output)
146        }
147        Err(Failure::Keep(e)) => {
148            reset_and_release(lease).await;
149            Err(e)
150        }
151        Err(Failure::Drop(e) | Failure::Stale(e)) => {
152            drop(lease);
153            Err(e)
154        }
155    }
156}
157
158/// BEGIN READ ONLY with the server-side time limits, as a statement list ending in a semicolon.
159fn begin_sql(settings: &SessionSettings, server_version_num: u32) -> String {
160    let st = settings.statement_timeout_ms;
161    let mut parts = vec![
162        "BEGIN READ ONLY".to_string(),
163        format!("SET LOCAL statement_timeout = {st}"),
164        format!("SET LOCAL lock_timeout = {}", settings.lock_timeout_ms),
165        format!(
166            "SET LOCAL idle_in_transaction_session_timeout = {}",
167            st.saturating_add(10_000)
168        ),
169    ];
170    if server_version_num >= 170_000 {
171        parts.push(format!(
172            "SET LOCAL transaction_timeout = {}",
173            st.saturating_add(5_000)
174        ));
175    }
176    if settings.search_path_catalog_only {
177        parts.push("SET LOCAL search_path = pg_catalog".to_string());
178    }
179    format!("{};", parts.join("; "))
180}
181
182/// Opens the read-only transaction and checks the session settings before anything else is sent.
183async fn verify_session(lease: &mut Lease<'_>, settings: &SessionSettings) -> Result<(), Failure> {
184    let conn = lease.conn();
185    let sql = format!(
186        "{} {SESSION_CHECK}",
187        begin_sql(settings, conn.server_version_num())
188    );
189    let result = match conn.simple_query(&sql).await {
190        Ok(result) => result,
191        Err(WireError::Io(e)) => return Err(Failure::Stale(RunError::Unavailable(e.to_string()))),
192        Err(e) => return Err(wire_failure(e)),
193    };
194    if result.status != TxStatus::InTransaction || !session_ok(&result.rows) {
195        let values = crate::scrub::scrub(&format!("{:?}", result.rows)).into_owned();
196        tracing::warn!(status = ?result.status, values = %values, "session check failed");
197        return Err(Failure::Drop(RunError::Internal(
198            "session check failed".into(),
199        )));
200    }
201    Ok(())
202}
203
204fn session_ok(rows: &[Vec<Option<String>>]) -> bool {
205    match rows {
206        [row] => {
207            row.len() == SESSION_EXPECTED.len()
208                && row
209                    .iter()
210                    .zip(SESSION_EXPECTED)
211                    .all(|(got, want)| got.as_deref() == Some(want))
212        }
213        _ => false,
214    }
215}
216
217/// Execute, type resolution. Runs inside the transaction opened by `verify_session`.
218async fn run_held(
219    conn: &mut Connection,
220    body: Body<'_>,
221    settings: &SessionSettings,
222    cancel: &CancellationToken,
223    types: &TypeCache,
224) -> Result<RunOutput, Failure> {
225    let cancel_handle = conn.cancel_handle();
226    let statement_ms = settings.statement_timeout_ms;
227    let deadline = Duration::from_millis(statement_ms.saturating_add(CLIENT_GRACE_MS));
228    let generic = matches!(body, Body::Generic { .. });
229    let started = Instant::now();
230    let race = tokio::select! {
231        biased;
232        _ = cancel.cancelled() => Race::Cancelled,
233        _ = tokio::time::sleep(deadline) => Race::Deadline,
234        r = fetch_rows(conn, body, settings) => Race::Done(r),
235    };
236    let elapsed = started.elapsed();
237    let result = match race {
238        Race::Done(Ok(result)) => result,
239        Race::Done(Err(e)) if conn.is_poisoned() => {
240            return Err(close_on(query_failure(e, statement_ms, elapsed)));
241        }
242        Race::Done(Err(e)) => return Err(query_failure(e, statement_ms, elapsed)),
243        Race::Cancelled => {
244            stop_query(&cancel_handle).await;
245            return Err(Failure::Drop(RunError::Cancelled));
246        }
247        Race::Deadline => {
248            stop_query(&cancel_handle).await;
249            return Err(Failure::Drop(RunError::Timeout(statement_ms)));
250        }
251    };
252    // The generic path has no truncation exception: its plan is never cut short.
253    if (generic || result.truncated.is_none()) && result.status != TxStatus::InTransaction {
254        return Err(Failure::Drop(RunError::Internal(
255            "unexpected transaction state".into(),
256        )));
257    }
258    if let Some(tag) = &result.command_tag
259        && !allowed_tag(tag)
260    {
261        return Err(Failure::Drop(RunError::Internal(
262            "unexpected command tag".into(),
263        )));
264    }
265    let oids: Vec<u32> = result.columns.iter().map(|c| c.type_oid).collect();
266    let types = resolve_types(conn, types, result.status, &oids, settings).await?;
267    Ok(RunOutput {
268        result,
269        types,
270        server_version_num: conn.server_version_num(),
271        elapsed,
272    })
273}
274
275async fn fetch_rows(
276    conn: &mut Connection,
277    body: Body<'_>,
278    settings: &SessionSettings,
279) -> Result<QueryResult, WireError> {
280    match body {
281        Body::Bound {
282            sql,
283            params,
284            user_sql,
285        } => conn.query(sql, params, user_sql, &settings.fetch).await,
286        Body::Generic { sql } => conn.explain_unbound(sql, settings.fetch.max_bytes).await,
287    }
288}
289
290/// The same failure, with the connection closed afterwards.
291fn close_on(failure: Failure) -> Failure {
292    match failure {
293        Failure::Keep(e) | Failure::Drop(e) | Failure::Stale(e) => Failure::Drop(e),
294    }
295}
296
297/// Command tags of the statements the gate lets run: `SELECT n`, `EXPLAIN` and `SHOW`.
298fn allowed_tag(tag: &str) -> bool {
299    match tag {
300        "EXPLAIN" | "SHOW" => true,
301        _ => tag
302            .strip_prefix("SELECT ")
303            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())),
304    }
305}
306
307/// Asks the server to cancel the running query. A failed cancel request is only logged.
308async fn stop_query(handle: &CancelHandle) {
309    if let Err(e) = handle.cancel().await {
310        tracing::debug!(error = %crate::scrub::scrub(&e.to_string()), "cancel request failed");
311    }
312}
313
314async fn resolve_types(
315    conn: &mut Connection,
316    types: &TypeCache,
317    status: TxStatus,
318    oids: &[u32],
319    settings: &SessionSettings,
320) -> Result<Vec<TypeInfo>, Failure> {
321    if status != TxStatus::InTransaction {
322        // A cancelled fetch aborted the transaction: end it, then open a new read-only one for the lookups.
323        simple_expect(conn, "ROLLBACK", TxStatus::Idle)
324            .await
325            .map_err(wire_failure)?;
326        let begin = begin_sql(settings, conn.server_version_num());
327        simple_expect(conn, &begin, TxStatus::InTransaction)
328            .await
329            .map_err(wire_failure)?;
330    }
331    types.resolve(conn, oids).await.map_err(wire_failure)
332}
333
334/// Runs one statement and requires the resulting transaction status.
335async fn simple_expect(
336    conn: &mut Connection,
337    sql: &str,
338    status: TxStatus,
339) -> Result<(), WireError> {
340    let result = conn.simple_query(sql).await?;
341    if result.status != status {
342        return Err(WireError::Protocol("unexpected transaction state".into()));
343    }
344    Ok(())
345}
346
347/// ROLLBACK, then DISCARD ALL, as two calls. The session must end idle.
348async fn reset(conn: &mut Connection) -> Result<(), WireError> {
349    simple_expect(conn, "ROLLBACK", TxStatus::Idle).await?;
350    simple_expect(conn, "DISCARD ALL", TxStatus::Idle).await
351}
352
353async fn reset_and_release(mut lease: Lease<'_>) {
354    match reset(lease.conn()).await {
355        Ok(()) => lease.release(true),
356        Err(e) => {
357            tracing::warn!(error = %crate::scrub::scrub(&e.to_string()), "session reset failed; closing the connection")
358        }
359    }
360}
361
362/// A 57014 is the statement limit when the run reached most of it, or when the server text says so. The text
363/// alone is not used: it is in the server's language. The client's own cancels never reach this function.
364fn query_failure(e: WireError, statement_ms: u64, elapsed: Duration) -> Failure {
365    match e {
366        WireError::Db(db)
367            if db.code == "57014"
368                && (db.message.contains("statement timeout")
369                    || reached_limit(elapsed, statement_ms)) =>
370        {
371            Failure::Keep(RunError::Timeout(statement_ms))
372        }
373        other => wire_failure(other),
374    }
375}
376
377/// True when `elapsed` is at least 90% of the statement limit.
378fn reached_limit(elapsed: Duration, statement_ms: u64) -> bool {
379    elapsed.as_millis() * 100 >= u128::from(statement_ms) * 90
380}
381
382/// Server-reported errors and refusals leave the connection resettable; anything else closes it.
383fn wire_failure(e: WireError) -> Failure {
384    match e {
385        WireError::Refused(m) => Failure::Keep(RunError::Refused(m)),
386        WireError::Db(db) => Failure::Keep(RunError::Db(db)),
387        WireError::Protocol(m) => Failure::Drop(RunError::Internal(m)),
388        other => Failure::Drop(RunError::Unavailable(other.to_string())),
389    }
390}
391
392fn pool_failure(e: PoolError) -> RunError {
393    match e {
394        PoolError::Busy => RunError::Unavailable("all connections are busy, retry shortly".into()),
395        PoolError::Closed => RunError::Unavailable("the pool is closed".into()),
396        PoolError::Connect(message) => RunError::Unavailable(message),
397    }
398}