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        // First occurrence wins: browsers send the most specific cookie first,
107        // so letting a later duplicate override it enables cookie tossing.
108        map.entry(name.to_string())
109            .or_insert_with(|| coerce_value(value));
110    }
111
112    serde_json::Value::Object(map)
113}
114
115// ---------------------------------------------------------------------------
116// Error response schemas (defined via vld::schema!)
117// ---------------------------------------------------------------------------
118
119use serde::Serialize;
120
121vld::schema! {
122    /// Simple error body: `{ "error": "..." }`.
123    ///
124    /// Used for generic HTTP errors such as "Invalid UTF-8", "Payload too large",
125    /// "Not Found", "Bad Request", etc.
126    #[derive(Debug, Clone, Serialize)]
127    pub struct ErrorBody {
128        pub error: String => vld::string(),
129    }
130}
131
132vld::schema! {
133    /// Error body with a message: `{ "error": "...", "message": "..." }`.
134    ///
135    /// Used for JSON parse errors that include a description of what went wrong.
136    #[derive(Debug, Clone, Serialize)]
137    pub struct ErrorWithMessage {
138        pub error: String   => vld::string(),
139        pub message: String => vld::string(),
140    }
141}
142
143vld::schema! {
144    /// A single validation issue: `{ "path": "...", "message": "..." }`.
145    #[derive(Debug, Clone, Serialize)]
146    pub struct ValidationIssue {
147        pub path: String    => vld::string(),
148        pub message: String => vld::string(),
149    }
150}
151
152vld::schema! {
153    /// A validation issue with an error code:
154    /// `{ "path": "...", "message": "...", "code": "..." }`.
155    #[derive(Debug, Clone, Serialize)]
156    pub struct ValidationIssueWithCode {
157        pub path: String    => vld::string(),
158        pub message: String => vld::string(),
159        pub code: String    => vld::string(),
160    }
161}
162
163vld::schema! {
164    /// Validation error response body:
165    /// `{ "error": "Validation failed", "issues": [...] }`.
166    #[derive(Debug, Clone, Serialize)]
167    pub struct ValidationErrorBody {
168        pub error: String => vld::string(),
169        pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
170    }
171}
172
173// ---------------------------------------------------------------------------
174// Formatting helpers
175// ---------------------------------------------------------------------------
176
177fn format_path(path: &[vld::error::PathSegment]) -> String {
178    use vld::error::PathSegment;
179    let mut out = String::new();
180    for seg in path {
181        match seg {
182            PathSegment::Field(name) => {
183                out.push('.');
184                out.push_str(name);
185            }
186            PathSegment::Index(idx) => {
187                out.push('[');
188                out.push_str(&idx.to_string());
189                out.push(']');
190            }
191        }
192    }
193    out
194}
195
196/// Format a [`VldError`](vld::error::VldError) into a list of
197/// [`ValidationIssue`] structs.
198pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
199    err.issues
200        .iter()
201        .map(|i| ValidationIssue {
202            path: format_path(&i.path),
203            message: i.message.clone(),
204        })
205        .collect()
206}
207
208/// Format a [`VldError`](vld::error::VldError) into a JSON object with
209/// `"error"` and `"issues"` keys — ready to be sent as a 422 response body.
210///
211/// Internally constructs a [`ValidationErrorBody`] and serializes it.
212pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
213    let body = ValidationErrorBody {
214        error: "Validation failed".into(),
215        issues: format_issues(err),
216    };
217    serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
218}
219
220/// Format issues with an additional `"code"` key from
221/// [`IssueCode::key()`](vld::error::IssueCode::key).
222///
223/// Returns a list of [`ValidationIssueWithCode`] structs.
224pub fn format_issues_with_code(err: &vld::error::VldError) -> Vec<ValidationIssueWithCode> {
225    err.issues
226        .iter()
227        .map(|issue| ValidationIssueWithCode {
228            path: format_path(&issue.path),
229            message: issue.message.clone(),
230            code: issue.code.key().to_string(),
231        })
232        .collect()
233}
234
235/// Minimal percent-decode for URL query parameters.
236///
237/// Handles `%XX` hex encoding and `+` → space conversion.
238pub fn url_decode(input: &str) -> String {
239    let s = input.replace('+', " ");
240    let mut result = String::with_capacity(s.len());
241    let mut chars = s.chars();
242    while let Some(c) = chars.next() {
243        if c == '%' {
244            let hex: String = chars.by_ref().take(2).collect();
245            if let Ok(byte) = u8::from_str_radix(&hex, 16) {
246                result.push(byte as char);
247            } else {
248                result.push('%');
249                result.push_str(&hex);
250            }
251        } else {
252            result.push(c);
253        }
254    }
255    result
256}
257
258// ---------------------------------------------------------------------------
259// Standard HTTP error response helpers
260// ---------------------------------------------------------------------------
261
262/// Build a JSON error body for invalid JSON parse errors.
263///
264/// Returns `{ "error": "Invalid JSON", "message": "..." }`.
265///
266/// Internally constructs an [`ErrorWithMessage`] and serializes it.
267pub fn format_json_parse_error(message: &str) -> serde_json::Value {
268    serde_json::to_value(ErrorWithMessage {
269        error: "Invalid JSON".into(),
270        message: message.into(),
271    })
272    .expect("ErrorWithMessage serialization cannot fail")
273}
274
275/// Build a JSON error body for invalid UTF-8 payloads.
276///
277/// Returns `{ "error": "Invalid UTF-8" }`.
278///
279/// Internally constructs an [`ErrorBody`] and serializes it.
280pub fn format_utf8_error() -> serde_json::Value {
281    serde_json::to_value(ErrorBody {
282        error: "Invalid UTF-8".into(),
283    })
284    .expect("ErrorBody serialization cannot fail")
285}
286
287/// Build a JSON error body for payloads that exceed the size limit.
288///
289/// Returns `{ "error": "Payload too large" }`.
290///
291/// Internally constructs an [`ErrorBody`] and serializes it.
292pub fn format_payload_too_large() -> serde_json::Value {
293    serde_json::to_value(ErrorBody {
294        error: "Payload too large".into(),
295    })
296    .expect("ErrorBody serialization cannot fail")
297}
298
299/// Build a generic JSON error body with a custom error string.
300///
301/// Returns `{ "error": "<error>" }`.
302///
303/// Internally constructs an [`ErrorBody`] and serializes it.
304pub fn format_generic_error(error: &str) -> serde_json::Value {
305    serde_json::to_value(ErrorBody {
306        error: error.into(),
307    })
308    .expect("ErrorBody serialization cannot fail")
309}
310
311/// Extract parameter names from a route pattern like `/users/{id}/posts/{post_id}`.
312pub fn extract_path_param_names(pattern: &str) -> Vec<String> {
313    let mut names = Vec::new();
314    let mut chars = pattern.chars().peekable();
315    while let Some(c) = chars.next() {
316        if c == '{' {
317            let name: String = chars.by_ref().take_while(|&c| c != '}').collect();
318            if !name.is_empty() {
319                names.push(name);
320            }
321        }
322    }
323    names
324}