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 `Some(true)`) or defers it to
4//! the normal forwarding path (returns `None`).
5
6use std::sync::Arc;
7
8use futures_util::SinkExt;
9use tokio::net::TcpStream;
10use tokio_util::codec::Framed;
11use tracing::debug;
12
13use crate::listener::ClientNotifications;
14use crate::pool::PoolManager;
15use crate::proto;
16use crate::proxy::prepared::ClientPrepared;
17use crate::sql;
18
19/// Intercept Close messages for named statements. Returns:
20/// - `Some(true)` — intercepted, synthetic CloseComplete sent to client
21/// - `None` — not a statement Close, caller should forward normally
22pub(super) async fn handle_close_intercept(
23    msg: &proto::frontend::FrontendMessage,
24    client_prepared: &mut ClientPrepared,
25    client: &mut Framed<TcpStream, proto::codec::FrontendCodec>,
26    pools: &Arc<PoolManager>,
27) -> anyhow::Result<Option<bool>> {
28    if let proto::frontend::FrontendMessage::Close(close) = msg
29        && close.kind == proto::frontend::TargetKind::Statement
30    {
31        {
32            let mut store = pools.stmt_store.lock();
33            client_prepared.remove(&close.name, &mut store);
34        }
35        client
36            .send(proto::backend::BackendMessage::CloseComplete)
37            .await?;
38        return Ok(Some(true));
39    }
40    Ok(None)
41}
42
43/// Intercept `DEALLOCATE name` and `DEALLOCATE ALL` queries in the
44/// simple query protocol. Returns:
45/// - `Some(true)` — intercepted, synthetic `CommandComplete` +
46///   `ReadyForQuery` sent to the client
47/// - `None` — not a DEALLOCATE, caller should forward normally
48pub(super) async fn handle_deallocate_intercept(
49    msg: &proto::frontend::FrontendMessage,
50    client_prepared: &mut ClientPrepared,
51    client: &mut Framed<TcpStream, proto::codec::FrontendCodec>,
52    pools: &Arc<PoolManager>,
53    status: proto::types::TransactionStatus,
54) -> anyhow::Result<Option<bool>> {
55    let proto::frontend::FrontendMessage::Query(query) = msg else {
56        return Ok(None);
57    };
58
59    let sql::Statement::Deallocate { target } = sql::parse(query) else {
60        return Ok(None);
61    };
62
63    match target {
64        sql::DeallocateTarget::Name(name) => {
65            debug!(%name, "intercepting DEALLOCATE for named statement");
66            let mut store = pools.stmt_store.lock();
67            // `remove` is a no-op if the name isn't tracked — the
68            // client's DEALLOCATE for an unknown name would error on
69            // the server, but since we can't forward (no canonical
70            // mapping), we still send the success response. The
71            // alternative — synthesising a server error — isn't
72            // worth the added complexity since clients that
73            // DEALLOCATE unknown statements are almost always bugs.
74            client_prepared.remove(&name, &mut store);
75        }
76        sql::DeallocateTarget::All => {
77            debug!("intercepting DEALLOCATE ALL, releasing all client prepared statements");
78            let mut store = pools.stmt_store.lock();
79            client_prepared.release_all(&mut store);
80        }
81    }
82
83    crate::messages::synthetic::send_synthetic_ok(client, "DEALLOCATE", status).await?;
84    Ok(Some(true))
85}
86
87/// If the message is a LISTEN/UNLISTEN and we're in multiplex mode, handle it
88/// locally (update subscriptions, send synthetic response). Returns:
89/// - `Some(true)` if the message was intercepted (caller should continue/skip)
90/// - `Some(false)` or `None` if the message should be forwarded normally
91pub(super) async fn handle_listen_intercept(
92    msg: &proto::frontend::FrontendMessage,
93    notifications: &mut Option<ClientNotifications>,
94    client: &mut Framed<TcpStream, proto::codec::FrontendCodec>,
95    status: proto::types::TransactionStatus,
96) -> anyhow::Result<Option<bool>> {
97    let proto::frontend::FrontendMessage::Query(query) = msg else {
98        return Ok(None);
99    };
100
101    match sql::parse(query) {
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(Some(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(Some(true));
124            }
125        }
126        _ => {}
127    }
128
129    Ok(None)
130}