Skip to main content

halephant_core/proxy/
intercept.rs

1//! Message interceptors that produce synthetic client-facing
2//! responses without involving the upstream server. Each handler
3//! either consumes the message (returns `true`) or defers it to the
4//! normal forwarding path (returns `false`).
5//!
6//! The SQL-driven handlers take the caller's one-per-message
7//! [`sql::Statement`] classification instead of re-parsing the
8//! message. Callers only offer statements from simple-protocol
9//! `Query` messages for interception: a `Parse`-carried statement is
10//! being prepared, not executed, and a synthetic simple-query
11//! response would desynchronize the extended-protocol reply stream.
12
13use std::sync::Arc;
14
15use futures_util::SinkExt;
16use tokio::net::TcpStream;
17use tokio_util::codec::Framed;
18use tracing::debug;
19
20use crate::listener::ClientNotifications;
21use crate::pool::PoolManager;
22use crate::proto;
23use crate::proxy::prepared::ClientPrepared;
24use crate::sql;
25
26/// Intercept Close messages for named statements. Returns `true` when
27/// the Close was absorbed and a synthetic CloseComplete was sent to
28/// the client; `false` when the caller should forward normally.
29pub(super) async fn handle_close_intercept(
30    msg: &proto::frontend::FrontendMessage,
31    client_prepared: &mut ClientPrepared,
32    client: &mut Framed<TcpStream, proto::codec::FrontendCodec>,
33    pools: &Arc<PoolManager>,
34) -> anyhow::Result<bool> {
35    if let proto::frontend::FrontendMessage::Close(close) = msg
36        && close.kind == proto::frontend::TargetKind::Statement
37    {
38        {
39            let mut store = pools.stmt_store.lock();
40            client_prepared.remove(&close.name, &mut store);
41        }
42        client
43            .send(proto::backend::BackendMessage::CloseComplete)
44            .await?;
45        return Ok(true);
46    }
47    Ok(false)
48}
49
50/// Intercept `DEALLOCATE name` and `DEALLOCATE ALL` statements in the
51/// simple query protocol. Returns `true` when the statement was
52/// absorbed and a synthetic `CommandComplete` + `ReadyForQuery` was
53/// sent to the client; `false` when the caller should forward
54/// normally.
55pub(super) async fn handle_deallocate_intercept(
56    stmt: &sql::Statement,
57    client_prepared: &mut ClientPrepared,
58    client: &mut Framed<TcpStream, proto::codec::FrontendCodec>,
59    pools: &Arc<PoolManager>,
60    status: proto::types::TransactionStatus,
61) -> anyhow::Result<bool> {
62    let sql::Statement::Deallocate { target } = stmt else {
63        return Ok(false);
64    };
65
66    match target {
67        sql::DeallocateTarget::Name(name) => {
68            debug!(%name, "intercepting DEALLOCATE for named statement");
69            let mut store = pools.stmt_store.lock();
70            // `remove` is a no-op if the name isn't tracked — the
71            // client's DEALLOCATE for an unknown name would error on
72            // the server, but since we can't forward (no canonical
73            // mapping), we still send the success response. The
74            // alternative — synthesising a server error — isn't
75            // worth the added complexity since clients that
76            // DEALLOCATE unknown statements are almost always bugs.
77            client_prepared.remove(name, &mut store);
78        }
79        sql::DeallocateTarget::All => {
80            debug!("intercepting DEALLOCATE ALL, releasing all client prepared statements");
81            let mut store = pools.stmt_store.lock();
82            client_prepared.release_all(&mut store);
83        }
84    }
85
86    crate::messages::synthetic::send_synthetic_ok(client, "DEALLOCATE", status).await?;
87    Ok(true)
88}
89
90/// Intercept LISTEN/UNLISTEN statements when multiplexing is active
91/// for this client (update subscriptions, send synthetic response).
92/// Returns `true` when the statement was absorbed; `false` when the
93/// caller should forward normally (including when no subscription
94/// exists to multiplex onto).
95pub(super) async fn handle_listen_intercept(
96    stmt: &sql::Statement,
97    notifications: &mut Option<ClientNotifications>,
98    client: &mut Framed<TcpStream, proto::codec::FrontendCodec>,
99    status: proto::types::TransactionStatus,
100) -> anyhow::Result<bool> {
101    match stmt {
102        sql::Statement::Listen { channel } => {
103            if let Some(notifs) = notifications.as_mut() {
104                debug!(%channel, "multiplex: subscribing client to channel");
105                notifs.listen(channel);
106                crate::messages::synthetic::send_synthetic_ok(client, "LISTEN", status).await?;
107                return Ok(true);
108            }
109        }
110        sql::Statement::Unlisten { target } => {
111            if let Some(notifs) = notifications.as_mut() {
112                match target {
113                    sql::UnlistenTarget::Star => {
114                        debug!("multiplex: unsubscribing client from all channels");
115                        notifs.unlisten_all();
116                    }
117                    sql::UnlistenTarget::Channel(channel) => {
118                        debug!(%channel, "multiplex: unsubscribing client from channel");
119                        notifs.unlisten(channel);
120                    }
121                }
122                crate::messages::synthetic::send_synthetic_ok(client, "UNLISTEN", status).await?;
123                return Ok(true);
124            }
125        }
126        _ => {}
127    }
128
129    Ok(false)
130}