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