Skip to main content

halephant_core/messages/
error.rs

1//! Error-response frame builders — two flavours:
2//!
3//! - [`send_fatal`] for `"FATAL"` errors where the connection is
4//!   closing anyway (auth rejection, upstream closed mid-transaction).
5//!   Errors during send are swallowed and logged — if we couldn't
6//!   push the error frame, the socket is already gone.
7//!
8//! - [`send_error`] for non-fatal `"ERROR"` rejections where the
9//!   client's session continues afterwards (read-write override on
10//!   a replica-routed transaction, rejected SQL statements). Follows
11//!   the error with `ReadyForQuery(status)` so the client knows the
12//!   session is still usable, and propagates send errors.
13
14use futures_util::SinkExt;
15use tokio::net::TcpStream;
16use tokio_util::codec::Framed;
17use tracing::warn;
18
19use crate::proto::backend::{BackendMessage, NoticeFields};
20use crate::proto::codec::FrontendCodec;
21use crate::proto::types::TransactionStatus;
22
23/// Send a FATAL `ErrorResponse` frame. Used when the connection is
24/// closing anyway — the caller typically bails immediately after.
25///
26/// Errors during send are logged but not propagated: if we couldn't
27/// deliver the error frame, the socket is already gone and there's
28/// nothing useful the caller could do with a send error.
29pub async fn send_fatal(
30    client: &mut Framed<TcpStream, FrontendCodec>,
31    sqlstate: &str,
32    message: &str,
33) {
34    let frame = BackendMessage::ErrorResponse(NoticeFields {
35        fields: vec![
36            (b'S', "FATAL".into()),
37            (b'C', sqlstate.into()),
38            (b'M', message.into()),
39        ],
40    });
41    if let Err(e) = client.send(frame).await {
42        warn!(%e, sqlstate, "failed to send FATAL error response to client");
43    }
44}
45
46/// Send a non-fatal `ErrorResponse` frame followed by
47/// `ReadyForQuery(status)` so the client can continue the session
48/// after the error. Used for in-session rejections like read-write
49/// override attempts on a replica-routed transaction.
50///
51/// The `status` parameter **must** reflect the actual session state
52/// at the call site — same rule as
53/// [`super::synthetic::send_synthetic_ok`].
54pub async fn send_error(
55    client: &mut Framed<TcpStream, FrontendCodec>,
56    sqlstate: &str,
57    message: &str,
58    status: TransactionStatus,
59) -> anyhow::Result<()> {
60    client
61        .feed(BackendMessage::ErrorResponse(NoticeFields {
62            fields: vec![
63                (b'S', "ERROR".into()),
64                (b'C', sqlstate.into()),
65                (b'M', message.into()),
66            ],
67        }))
68        .await?;
69    client.send(BackendMessage::ReadyForQuery(status)).await?;
70    Ok(())
71}