doido-controller 0.0.9

Action Controller + routing + Tower middleware for Doido: handlers, Context, responses, filters, routes! DSL, sessions, and middleware stacks.
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
use crate::cookies::CookieJar;
use crate::flash::Flash;
use crate::session::{CookieSessionStore, EncryptedCookieSessionStore, Session};
use axum::{
    body::Body,
    extract::{FromRequestParts, RawPathParams, Request},
    http::{header, HeaderValue, StatusCode},
    response::Response,
};
use doido_model::sea_orm::DatabaseConnection;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::BTreeMap;

/// Maximum request body size accepted by [`Context::form`]/[`Context::body_json`].
const MAX_BODY_BYTES: usize = 2 * 1024 * 1024;

/// Cookie name for the encrypted session.
const SESSION_COOKIE: &str = "_doido_session";
/// Cookie name for the flash.
const FLASH_COOKIE: &str = "_doido_flash";

/// Per-request context passed to every action.
pub struct Context {
    pub(crate) parts: http::request::Parts,
    /// Taken (set to `None`) once read by [`form`](Self::form)/[`body_json`](Self::body_json).
    pub(crate) body: Option<Body>,
    /// Matched path parameters (e.g. `id` from `/posts/{id}`), in route order.
    pub(crate) path_params: Vec<(String, String)>,
    /// Encrypted session, loaded from the session cookie on first access.
    pub(crate) session: Option<Session>,
    /// Flash bag, loaded from the flash cookie on first access.
    pub(crate) flash: Option<Flash>,
    /// Snapshot of the incoming flash, used to sweep it after one request.
    pub(crate) flash_loaded: BTreeMap<String, String>,
    /// Cookie jar, built from the request `Cookie` header on first access.
    pub(crate) cookies: Option<CookieJar>,
}

impl Context {
    /// Central constructor used by the `#[controller]` macro. Splits the request,
    /// captures matched path params, and retains the body for later reads.
    pub async fn build(req: Request) -> Self {
        let (mut parts, body) = req.into_parts();
        let path_params = Self::extract_path_params(&mut parts).await;
        Self {
            parts,
            body: Some(body),
            path_params,
            session: None,
            flash: None,
            flash_loaded: BTreeMap::new(),
            cookies: None,
        }
    }

    async fn extract_path_params(parts: &mut http::request::Parts) -> Vec<(String, String)> {
        match RawPathParams::from_request_parts(parts, &()).await {
            Ok(params) => params
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            Err(_) => Vec::new(),
        }
    }

    pub fn from_request_parts(parts: http::request::Parts) -> Self {
        Self {
            parts,
            body: None,
            path_params: Vec::new(),
            session: None,
            flash: None,
            flash_loaded: BTreeMap::new(),
            cookies: None,
        }
    }

    pub fn from_request(parts: http::request::Parts, body: Body) -> Self {
        Self {
            parts,
            body: Some(body),
            path_params: Vec::new(),
            session: None,
            flash: None,
            flash_loaded: BTreeMap::new(),
            cookies: None,
        }
    }

    /// The application's database connection (global pool installed at boot).
    pub fn db(&self) -> &'static DatabaseConnection {
        doido_model::pool::pool()
    }

    /// A matched path parameter by name, e.g. `ctx.param("id")` for `/posts/{id}`.
    pub fn param(&self, name: &str) -> Option<&str> {
        self.path_params
            .iter()
            .find(|(k, _)| k == name)
            .map(|(_, v)| v.as_str())
    }

    /// Deserialize a URL-encoded (form) request body. Consumes the body.
    pub async fn form<T: DeserializeOwned>(&mut self) -> doido_core::Result<T> {
        let bytes = self.read_body().await?;
        serde_urlencoded::from_bytes(&bytes)
            .map_err(|e| doido_core::anyhow::anyhow!("form deserialization failed: {e}"))
    }

    /// Deserialize a JSON request body. Consumes the body.
    pub async fn body_json<T: DeserializeOwned>(&mut self) -> doido_core::Result<T> {
        let bytes = self.read_body().await?;
        serde_json::from_slice(&bytes)
            .map_err(|e| doido_core::anyhow::anyhow!("JSON body deserialization failed: {e}"))
    }

    async fn read_body(&mut self) -> doido_core::Result<Vec<u8>> {
        let body = self
            .body
            .take()
            .ok_or_else(|| doido_core::anyhow::anyhow!("request body already consumed"))?;
        let bytes = axum::body::to_bytes(body, MAX_BODY_BYTES)
            .await
            .map_err(|e| doido_core::anyhow::anyhow!("failed to read request body: {e}"))?;
        Ok(bytes.to_vec())
    }

    /// Deserialize typed params from the request URI query string.
    pub fn params<T: serde::de::DeserializeOwned>(&self) -> doido_core::Result<T> {
        let query = self.parts.uri.query().unwrap_or("");
        serde_urlencoded::from_str(query)
            .map_err(|e| doido_core::anyhow::anyhow!("params deserialization failed: {e}"))
    }

    /// The query string as strong [`Params`](crate::params::Params), for
    /// `require`/`permit` allowlisting before use.
    pub fn query_params(&self) -> crate::params::Params {
        let query = self.parts.uri.query().unwrap_or("");
        let pairs: Vec<(String, String)> = serde_urlencoded::from_str(query).unwrap_or_default();
        let mut map = serde_json::Map::new();
        for (k, v) in pairs {
            map.insert(k, serde_json::Value::String(v));
        }
        crate::params::Params::new(serde_json::Value::Object(map))
    }

    /// Render a Tera view to an HTML 200 response.
    ///
    /// `template` is resolved by the global [`doido_view`] engine (installed at
    /// boot) against `app/views`, with the `.html.tera` suffix added — e.g.
    /// `"posts/index"` → `app/views/posts/index.html.tera`. A render failure (or
    /// an uninitialised engine) yields a `500`.
    pub fn render(&self, template: &str, data: serde_json::Value) -> Response {
        match doido_view::render(template, &data) {
            Ok(html) => Response::builder()
                .status(StatusCode::OK)
                .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
                .body(Body::from(html))
                .expect("valid html response"),
            Err(error) => {
                tracing::error!(%error, template, "view render failed");
                Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Body::from("Internal Server Error"))
                    .expect("valid 500 response")
            }
        }
    }

    /// Return a JSON 200 response.
    pub fn json<T: Serialize>(&self, data: T) -> Response {
        let body = serde_json::to_vec(&data).unwrap_or_default();
        Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(body))
            .unwrap()
    }

    /// Return a 302 redirect.
    pub fn redirect_to(&self, location: impl AsRef<str>) -> Response {
        Response::builder()
            .status(StatusCode::FOUND)
            .header(
                header::LOCATION,
                HeaderValue::from_str(location.as_ref()).unwrap(),
            )
            .body(Body::empty())
            .unwrap()
    }

    /// Return a response with an explicit status code and empty body.
    /// `code` must be a valid HTTP status code (100–999).
    pub fn status(&self, code: u16) -> Response {
        Response::builder()
            .status(code)
            .body(Body::empty())
            .unwrap()
    }

    /// Get a request header by name (lowercase).
    pub fn header(&self, name: &str) -> Option<&http::HeaderValue> {
        self.parts.headers.get(name)
    }

    /// Send raw bytes as a response (Rails `send_data`). When `filename` is set,
    /// a `Content-Disposition: attachment` header prompts a download.
    pub fn send_data(&self, data: Vec<u8>, content_type: &str, filename: Option<&str>) -> Response {
        let mut builder = Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, content_type);
        if let Some(name) = filename {
            builder = builder.header(
                header::CONTENT_DISPOSITION,
                format!("attachment; filename=\"{name}\""),
            );
        }
        builder
            .body(Body::from(data))
            .expect("valid send_data response")
    }

    /// Send a file's contents as a response (Rails `send_file`). `content_type`
    /// defaults to `application/octet-stream`; the file name is used for the
    /// download disposition.
    pub async fn send_file(
        &self,
        path: impl AsRef<std::path::Path>,
        content_type: Option<&str>,
    ) -> doido_core::Result<Response> {
        let path = path.as_ref();
        let data = tokio::fs::read(path)
            .await
            .map_err(|e| doido_core::anyhow::anyhow!("send_file failed to read {path:?}: {e}"))?;
        let content_type = content_type.unwrap_or("application/octet-stream");
        let filename = path.file_name().and_then(|n| n.to_str());
        Ok(self.send_data(data, content_type, filename))
    }

    /// The negotiated response [`Format`](crate::respond::Format): a `.json` or
    /// `.html` path extension wins, otherwise the `Accept` header is inspected;
    /// anything else is `Any`.
    pub fn negotiated_format(&self) -> crate::respond::Format {
        use crate::respond::Format;
        let path = self.parts.uri.path();
        if path.ends_with(".json") {
            return Format::Json;
        }
        if path.ends_with(".html") {
            return Format::Html;
        }
        match self
            .parts
            .headers
            .get(header::ACCEPT)
            .and_then(|a| a.to_str().ok())
        {
            Some(accept) if accept.contains("application/json") => Format::Json,
            Some(accept) if accept.contains("text/html") => Format::Html,
            _ => Format::Any,
        }
    }

    /// Begin format-based content negotiation (Rails `respond_to`).
    pub fn respond_to(&self) -> crate::respond::RespondTo {
        crate::respond::RespondTo::new(self.negotiated_format())
    }

    /// Whether the request's `If-None-Match` matches `etag` (or is `*`).
    pub fn etag_matches(&self, etag: &str) -> bool {
        match self
            .parts
            .headers
            .get(header::IF_NONE_MATCH)
            .and_then(|v| v.to_str().ok())
        {
            Some("*") => true,
            Some(inm) => inm.split(',').map(str::trim).any(|t| t == etag),
            None => false,
        }
    }

    fn if_modified_since_matches(&self, last_modified: &str) -> bool {
        self.parts
            .headers
            .get(header::IF_MODIFIED_SINCE)
            .and_then(|v| v.to_str().ok())
            .map(|v| v == last_modified)
            .unwrap_or(false)
    }

    /// HTTP conditional-GET check (Rails `fresh_when`): if the request's
    /// validators match `etag` (`If-None-Match`) or `last_modified`
    /// (`If-Modified-Since`), return a `304 Not Modified` echoing the validators;
    /// otherwise return `None` and render normally (setting the same validators).
    pub fn fresh_when(&self, etag: Option<&str>, last_modified: Option<&str>) -> Option<Response> {
        let fresh = etag.map(|e| self.etag_matches(e)).unwrap_or(false)
            || last_modified
                .map(|lm| self.if_modified_since_matches(lm))
                .unwrap_or(false);
        if !fresh {
            return None;
        }
        let mut builder = Response::builder().status(StatusCode::NOT_MODIFIED);
        if let Some(e) = etag {
            builder = builder.header(header::ETAG, e);
        }
        if let Some(lm) = last_modified {
            builder = builder.header(header::LAST_MODIFIED, lm);
        }
        Some(builder.body(Body::empty()).expect("valid 304 response"))
    }

    /// The plain/signed cookie jar (Rails `cookies` / `cookies.signed`). Reads
    /// parse the request `Cookie` header; staged writes are flushed to
    /// `Set-Cookie` after the action runs (see [`commit_to_response`]).
    ///
    /// [`commit_to_response`]: Self::commit_to_response
    pub fn cookies(&mut self) -> &mut CookieJar {
        if self.cookies.is_none() {
            let header = self
                .parts
                .headers
                .get(header::COOKIE)
                .and_then(|v| v.to_str().ok());
            self.cookies = Some(CookieJar::from_header(header, crate::secret::key_base()));
        }
        self.cookies.as_mut().expect("cookie jar just set")
    }

    /// The encrypted session (Rails `session`). Loaded from the session cookie on
    /// first access and re-encrypted into the response afterwards.
    pub fn session(&mut self) -> &mut Session {
        if self.session.is_none() {
            let store = EncryptedCookieSessionStore::default();
            let session = self
                .raw_cookie(SESSION_COOKIE)
                .and_then(|raw| store.decode(&raw))
                .unwrap_or_default();
            self.session = Some(session);
        }
        self.session.as_mut().expect("session just set")
    }

    /// The flash (Rails `flash`): messages set on one request and read on the
    /// next. Messages set this request are carried forward in a cookie; a flash
    /// that is only read is swept so it lives exactly one following request.
    pub fn flash(&mut self) -> &mut Flash {
        if self.flash.is_none() {
            let store = CookieSessionStore::new(crate::secret::key_base());
            let flash = self
                .raw_cookie(FLASH_COOKIE)
                .map(|raw| Flash::from_cookie(&store, &raw))
                .unwrap_or_default();
            self.flash_loaded = flash.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
            self.flash = Some(flash);
        }
        self.flash.as_mut().expect("flash just set")
    }

    /// Read a raw incoming cookie value by name from the request `Cookie` header.
    fn raw_cookie(&self, name: &str) -> Option<String> {
        let header = self.parts.headers.get(header::COOKIE)?.to_str().ok()?;
        header
            .split(';')
            .filter_map(|pair| pair.trim().split_once('='))
            .find(|(k, _)| *k == name)
            .map(|(_, v)| v.to_string())
    }

    /// Flush any session/flash/cookie changes into the response `Set-Cookie`
    /// headers. Called by the `#[controller]` macro after the action; a no-op
    /// when the action never touched session/flash/cookies.
    pub fn commit_to_response(&self, response: &mut Response) {
        let secret = crate::secret::key_base();

        if let Some(session) = &self.session {
            let value = EncryptedCookieSessionStore::new(secret.clone()).encode(session);
            append_cookie(
                response,
                &format!("{SESSION_COOKIE}={value}; Path=/; HttpOnly; SameSite=Lax"),
            );
        }

        if let Some(flash) = &self.flash {
            let current: BTreeMap<String, String> =
                flash.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
            if current != self.flash_loaded {
                // New messages set this request → carry them to the next one.
                if current.is_empty() {
                    append_cookie(response, &format!("{FLASH_COOKIE}=; Path=/; Max-Age=0"));
                } else {
                    let value = flash.to_cookie(&CookieSessionStore::new(secret.clone()));
                    append_cookie(
                        response,
                        &format!("{FLASH_COOKIE}={value}; Path=/; HttpOnly; SameSite=Lax"),
                    );
                }
            } else if !self.flash_loaded.is_empty() {
                // Read-only this request → expire so it lives exactly one request.
                append_cookie(response, &format!("{FLASH_COOKIE}=; Path=/; Max-Age=0"));
            }
        }

        if let Some(jar) = &self.cookies {
            for header_value in jar.to_set_cookie_headers() {
                append_cookie(response, &header_value);
            }
        }
    }
}

/// Append a `Set-Cookie` header value to a response (multiple are allowed).
fn append_cookie(response: &mut Response, value: &str) {
    if let Ok(header_value) = HeaderValue::from_str(value) {
        response
            .headers_mut()
            .append(header::SET_COOKIE, header_value);
    }
}

/// Lets a `#[controller]` action body evaluate to either a [`Response`] or a
/// `Result<Response, E>`. The macro wraps every action body in
/// `into_action_response()`, so actions can use `?` for fallible work (DB calls,
/// body parsing) and an `Err` becomes a `500` response.
pub trait IntoActionResponse {
    fn into_action_response(self) -> Response;
}

impl IntoActionResponse for Response {
    fn into_action_response(self) -> Response {
        self
    }
}

impl<E: std::fmt::Display> IntoActionResponse for Result<Response, E> {
    fn into_action_response(self) -> Response {
        match self {
            Ok(response) => response,
            Err(error) => {
                tracing::error!(%error, "action returned an error");
                Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Body::from("Internal Server Error"))
                    .expect("static 500 response is valid")
            }
        }
    }
}

// `Context` must stay `Send` so controller handler futures (which hold a
// `&mut Context` across `.await`) satisfy axum's `Handler` bound.
const _: fn() = || {
    fn assert_send<T: Send>() {}
    assert_send::<Context>();
};