ferro-rs 0.2.7

A Laravel-inspired web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use super::body::{collect_body, parse_form, parse_json};
use super::cookie::parse_cookies;
use super::ParamError;
use crate::error::FrameworkError;
use bytes::Bytes;
use serde::de::DeserializeOwned;
use std::any::{Any, TypeId};
use std::collections::HashMap;

/// HTTP Request wrapper providing Laravel-like access to request data
pub struct Request {
    inner: hyper::Request<hyper::body::Incoming>,
    params: HashMap<String, String>,
    extensions: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
    /// Route pattern for metrics (e.g., "/users/{id}" instead of "/users/123")
    route_pattern: Option<String>,
}

impl Request {
    /// Create a new request from a raw hyper request.
    pub fn new(inner: hyper::Request<hyper::body::Incoming>) -> Self {
        Self {
            inner,
            params: HashMap::new(),
            extensions: HashMap::new(),
            route_pattern: None,
        }
    }

    /// Attach route parameters extracted from the URL path.
    pub fn with_params(mut self, params: HashMap<String, String>) -> Self {
        self.params = params;
        self
    }

    /// Set the route pattern (e.g., "/users/{id}")
    pub fn with_route_pattern(mut self, pattern: String) -> Self {
        self.route_pattern = Some(pattern);
        self
    }

    /// Get the route pattern for metrics grouping
    pub fn route_pattern(&self) -> Option<String> {
        self.route_pattern.clone()
    }

    /// Insert a value into the request extensions (type-map pattern)
    ///
    /// This is async-safe unlike thread-local storage.
    pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
        self.extensions.insert(TypeId::of::<T>(), Box::new(value));
    }

    /// Get a reference to a value from the request extensions
    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.extensions
            .get(&TypeId::of::<T>())
            .and_then(|boxed| boxed.downcast_ref::<T>())
    }

    /// Get a mutable reference to a value from the request extensions
    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
        self.extensions
            .get_mut(&TypeId::of::<T>())
            .and_then(|boxed| boxed.downcast_mut::<T>())
    }

    /// Get the request method
    pub fn method(&self) -> &hyper::Method {
        self.inner.method()
    }

    /// Get the request path
    pub fn path(&self) -> &str {
        self.inner.uri().path()
    }

    /// Get a route parameter by name (e.g., /users/{id})
    /// Returns Err(ParamError) if the parameter is missing, enabling use of `?` operator
    pub fn param(&self, name: &str) -> Result<&str, ParamError> {
        self.params
            .get(name)
            .map(|s| s.as_str())
            .ok_or_else(|| ParamError {
                param_name: name.to_string(),
            })
    }

    /// Get a route parameter parsed as a specific type
    ///
    /// Combines `param()` with parsing, returning a typed value.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// pub async fn show(req: Request) -> Response {
    ///     let id: i32 = req.param_as("id")?;
    ///     // ...
    /// }
    /// ```
    pub fn param_as<T: std::str::FromStr>(&self, name: &str) -> Result<T, ParamError>
    where
        T::Err: std::fmt::Display,
    {
        let value = self.param(name)?;
        value.parse::<T>().map_err(|e| ParamError {
            param_name: format!("{name} (parse error: {e})"),
        })
    }

    /// Get all route parameters
    pub fn params(&self) -> &HashMap<String, String> {
        &self.params
    }

    /// Get a query string parameter by name
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // URL: /users?page=2&limit=10
    /// let page = req.query("page"); // Some("2")
    /// let sort = req.query("sort"); // None
    /// ```
    pub fn query(&self, name: &str) -> Option<String> {
        self.inner.uri().query().and_then(|q| {
            form_urlencoded::parse(q.as_bytes())
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.into_owned())
        })
    }

    /// Get a query string parameter or a default value
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // URL: /users?page=2
    /// let page = req.query_or("page", "1"); // "2"
    /// let limit = req.query_or("limit", "10"); // "10"
    /// ```
    pub fn query_or(&self, name: &str, default: &str) -> String {
        self.query(name).unwrap_or_else(|| default.to_string())
    }

    /// Get a query string parameter parsed as a specific type
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // URL: /users?page=2&limit=10
    /// let page: Option<i32> = req.query_as("page"); // Some(2)
    /// ```
    pub fn query_as<T: std::str::FromStr>(&self, name: &str) -> Option<T> {
        self.query(name).and_then(|v| v.parse().ok())
    }

    /// Get a query string parameter parsed as a specific type, or a default
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // URL: /users?page=2
    /// let page: i32 = req.query_as_or("page", 1); // 2
    /// let limit: i32 = req.query_as_or("limit", 10); // 10
    /// ```
    pub fn query_as_or<T: std::str::FromStr>(&self, name: &str, default: T) -> T {
        self.query_as(name).unwrap_or(default)
    }

    // ── Phase 137: validation flash round-trip helpers ────────────────────────

    /// Read a previously-submitted form value from session flash.
    ///
    /// After a POST handler calls `ValidationError::with_old_input(&data).redirect_back(...)`,
    /// the GET handler retrieves the value with `req.old("field_name")` and passes it as
    /// `InputProps.default_value` to repopulate the form.
    ///
    /// Reads from `_flash.old._old_input.<field>` without clearing (read-only semantics).
    /// Flash aging (move new→old→deleted) is handled by the session middleware at request
    /// boundaries, so multiple reads in the same GET handler are safe.
    ///
    /// Returns `None` when no flash value exists, no session is active, or the key is absent.
    pub fn old(&self, field: &str) -> Option<String> {
        let key = format!("_flash.old._old_input.{field}");
        crate::session::session().and_then(|s| s.get::<String>(&key))
    }

    /// Read the first validation error message for a field from session flash.
    ///
    /// After a POST handler calls `errors.redirect_back(...)`, the GET handler calls
    /// `req.validation_error("field_name")` and passes the result as `InputProps.error`.
    ///
    /// Reads from `_flash.old._validation_errors` without clearing (read-only semantics).
    ///
    /// Returns `None` when no flash errors exist, no session is active, or the field has no error.
    pub fn validation_error(&self, field: &str) -> Option<String> {
        let errors: Option<std::collections::HashMap<String, Vec<String>>> =
            crate::session::session().and_then(|s| {
                s.get::<std::collections::HashMap<String, Vec<String>>>(
                    "_flash.old._validation_errors",
                )
            });
        errors.and_then(|map| map.get(field).and_then(|v| v.first()).cloned())
    }

    /// Returns `true` when any validation errors were flashed from a prior request.
    ///
    /// Useful for rendering a form-wide error summary banner.
    pub fn has_validation_errors(&self) -> bool {
        crate::session::session()
            .and_then(|s| {
                s.get::<std::collections::HashMap<String, Vec<String>>>(
                    "_flash.old._validation_errors",
                )
            })
            .map(|m| !m.is_empty())
            .unwrap_or(false)
    }

    /// Get the inner hyper request
    pub fn inner(&self) -> &hyper::Request<hyper::body::Incoming> {
        &self.inner
    }

    /// Get a header value by name
    pub fn header(&self, name: &str) -> Option<&str> {
        self.inner.headers().get(name).and_then(|v| v.to_str().ok())
    }

    /// Get the Content-Type header
    pub fn content_type(&self) -> Option<&str> {
        self.header("content-type")
    }

    /// Check if this is an Inertia XHR request
    pub fn is_inertia(&self) -> bool {
        self.header("X-Inertia")
            .map(|v| v == "true")
            .unwrap_or(false)
    }

    /// Get all cookies from the request
    ///
    /// Parses the Cookie header and returns a HashMap of cookie names to values.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cookies = req.cookies();
    /// if let Some(session) = cookies.get("session") {
    ///     println!("Session: {}", session);
    /// }
    /// ```
    pub fn cookies(&self) -> HashMap<String, String> {
        self.header("Cookie").map(parse_cookies).unwrap_or_default()
    }

    /// Get a specific cookie value by name
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if let Some(session_id) = req.cookie("session") {
    ///     // Use session_id
    /// }
    /// ```
    pub fn cookie(&self, name: &str) -> Option<String> {
        self.cookies().get(name).cloned()
    }

    /// Get the Inertia version from request headers
    pub fn inertia_version(&self) -> Option<&str> {
        self.header("X-Inertia-Version")
    }

    /// Get partial component name for partial reloads
    pub fn inertia_partial_component(&self) -> Option<&str> {
        self.header("X-Inertia-Partial-Component")
    }

    /// Get partial data keys for partial reloads
    pub fn inertia_partial_data(&self) -> Option<Vec<&str>> {
        self.header("X-Inertia-Partial-Data")
            .map(|v| v.split(',').collect())
    }

    /// Consume the request and collect the body as bytes
    pub async fn body_bytes(self) -> Result<(RequestParts, Bytes), FrameworkError> {
        let content_type = self
            .inner
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());

        let params = self.params;
        let bytes = collect_body(self.inner.into_body()).await?;

        Ok((
            RequestParts {
                params,
                content_type,
            },
            bytes,
        ))
    }

    /// Parse the request body as JSON
    ///
    /// Consumes the request since the body can only be read once.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// #[derive(Deserialize)]
    /// struct CreateUser { name: String, email: String }
    ///
    /// pub async fn store(req: Request) -> Response {
    ///     let data: CreateUser = req.json().await?;
    ///     // ...
    /// }
    /// ```
    pub async fn json<T: DeserializeOwned>(self) -> Result<T, FrameworkError> {
        let (_, bytes) = self.body_bytes().await?;
        parse_json(&bytes)
    }

    /// Parse the request body as form-urlencoded
    ///
    /// Consumes the request since the body can only be read once.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// #[derive(Deserialize)]
    /// struct LoginForm { username: String, password: String }
    ///
    /// pub async fn login(req: Request) -> Response {
    ///     let form: LoginForm = req.form().await?;
    ///     // ...
    /// }
    /// ```
    pub async fn form<T: DeserializeOwned>(self) -> Result<T, FrameworkError> {
        let (_, bytes) = self.body_bytes().await?;
        parse_form(&bytes)
    }

    /// Parse the request body based on Content-Type header
    ///
    /// - `application/json` -> JSON parsing
    /// - `application/x-www-form-urlencoded` -> Form parsing
    /// - Otherwise -> JSON parsing (default)
    ///
    /// Consumes the request since the body can only be read once.
    pub async fn input<T: DeserializeOwned>(self) -> Result<T, FrameworkError> {
        let (parts, bytes) = self.body_bytes().await?;

        match parts.content_type.as_deref() {
            Some(ct) if ct.starts_with("application/x-www-form-urlencoded") => parse_form(&bytes),
            _ => parse_json(&bytes),
        }
    }

    /// Consume the request and return its parts along with the inner hyper request body
    ///
    /// This is used internally by the handler macro for FormRequest extraction.
    pub fn into_parts(self) -> (RequestParts, hyper::body::Incoming) {
        let content_type = self
            .inner
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());

        let params = self.params;
        let body = self.inner.into_body();

        (
            RequestParts {
                params,
                content_type,
            },
            body,
        )
    }
}

/// Request parts after body has been separated
///
/// Contains metadata needed for body parsing without the body itself.
#[derive(Clone)]
pub struct RequestParts {
    /// Route parameters extracted from the URL path.
    pub params: HashMap<String, String>,
    /// Content-Type header value, if present.
    pub content_type: Option<String>,
}

#[cfg(test)]
mod tests {
    // Phase 137: unit tests for old() / validation_error() / has_validation_errors().
    //
    // The Request struct wraps hyper::body::Incoming which cannot be constructed
    // in unit tests.  We therefore test the underlying session-reading logic
    // directly (the same code path the methods delegate to) using
    // SESSION_CONTEXT.scope() to inject a session.
    //
    // Full end-to-end round-trips (POST → flash → GET → InputProps) live in the
    // gestiscilo integration test scaffold (validation_roundtrip_tests.rs).

    use crate::session::middleware::SESSION_CONTEXT;
    use crate::session::store::SessionData;
    use std::collections::HashMap;
    use std::sync::Arc;
    use tokio::sync::RwLock;

    // ── No-session guard tests ────────────────────────────────────────────────

    #[tokio::test]
    async fn test_session_absent_old_returns_none() {
        // Outside any SESSION_CONTEXT scope, session() returns None.
        // old() delegates to session().and_then(...) so it must also return None.
        let val =
            crate::session::session().and_then(|s| s.get::<String>("_flash.old._old_input.email"));
        assert_eq!(val, None);
    }

    #[tokio::test]
    async fn test_session_absent_validation_error_returns_none() {
        let val = crate::session::session().and_then(|s| {
            s.get::<HashMap<String, Vec<String>>>("_flash.old._validation_errors")
                .and_then(|map| map.get("email").and_then(|v| v.first()).cloned())
        });
        assert_eq!(val, None);
    }

    #[tokio::test]
    async fn test_session_absent_has_validation_errors_false() {
        let val = crate::session::session()
            .and_then(|s| s.get::<HashMap<String, Vec<String>>>("_flash.old._validation_errors"))
            .map(|m| !m.is_empty())
            .unwrap_or(false);
        assert!(!val);
    }

    // ── Session-present tests (direct logic, mirrors Request method bodies) ───

    #[tokio::test]
    async fn test_old_reads_from_flash_old_key() {
        let mut session = SessionData::new("test-id".to_string(), "csrf".to_string());
        // Simulate age_flash_data() having moved the flash to _flash.old.*
        session.put(
            "_flash.old._old_input.email",
            "user@example.com".to_string(),
        );

        let ctx = Arc::new(RwLock::new(Some(session)));
        let val = SESSION_CONTEXT
            .scope(ctx, async {
                crate::session::session()
                    .and_then(|s| s.get::<String>("_flash.old._old_input.email"))
            })
            .await;

        assert_eq!(val, Some("user@example.com".to_string()));
    }

    #[tokio::test]
    async fn test_validation_error_reads_first_message_for_field() {
        let mut session = SessionData::new("test-id".to_string(), "csrf".to_string());
        let mut errors: HashMap<String, Vec<String>> = HashMap::new();
        errors.insert(
            "email".to_string(),
            vec!["Inserisci un indirizzo email valido".to_string()],
        );
        session.put("_flash.old._validation_errors", &errors);

        let ctx = Arc::new(RwLock::new(Some(session)));
        let (email_err, other_err) = SESSION_CONTEXT
            .scope(ctx, async {
                let email_err = crate::session::session().and_then(|s| {
                    s.get::<HashMap<String, Vec<String>>>("_flash.old._validation_errors")
                        .and_then(|map| map.get("email").and_then(|v| v.first()).cloned())
                });
                // Reading the same session twice must not clear the data.
                let other_err = crate::session::session().and_then(|s| {
                    s.get::<HashMap<String, Vec<String>>>("_flash.old._validation_errors")
                        .and_then(|map| map.get("name").and_then(|v| v.first()).cloned())
                });
                (email_err, other_err)
            })
            .await;

        assert_eq!(
            email_err,
            Some("Inserisci un indirizzo email valido".to_string())
        );
        assert_eq!(other_err, None);
    }

    #[tokio::test]
    async fn test_multiple_reads_do_not_clear_flash() {
        // Validates read-only semantics: calling session().get() twice returns
        // the same value (unlike get_flash which clears on read).
        let mut session = SessionData::new("test-id".to_string(), "csrf".to_string());
        session.put("_flash.old._old_input.name", "Mario".to_string());

        let ctx = Arc::new(RwLock::new(Some(session)));
        let (first, second) = SESSION_CONTEXT
            .scope(ctx, async {
                let a = crate::session::session()
                    .and_then(|s| s.get::<String>("_flash.old._old_input.name"));
                let b = crate::session::session()
                    .and_then(|s| s.get::<String>("_flash.old._old_input.name"));
                (a, b)
            })
            .await;

        assert_eq!(first, Some("Mario".to_string()));
        assert_eq!(second, Some("Mario".to_string()));
    }
}