Skip to main content

halephant_core/proxy/
session.rs

1use std::sync::Arc;
2
3use futures_util::{SinkExt, StreamExt};
4use tokio::net::TcpStream;
5use tokio_util::codec::Framed;
6use tracing::trace;
7
8use crate::connections::server::{Reply, ServerConn};
9use crate::pool::PoolManager;
10use crate::proto::backend::BackendMessage;
11use crate::proto::codec::FrontendCodec;
12use crate::proto::frontend::FrontendMessage;
13use crate::proto::types::TransactionStatus;
14use crate::proxy::intercept::{handle_close_intercept, handle_deallocate_intercept};
15use crate::proxy::prepared::{ClientPrepared, PreparedGuard, rewrite_outbound};
16
17/// Forward messages between client and server for the lifetime of the session.
18///
19/// `Terminate` from the client is intercepted so the server connection can be
20/// returned to the pool rather than closed.
21///
22/// One client owns the backend for the whole session, but the backend is
23/// reused by later sessions, so prepared statements still flow through
24/// halephant's canonical-name rewriting. Forwarding client-chosen names (such
25/// as psycopg3's `_pg3_0`, which restarts at 0 on every new connection)
26/// verbatim would collide with a name a previous session left prepared on that
27/// backend and draw `42P05 duplicate_prepared_statement`. Rewriting every
28/// `Parse` to `SHA-256(query, param_oids)` makes the backend see only
29/// collision-free hashes; the per-backend cache that records them persists
30/// across sessions, while the per-client name map is dropped on disconnect.
31pub async fn forward(
32    client: &mut Framed<TcpStream, FrontendCodec>,
33    server: &mut ServerConn,
34    pools: &Arc<PoolManager>,
35) -> anyhow::Result<()> {
36    // Drop guard releases the session's statement-store references even
37    // if the client task is cancelled mid-forward.
38    let mut client_prepared = PreparedGuard {
39        inner: ClientPrepared::new(),
40        pools: Arc::clone(pools),
41    };
42    forward_loop(client, server, pools, &mut client_prepared.inner).await
43}
44
45async fn forward_loop(
46    client: &mut Framed<TcpStream, FrontendCodec>,
47    server: &mut ServerConn,
48    pools: &Arc<PoolManager>,
49    client_prepared: &mut ClientPrepared,
50) -> anyhow::Result<()> {
51    // The per-backend prepared cache persists across sessions, but the
52    // reply bookkeeping must start clean for this session.
53    server.statements.reset_pending();
54    // Track the latest backend transaction status so intercepted
55    // messages (DEALLOCATE) can synthesize an accurate ReadyForQuery.
56    let mut last_status = TransactionStatus::Idle;
57
58    loop {
59        tokio::select! {
60            msg = client.next() => match msg.transpose()? {
61                Some(FrontendMessage::Terminate) => {
62                    trace!("client sent Terminate");
63                    return Ok(());
64                }
65                Some(msg) => {
66                    // Absorb statement Close: drop the per-client mapping
67                    // but never forward to the backend — the canonical may
68                    // still be needed by another session.
69                    if let Some(true) =
70                        handle_close_intercept(&msg, client_prepared, client, pools).await?
71                    {
72                        continue;
73                    }
74                    // Absorb DEALLOCATE for the same reason: the backend
75                    // only knows canonical names, never the client's.
76                    if let Some(true) = handle_deallocate_intercept(
77                        &msg,
78                        client_prepared,
79                        client,
80                        pools,
81                        last_status,
82                    )
83                    .await?
84                    {
85                        continue;
86                    }
87                    // Rewrite prepared-statement names to canonicals (and
88                    // re-Parse on cache miss) before forwarding.
89                    if let Some(msg) =
90                        rewrite_outbound(msg, client_prepared, server, pools, client).await?
91                    {
92                        trace!(?msg, "client -> server");
93                        server.framed.send(msg).await?;
94                    }
95                }
96                None => return Ok(()),
97            },
98            msg = server.framed.next() => match msg.transpose()? {
99                // Filter out completions that answer Parse/Close messages
100                // halephant injected on the client's behalf — same rules as
101                // transaction mode, driven by the per-connection FIFO.
102                Some(BackendMessage::ParseComplete) => match server.statements.next_parse_reply() {
103                    Reply::Suppress => trace!("suppressing injected ParseComplete"),
104                    Reply::Forward => client.send(BackendMessage::ParseComplete).await?,
105                },
106                Some(BackendMessage::CloseComplete) => match server.statements.next_close_reply() {
107                    Reply::Suppress => trace!("suppressing injected CloseComplete"),
108                    Reply::Forward => client.send(BackendMessage::CloseComplete).await?,
109                },
110                Some(BackendMessage::ReadyForQuery(status)) => {
111                    last_status = status;
112                    server.last_tx_status = status;
113                    client.send(BackendMessage::ReadyForQuery(status)).await?;
114                }
115                Some(BackendMessage::ErrorResponse(ref err)) => {
116                    // Roll back optimistic prepared-statement inserts the
117                    // aborted batch will never confirm — essential here
118                    // because session mode reuses one backend for the whole
119                    // session with no per-transaction checkout to reset it.
120                    server.statements.roll_back_after_error();
121                    client
122                        .send(BackendMessage::ErrorResponse(err.clone()))
123                        .await?;
124                }
125                Some(msg) => {
126                    trace!(?msg, "server -> client");
127                    client.send(msg).await?;
128                }
129                None => anyhow::bail!("upstream server closed unexpectedly"),
130            },
131        }
132    }
133}