Skip to main content

postgres_mcp/encode/
mod.rs

1//! Decodes PostgreSQL TEXT-format values into JSON, lossless or capped.
2
3mod array;
4mod columns;
5mod json;
6mod range;
7mod types;
8
9use std::borrow::Cow;
10
11use serde_json::Value;
12
13use crate::scrub;
14
15pub use columns::dedup_columns;
16pub use types::{TypeInfo, TypeKind, builtin_type};
17
18/// Size caps for one encoded value.
19#[derive(Debug, Clone, Copy)]
20pub struct EncodeLimits {
21    pub max_value_bytes: usize,
22    pub max_binary_preview_bytes: usize,
23}
24
25/// Counters for values that were cut or fell back to raw text.
26#[derive(Debug, Default, Clone, PartialEq, Eq)]
27pub struct EncodeStats {
28    pub truncated_values: u64,
29    pub raw_fallbacks: u64,
30}
31
32/// The text that starts the marker after a cut value; the masks strip it by this same constant.
33pub const TRUNCATION_MARK: &str = "…[truncated: ";
34const MAX_SAFE_INTEGER: u128 = 9_007_199_254_740_991;
35
36/// Encodes one non-NULL value. `raw` may be a prefix of the value; `full_len` is its real length.
37/// Password hashes in the kept bytes are replaced before the value is decoded or cut again.
38pub fn encode_value(
39    raw: &[u8],
40    full_len: usize,
41    ty: &TypeInfo,
42    limits: &EncodeLimits,
43    stats: &mut EncodeStats,
44) -> Value {
45    let complete = full_len <= raw.len();
46    if let (false, TypeKind::Bytea, Some(hex_text)) = (complete, &ty.kind, raw.strip_prefix(b"\\x"))
47    {
48        return wire_truncated_bytea(hex_text, full_len, limits, stats);
49    }
50    let (raw, _) = scrub_raw(raw, ty);
51    if !complete {
52        // The cut may split an md5 hash, in text or inside a hex run; the fragment is replaced here.
53        let (hex_tail, _) = scrub::scrub_hex_tail(&raw);
54        let (tail, _) = scrub::scrub_cut_tail(&hex_tail);
55        let keep = scrub::cut_index(&tail, limits.max_value_bytes);
56        return wire_truncated(&tail[..keep], full_len, stats);
57    }
58    let Ok(text) = std::str::from_utf8(&raw) else {
59        stats.raw_fallbacks += 1;
60        return hex_capped(&raw, limits, stats);
61    };
62    match decode(text, ty, limits, stats) {
63        Some(value) => value,
64        None => {
65            stats.raw_fallbacks += 1;
66            text_value(text, limits, stats)
67        }
68    }
69}
70
71/// Decodes valid UTF-8 text by kind; None means the text did not parse.
72fn decode(
73    text: &str,
74    ty: &TypeInfo,
75    limits: &EncodeLimits,
76    stats: &mut EncodeStats,
77) -> Option<Value> {
78    match &ty.kind {
79        TypeKind::Bool => match text {
80            "t" => Some(Value::Bool(true)),
81            "f" => Some(Value::Bool(false)),
82            _ => None,
83        },
84        TypeKind::Int => text.parse::<i64>().ok().map(Value::from),
85        TypeKind::BigInt => {
86            let v: i128 = text.parse().ok()?;
87            if v.unsigned_abs() <= MAX_SAFE_INTEGER {
88                Some(Value::from(i64::try_from(v).ok()?))
89            } else {
90                Some(text_value(text, limits, stats))
91            }
92        }
93        TypeKind::Float => float(text, limits, stats),
94        TypeKind::Numeric | TypeKind::Text => Some(text_value(text, limits, stats)),
95        TypeKind::Json => json::decode(text, limits, stats),
96        TypeKind::Bytea => bytea(text, limits, stats),
97        TypeKind::Array { elem, delim } => array::decode(text, elem, *delim, limits, stats),
98        TypeKind::Range { sub } => range::decode(text, sub, limits, stats),
99        TypeKind::Multirange { sub } => range::decode_multirange(text, sub, limits, stats),
100    }
101}
102
103fn float(text: &str, limits: &EncodeLimits, stats: &mut EncodeStats) -> Option<Value> {
104    match text {
105        "NaN" | "Infinity" | "-Infinity" => Some(text_value(text, limits, stats)),
106        _ => {
107            let f: f64 = text.parse().ok()?;
108            if !f.is_finite() {
109                return None;
110            }
111            match serde_json::from_str::<Value>(text) {
112                Ok(v @ Value::Number(_)) => Some(v),
113                _ => None,
114            }
115        }
116    }
117}
118
119/// A bytea value cut by the wire. Its kept bytes are scrubbed and cut again, so an md5 hash that straddles
120/// the cut is replaced in the bytes it is made of. The result stays hex, so the marker reads as hex bytes.
121fn wire_truncated_bytea(
122    hex_text: &[u8],
123    full_len: usize,
124    limits: &EncodeLimits,
125    stats: &mut EncodeStats,
126) -> Value {
127    let bytes = unhex_pairs(hex_text);
128    let (scrubbed, _) = scrub::scrub_bytes(&bytes);
129    let (tail, _) = scrub::scrub_cut_tail(&scrubbed);
130    let keep = scrub::cut_index(&tail, limits.max_value_bytes);
131    stats.truncated_values += 1;
132    let decoded_len = full_len.saturating_sub(2) / 2;
133    Value::String(format!(
134        "\\x{}{TRUNCATION_MARK}{keep} of {decoded_len} bytes]",
135        hex(&tail[..keep])
136    ))
137}
138
139/// Replaces password hashes in a raw value. A bytea value is scrubbed as the bytes its hex text stands for.
140fn scrub_raw<'a>(raw: &'a [u8], ty: &TypeInfo) -> (Cow<'a, [u8]>, usize) {
141    match ty.kind {
142        TypeKind::Bytea => scrub_bytea_text(raw),
143        _ => scrub::scrub_bytes(raw),
144    }
145}
146
147/// Scrubs the bytes of a `\x` hex text. Returns the text unchanged when no hash is found.
148fn scrub_bytea_text(raw: &[u8]) -> (Cow<'_, [u8]>, usize) {
149    let Some(hex_text) = raw.strip_prefix(b"\\x") else {
150        return (Cow::Borrowed(raw), 0);
151    };
152    let bytes = unhex_pairs(hex_text);
153    let (scrubbed, found) = scrub::scrub_bytes(&bytes);
154    if found == 0 {
155        return (Cow::Borrowed(raw), 0);
156    }
157    let mut text = b"\\x".to_vec();
158    text.extend_from_slice(hex(&scrubbed).as_bytes());
159    (Cow::Owned(text), found)
160}
161
162/// The bytes of each complete pair of hex digits, stopping at the first character that is not a digit.
163fn unhex_pairs(hex_text: &[u8]) -> Vec<u8> {
164    let digit = |b: u8| char::from(b).to_digit(16).map(|d| d as u8);
165    let mut out = Vec::with_capacity(hex_text.len() / 2);
166    for pair in hex_text.chunks_exact(2) {
167        match (digit(pair[0]), digit(pair[1])) {
168            (Some(high), Some(low)) => out.push(high << 4 | low),
169            _ => break,
170        }
171    }
172    out
173}
174
175fn bytea(text: &str, limits: &EncodeLimits, stats: &mut EncodeStats) -> Option<Value> {
176    let hex = text.strip_prefix("\\x")?;
177    if !hex.len().is_multiple_of(2) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
178        return None;
179    }
180    let (scrubbed, found) = scrub_bytea_text(text.as_bytes());
181    if found > 0 {
182        let replaced = String::from_utf8_lossy(&scrubbed).into_owned();
183        return bytea(&replaced, limits, stats);
184    }
185    let decoded_len = hex.len() / 2;
186    let cap = limits.max_binary_preview_bytes;
187    if decoded_len <= cap {
188        return Some(Value::String(format!("\\x{hex}")));
189    }
190    let decoded = unhex_pairs(hex.as_bytes());
191    let keep = scrub::cut_index(&decoded, cap);
192    stats.truncated_values += 1;
193    Some(Value::String(format!(
194        "\\x{}{TRUNCATION_MARK}{keep} of {decoded_len} bytes]",
195        self::hex(&decoded[..keep])
196    )))
197}
198
199/// Text is cut on a char boundary, with the marker, when longer than max_value_bytes.
200pub(super) fn text_value(s: &str, limits: &EncodeLimits, stats: &mut EncodeStats) -> Value {
201    let max = limits.max_value_bytes;
202    if s.len() <= max {
203        return Value::String(s.to_string());
204    }
205    let mut cut = crate::scrub::cut_index(s.as_bytes(), max);
206    while !s.is_char_boundary(cut) {
207        cut -= 1;
208    }
209    stats.truncated_values += 1;
210    Value::String(format!(
211        "{}{TRUNCATION_MARK}{cut} of {} bytes]",
212        &s[..cut],
213        s.len()
214    ))
215}
216
217/// Adds the counters of a nested decode that succeeded.
218pub(super) fn absorb(stats: &mut EncodeStats, other: &EncodeStats) {
219    stats.truncated_values += other.truncated_values;
220    stats.raw_fallbacks += other.raw_fallbacks;
221}
222
223/// The wire cut the value: keep the valid prefix, lossy-decoded, with the marker.
224fn wire_truncated(raw: &[u8], full_len: usize, stats: &mut EncodeStats) -> Value {
225    let valid = match std::str::from_utf8(raw) {
226        Ok(_) => raw.len(),
227        Err(e) if e.error_len().is_none() => e.valid_up_to(),
228        Err(_) => raw.len(),
229    };
230    let cut = scrub::cut_index(raw, valid);
231    stats.truncated_values += 1;
232    Value::String(format!(
233        "{}{TRUNCATION_MARK}{cut} of {full_len} bytes]",
234        String::from_utf8_lossy(&raw[..cut])
235    ))
236}
237
238/// Non-UTF-8 bytes as `\x` hex, capped like bytea.
239fn hex_capped(raw: &[u8], limits: &EncodeLimits, stats: &mut EncodeStats) -> Value {
240    let cap = limits.max_binary_preview_bytes;
241    if raw.len() <= cap {
242        return Value::String(format!("\\x{}", hex(raw)));
243    }
244    let keep = scrub::cut_index(raw, cap);
245    stats.truncated_values += 1;
246    Value::String(format!(
247        "\\x{}{TRUNCATION_MARK}{keep} of {} bytes]",
248        hex(&raw[..keep]),
249        raw.len()
250    ))
251}
252
253fn hex(bytes: &[u8]) -> String {
254    const DIGITS: &[u8; 16] = b"0123456789abcdef";
255    let mut out = String::with_capacity(bytes.len() * 2);
256    for &b in bytes {
257        out.push(char::from(DIGITS[usize::from(b >> 4)]));
258        out.push(char::from(DIGITS[usize::from(b & 0x0f)]));
259    }
260    out
261}