Skip to main content

vld_http_common/
lib.rs

1//! # vld-http-common — Shared HTTP helpers for `vld` web integrations
2//!
3//! This crate provides common utility functions used by `vld-axum`,
4//! `vld-actix`, `vld-rocket`, `vld-poem`, and `vld-warp`.
5//!
6//! **Not intended for direct use by end users** — import via the
7//! framework-specific crate instead.
8
9/// Default max request body size for adapters that do not reuse the
10/// framework's built-in limit (2 MiB — same as axum `DefaultBodyLimit`).
11pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
12
13/// Coerce a raw string value into a typed JSON value.
14///
15/// - `""` → `Null`
16/// - `"true"` / `"false"` (case-insensitive) → `Bool`
17/// - `"null"` (case-insensitive) → `Null`
18/// - Integer-looking → `Number` (i64)
19/// - Float-looking → `Number` (f64)
20/// - Everything else → `String`
21pub fn coerce_value(raw: &str) -> serde_json::Value {
22    if raw.is_empty() {
23        return serde_json::Value::Null;
24    }
25
26    if raw.eq_ignore_ascii_case("true") {
27        return serde_json::Value::Bool(true);
28    }
29    if raw.eq_ignore_ascii_case("false") {
30        return serde_json::Value::Bool(false);
31    }
32    if raw.eq_ignore_ascii_case("null") {
33        return serde_json::Value::Null;
34    }
35
36    if let Ok(n) = raw.parse::<i64>() {
37        return serde_json::Value::Number(n.into());
38    }
39
40    if let Ok(f) = raw.parse::<f64>() {
41        if f.is_finite() {
42            if let Some(n) = serde_json::Number::from_f64(f) {
43                return serde_json::Value::Number(n);
44            }
45        }
46    }
47
48    serde_json::Value::String(raw.to_string())
49}
50
51/// Parse a URL query string into a `serde_json::Map`.
52///
53/// Each `key=value` pair is URL-decoded and the value is coerced via
54/// [`coerce_value`]. Empty pairs are skipped.
55pub fn parse_query_string(query: &str) -> serde_json::Map<String, serde_json::Value> {
56    let mut map = serde_json::Map::new();
57
58    if query.is_empty() {
59        return map;
60    }
61
62    for pair in query.split('&') {
63        if pair.is_empty() {
64            continue;
65        }
66        let (key, raw_value) = match pair.split_once('=') {
67            Some((k, v)) => (k, v),
68            None => (pair, ""),
69        };
70
71        let key = url_decode(key);
72        let raw_value = url_decode(raw_value);
73
74        map.insert(key, coerce_value(&raw_value));
75    }
76
77    map
78}
79
80/// Parse a URL query string into a `serde_json::Value::Object`.
81///
82/// Convenience wrapper around [`parse_query_string`].
83pub fn query_string_to_json(query: &str) -> serde_json::Value {
84    serde_json::Value::Object(parse_query_string(query))
85}
86
87/// Build a JSON object from a `Cookie` header value.
88///
89/// Cookie names are used as-is. Values are coerced via [`coerce_value`].
90pub fn cookies_to_json(cookie_header: &str) -> serde_json::Value {
91    let mut map = serde_json::Map::new();
92
93    if cookie_header.is_empty() {
94        return serde_json::Value::Object(map);
95    }
96
97    for cookie in cookie_header.split(';') {
98        let cookie = cookie.trim();
99        if cookie.is_empty() {
100            continue;
101        }
102        let (name, value) = match cookie.split_once('=') {
103            Some((n, v)) => (n.trim(), v.trim()),
104            None => (cookie.trim(), ""),
105        };
106        map.insert(name.to_string(), coerce_value(value));
107    }
108
109    serde_json::Value::Object(map)
110}
111
112// ---------------------------------------------------------------------------
113// Error response schemas (defined via vld::schema!)
114// ---------------------------------------------------------------------------
115
116use serde::Serialize;
117
118vld::schema! {
119    /// Simple error body: `{ "error": "..." }`.
120    ///
121    /// Used for generic HTTP errors such as "Invalid UTF-8", "Payload too large",
122    /// "Not Found", "Bad Request", etc.
123    #[derive(Debug, Clone, Serialize)]
124    pub struct ErrorBody {
125        pub error: String => vld::string(),
126    }
127}
128
129vld::schema! {
130    /// Error body with a message: `{ "error": "...", "message": "..." }`.
131    ///
132    /// Used for JSON parse errors that include a description of what went wrong.
133    #[derive(Debug, Clone, Serialize)]
134    pub struct ErrorWithMessage {
135        pub error: String   => vld::string(),
136        pub message: String => vld::string(),
137    }
138}
139
140vld::schema! {
141    /// A single validation issue: `{ "path": "...", "message": "..." }`.
142    #[derive(Debug, Clone, Serialize)]
143    pub struct ValidationIssue {
144        pub path: String    => vld::string(),
145        pub message: String => vld::string(),
146    }
147}
148
149vld::schema! {
150    /// A validation issue with an error code:
151    /// `{ "path": "...", "message": "...", "code": "..." }`.
152    #[derive(Debug, Clone, Serialize)]
153    pub struct ValidationIssueWithCode {
154        pub path: String    => vld::string(),
155        pub message: String => vld::string(),
156        pub code: String    => vld::string(),
157    }
158}
159
160vld::schema! {
161    /// Validation error response body:
162    /// `{ "error": "Validation failed", "issues": [...] }`.
163    #[derive(Debug, Clone, Serialize)]
164    pub struct ValidationErrorBody {
165        pub error: String => vld::string(),
166        pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
167    }
168}
169
170// ---------------------------------------------------------------------------
171// Formatting helpers
172// ---------------------------------------------------------------------------
173
174fn format_path(path: &[vld::error::PathSegment]) -> String {
175    use vld::error::PathSegment;
176    let mut out = String::new();
177    for seg in path {
178        match seg {
179            PathSegment::Field(name) => {
180                out.push('.');
181                out.push_str(name);
182            }
183            PathSegment::Index(idx) => {
184                out.push('[');
185                out.push_str(&idx.to_string());
186                out.push(']');
187            }
188        }
189    }
190    out
191}
192
193/// Format a [`VldError`](vld::error::VldError) into a list of
194/// [`ValidationIssue`] structs.
195pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
196    err.issues
197        .iter()
198        .map(|i| ValidationIssue {
199            path: format_path(&i.path),
200            message: i.message.clone(),
201        })
202        .collect()
203}
204
205/// Format a [`VldError`](vld::error::VldError) into a JSON object with
206/// `"error"` and `"issues"` keys — ready to be sent as a 422 response body.
207///
208/// Internally constructs a [`ValidationErrorBody`] and serializes it.
209pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
210    let body = ValidationErrorBody {
211        error: "Validation failed".into(),
212        issues: format_issues(err),
213    };
214    serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
215}
216
217/// Format issues with an additional `"code"` key from
218/// [`IssueCode::key()`](vld::error::IssueCode::key).
219///
220/// Returns a list of [`ValidationIssueWithCode`] structs.
221pub fn format_issues_with_code(err: &vld::error::VldError) -> Vec<ValidationIssueWithCode> {
222    err.issues
223        .iter()
224        .map(|issue| ValidationIssueWithCode {
225            path: format_path(&issue.path),
226            message: issue.message.clone(),
227            code: issue.code.key().to_string(),
228        })
229        .collect()
230}
231
232/// Minimal percent-decode for URL query parameters.
233///
234/// Handles `%XX` hex encoding and `+` → space conversion.
235pub fn url_decode(input: &str) -> String {
236    let s = input.replace('+', " ");
237    let mut result = String::with_capacity(s.len());
238    let mut chars = s.chars();
239    while let Some(c) = chars.next() {
240        if c == '%' {
241            let hex: String = chars.by_ref().take(2).collect();
242            if let Ok(byte) = u8::from_str_radix(&hex, 16) {
243                result.push(byte as char);
244            } else {
245                result.push('%');
246                result.push_str(&hex);
247            }
248        } else {
249            result.push(c);
250        }
251    }
252    result
253}
254
255// ---------------------------------------------------------------------------
256// Standard HTTP error response helpers
257// ---------------------------------------------------------------------------
258
259/// Build a JSON error body for invalid JSON parse errors.
260///
261/// Returns `{ "error": "Invalid JSON", "message": "..." }`.
262///
263/// Internally constructs an [`ErrorWithMessage`] and serializes it.
264pub fn format_json_parse_error(message: &str) -> serde_json::Value {
265    serde_json::to_value(ErrorWithMessage {
266        error: "Invalid JSON".into(),
267        message: message.into(),
268    })
269    .expect("ErrorWithMessage serialization cannot fail")
270}
271
272/// Build a JSON error body for invalid UTF-8 payloads.
273///
274/// Returns `{ "error": "Invalid UTF-8" }`.
275///
276/// Internally constructs an [`ErrorBody`] and serializes it.
277pub fn format_utf8_error() -> serde_json::Value {
278    serde_json::to_value(ErrorBody {
279        error: "Invalid UTF-8".into(),
280    })
281    .expect("ErrorBody serialization cannot fail")
282}
283
284/// Build a JSON error body for payloads that exceed the size limit.
285///
286/// Returns `{ "error": "Payload too large" }`.
287///
288/// Internally constructs an [`ErrorBody`] and serializes it.
289pub fn format_payload_too_large() -> serde_json::Value {
290    serde_json::to_value(ErrorBody {
291        error: "Payload too large".into(),
292    })
293    .expect("ErrorBody serialization cannot fail")
294}
295
296/// Build a generic JSON error body with a custom error string.
297///
298/// Returns `{ "error": "<error>" }`.
299///
300/// Internally constructs an [`ErrorBody`] and serializes it.
301pub fn format_generic_error(error: &str) -> serde_json::Value {
302    serde_json::to_value(ErrorBody {
303        error: error.into(),
304    })
305    .expect("ErrorBody serialization cannot fail")
306}
307
308/// Extract parameter names from a route pattern like `/users/{id}/posts/{post_id}`.
309pub fn extract_path_param_names(pattern: &str) -> Vec<String> {
310    let mut names = Vec::new();
311    let mut chars = pattern.chars().peekable();
312    while let Some(c) = chars.next() {
313        if c == '{' {
314            let name: String = chars.by_ref().take_while(|&c| c != '}').collect();
315            if !name.is_empty() {
316                names.push(name);
317            }
318        }
319    }
320    names
321}