Skip to main content

halephant_core/proto/
codec.rs

1use bytes::BytesMut;
2use tokio_util::codec::{Decoder, Encoder};
3
4use crate::errors;
5use crate::proto::backend::BackendMessage;
6use crate::proto::frontend::FrontendMessage;
7
8// ---------------------------------------------------------------------------
9// FrontendCodec — client-facing side of the proxy
10//
11// Decodes FrontendMessage (client → proxy)
12// Encodes BackendMessage (proxy → client)
13// ---------------------------------------------------------------------------
14
15/// Codec for the client-facing half of a proxied connection.
16pub struct FrontendCodec {
17    /// `true` while we are expecting initial messages (startup / SSL / cancel)
18    /// that lack a type byte. Switches to `false` after a `StartupMessage`.
19    startup: bool,
20}
21
22impl FrontendCodec {
23    pub fn new() -> Self {
24        Self { startup: true }
25    }
26
27    /// Creates a codec that skips startup message parsing. Use this for
28    /// connections that have already completed the startup handshake.
29    pub fn post_startup() -> Self {
30        Self { startup: false }
31    }
32}
33
34impl Default for FrontendCodec {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl Decoder for FrontendCodec {
41    type Item = FrontendMessage;
42    type Error = errors::ProtocolError;
43
44    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
45        if self.startup {
46            decode_initial(src)
47        } else {
48            decode_regular(src, FrontendMessage::parse)
49        }
50        .map(|opt| {
51            if let Some(ref msg) = opt {
52                match msg {
53                    // SSLRequest / GssEncRequest: stay in startup mode — the
54                    // real StartupMessage follows after the proxy responds.
55                    // CancelRequest is a one-shot message on a throwaway
56                    // connection, but keep startup mode just in case.
57                    FrontendMessage::SslRequest
58                    | FrontendMessage::GssEncRequest
59                    | FrontendMessage::CancelRequest { .. } => {}
60                    // Any other initial message (StartupMessage) transitions
61                    // to regular message framing.
62                    _ => self.startup = false,
63                }
64            }
65            opt
66        })
67    }
68}
69
70impl Encoder<BackendMessage> for FrontendCodec {
71    type Error = errors::ProtocolError;
72
73    fn encode(&mut self, item: BackendMessage, dst: &mut BytesMut) -> Result<(), Self::Error> {
74        item.encode(dst);
75        Ok(())
76    }
77}
78
79// ---------------------------------------------------------------------------
80// BackendCodec — server-facing side of the proxy
81//
82// Decodes BackendMessage (server → proxy)
83// Encodes FrontendMessage (proxy → server)
84// ---------------------------------------------------------------------------
85
86/// Codec for the server-facing half of a proxied connection.
87pub struct BackendCodec;
88
89impl BackendCodec {
90    pub fn new() -> Self {
91        Self
92    }
93}
94
95impl Default for BackendCodec {
96    fn default() -> Self {
97        Self::new()
98    }
99}
100
101impl Decoder for BackendCodec {
102    type Item = BackendMessage;
103    type Error = errors::ProtocolError;
104
105    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
106        decode_regular(src, BackendMessage::parse)
107    }
108}
109
110impl Encoder<FrontendMessage> for BackendCodec {
111    type Error = errors::ProtocolError;
112
113    fn encode(&mut self, item: FrontendMessage, dst: &mut BytesMut) -> Result<(), Self::Error> {
114        item.encode(dst);
115        Ok(())
116    }
117}
118
119// ---------------------------------------------------------------------------
120// Shared framing helpers
121// ---------------------------------------------------------------------------
122
123/// Decode an initial message (no type byte): `[length: i32] [payload]`.
124fn decode_initial(src: &mut BytesMut) -> Result<Option<FrontendMessage>, errors::ProtocolError> {
125    if src.len() < 4 {
126        return Ok(None);
127    }
128    let length = u32::from_be_bytes([src[0], src[1], src[2], src[3]]) as usize;
129    if length < 4 {
130        return Err(errors::ProtocolError::InvalidValue {
131            position: 0,
132            message: format!("initial message length too small: {length}"),
133        });
134    }
135    if src.len() < length {
136        // Not enough data yet — wait for more.
137        return Ok(None);
138    }
139    let frame = src.split_to(length);
140    FrontendMessage::parse_initial(&frame).map(Some)
141}
142
143/// Decode a regular message: `[type: u8] [length: i32] [payload]`.
144///
145/// The `parse` callback receives `(type_byte, payload_slice)`.
146fn decode_regular<M>(
147    src: &mut BytesMut,
148    parse: impl FnOnce(u8, &[u8]) -> Result<M, errors::ProtocolError>,
149) -> Result<Option<M>, errors::ProtocolError> {
150    if src.len() < 5 {
151        return Ok(None);
152    }
153    let msg_type = src[0];
154    let length = u32::from_be_bytes([src[1], src[2], src[3], src[4]]) as usize;
155    if length < 4 {
156        return Err(errors::ProtocolError::InvalidValue {
157            position: 1,
158            message: format!("message length too small: {length}"),
159        });
160    }
161    let total = 1 + length; // type byte + length value (which includes its own 4 bytes)
162    if src.len() < total {
163        return Ok(None);
164    }
165    let frame = src.split_to(total);
166    let payload = &frame[5..]; // skip type (1) + length (4)
167    parse(msg_type, payload).map(Some)
168}