rustango 0.61.13

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! Form sets — parse N copies of the same [`crate::forms::Form`]
//! from a single HTTP request payload.
//!
//! Each row is keyed `<prefix>-<N>-<field>`. The usual prefix is
//! `form`, so three rows of a `title` field arrive as `form-0-title`,
//! `form-1-title` and `form-2-title`.
//!
//! ```ignore
//! use rustango::forms::formset::parse_formset;
//!
//! #[derive(rustango::Form)]
//! struct ArticleRow {
//!     title: String,
//!     #[rustango(min = 0)]
//!     order: i32,
//! }
//!
//! async fn save_articles(axum::Form(data): axum::Form<HashMap<String, String>>) {
//!     match parse_formset::<ArticleRow>(&data, "form") {
//!         Ok(rows) => /* save Vec<ArticleRow> */,
//!         Err(errors) => /* errors[i] is the FormErrors for row i */,
//!     }
//! }
//! ```
//!
//! ## Management form
//!
//! Every payload also carries a "management form" — three integer
//! fields that bound the row range:
//!
//! - `<prefix>-TOTAL_FORMS`: how many rows the client submitted.
//!   **Required** — `parse_formset` errors if missing or malformed.
//! - `<prefix>-INITIAL_FORMS`: how many rows existed when the page
//!   rendered (extras are "new" rows). Currently unused by the
//!   parser; preserved for round-tripping.
//! - `<prefix>-MAX_NUM_FORMS`: upper bound. Unused by the parser;
//!   the caller enforces it.
//!
//! The parser only needs `TOTAL_FORMS`. The rest are accepted (for
//! future use) but not consulted.
//!
//! ## Errors
//!
//! Each row's [`crate::forms::FormErrors`] lands at the matching
//! index in the returned `Vec<FormErrors>`. A row with no errors
//! is represented by an empty `FormErrors`. A separate top-level
//! error variant covers the malformed-management-form case.

use std::collections::HashMap;

use super::{Form, FormErrors};

/// Error returned when the management form is missing or malformed.
/// Distinct from per-row errors so the caller can give a clear
/// "your form rendering is broken" message rather than blaming the
/// user's input.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FormSetError {
    /// `<prefix>-TOTAL_FORMS` was absent. The form likely didn't
    /// render through the formset's management-form helper.
    #[error("formset: missing `{0}-TOTAL_FORMS` management field")]
    MissingTotalForms(String),
    /// `<prefix>-TOTAL_FORMS` was present but not a non-negative
    /// integer.
    #[error("formset: `{prefix}-TOTAL_FORMS` is not a non-negative integer (got `{got}`)")]
    InvalidTotalForms { prefix: String, got: String },
    /// `<prefix>-TOTAL_FORMS` is above [`MAX_FORMS`]: refused before any
    /// allocation or row loop sized by it (#1892).
    #[error("formset: `{prefix}-TOTAL_FORMS` is {got}, above the limit of {max}")]
    TooManyForms {
        prefix: String,
        got: usize,
        max: usize,
    },
}

/// Most rows one formset accepts; rendered as `MAX_NUM_FORMS`.
pub const MAX_FORMS: usize = 1000;

/// Pull the `TOTAL_FORMS` count out of the payload. Returns
/// [`FormSetError`] if the field is missing, malformed or above [`MAX_FORMS`].
pub fn total_forms(data: &HashMap<String, String>, prefix: &str) -> Result<usize, FormSetError> {
    let key = format!("{prefix}-TOTAL_FORMS");
    let raw = data
        .get(&key)
        .ok_or_else(|| FormSetError::MissingTotalForms(prefix.to_owned()))?;
    let n = raw
        .parse::<usize>()
        .map_err(|_| FormSetError::InvalidTotalForms {
            prefix: prefix.to_owned(),
            got: raw.clone(),
        })?;
    if n > MAX_FORMS {
        return Err(FormSetError::TooManyForms {
            prefix: prefix.to_owned(),
            got: n,
            max: MAX_FORMS,
        });
    }
    Ok(n)
}

/// `<prefix>-INITIAL_FORMS`: rows below it are existing ones. `None`
/// when absent or not a number.
#[must_use]
pub fn initial_forms(data: &HashMap<String, String>, prefix: &str) -> Option<usize> {
    data.get(&format!("{prefix}-INITIAL_FORMS"))?.parse().ok()
}

/// Extract the per-row payload at index `idx`. Strips the
/// `<prefix>-<idx>-` prefix from each key. Returns a fresh HashMap
/// suitable for `F::parse`.
#[must_use]
pub fn row_payload(
    data: &HashMap<String, String>,
    prefix: &str,
    idx: usize,
) -> HashMap<String, String> {
    let row_prefix = format!("{prefix}-{idx}-");
    let mut out = HashMap::new();
    for (k, v) in data {
        if let Some(field) = k.strip_prefix(&row_prefix) {
            out.insert(field.to_owned(), v.clone());
        }
    }
    out
}

/// [`row_payload`] for rows `0..n`, in one pass over the keys.
pub(crate) fn row_payloads(
    data: &HashMap<String, String>,
    prefix: &str,
    n: usize,
) -> Vec<HashMap<String, String>> {
    let mut rows = vec![HashMap::new(); n];
    let head = format!("{prefix}-");
    for (k, v) in data {
        let Some((idx, field)) = k.strip_prefix(&head).and_then(|r| r.split_once('-')) else {
            continue;
        };
        // Only the index `format!` writes: no sign, no leading zero.
        let canonical =
            idx.bytes().all(|b| b.is_ascii_digit()) && (idx == "0" || !idx.starts_with('0'));
        if let Some(row) = idx
            .parse::<usize>()
            .ok()
            .filter(|_| canonical)
            .and_then(|i| rows.get_mut(i))
        {
            row.insert(field.to_owned(), v.clone());
        }
    }
    rows
}

/// Parse a formset payload into `Vec<F>`, one entry per row.
///
/// On success: every row parsed cleanly, `Vec<F>` length equals
/// `<prefix>-TOTAL_FORMS`.
///
/// On per-row failure: the returned `Vec<FormErrors>` has length
/// `TOTAL_FORMS`; rows that parsed successfully carry an empty
/// `FormErrors`, rows that failed carry their actual errors. So
/// the caller can re-render the form with errors threaded back
/// to the right row.
///
/// # Errors
/// - [`FormSetError`] if the management form is missing/malformed.
/// - `Err(Err(Vec<FormErrors>))` if ANY row failed parsing.
pub fn parse_formset<F: Form>(
    data: &HashMap<String, String>,
    prefix: &str,
) -> Result<Result<Vec<F>, Vec<FormErrors>>, FormSetError> {
    let n = total_forms(data, prefix)?;
    let mut rows: Vec<F> = Vec::with_capacity(n);
    let mut errors: Vec<FormErrors> = Vec::with_capacity(n);
    let mut any_err = false;
    for row_data in row_payloads(data, prefix, n) {
        match F::parse(&row_data) {
            Ok(row) => {
                rows.push(row);
                errors.push(FormErrors::default());
            }
            Err(e) => {
                any_err = true;
                errors.push(e);
            }
        }
    }
    if any_err {
        Ok(Err(errors))
    } else {
        Ok(Ok(rows))
    }
}

/// Render the three management-form `<input type="hidden">` fields
/// callers stamp into their form's HTML. Counterpart to the parser
/// — emit this in the template so the next submit matches.
///
/// ```ignore
/// // In your handler:
/// ctx.insert("formset_management", &management_form_html("form", initial, total));
///
/// // In the template:
/// <form method="post">
///   {{ formset_management | safe }}
///   {% for row in rows %}
///     {{ row.title.field | safe }}
///   {% endfor %}
/// </form>
/// ```
///
/// `total` is "rows currently rendered" (TOTAL_FORMS); `initial` is
/// "rows that existed when the page first loaded" (INITIAL_FORMS).
/// They're usually equal on first render; they diverge when JS
/// adds extra-row inputs.
#[must_use]
pub fn management_form_html(prefix: &str, initial: usize, total: usize) -> String {
    format!(
        concat!(
            r#"<input type="hidden" name="{p}-TOTAL_FORMS" value="{t}">"#,
            r#"<input type="hidden" name="{p}-INITIAL_FORMS" value="{i}">"#,
            r#"<input type="hidden" name="{p}-MIN_NUM_FORMS" value="0">"#,
            r#"<input type="hidden" name="{p}-MAX_NUM_FORMS" value="{m}">"#,
        ),
        p = prefix,
        t = total,
        i = initial,
        m = MAX_FORMS,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::forms::{Form, FormErrors};
    use std::collections::HashMap;

    // ---------- management form ----------

    #[test]
    fn total_forms_returns_count() {
        let mut data = HashMap::new();
        data.insert("form-TOTAL_FORMS".into(), "3".into());
        assert_eq!(total_forms(&data, "form").unwrap(), 3);
    }

    #[test]
    fn total_forms_above_the_cap_errors() {
        for raw in ["1001", "1000000000000", &u64::MAX.to_string()] {
            let data = HashMap::from([("form-TOTAL_FORMS".to_owned(), raw.to_owned())]);
            let r = total_forms(&data, "form");
            assert!(
                matches!(r, Err(FormSetError::TooManyForms { .. })),
                "{raw}: {r:?}"
            );
        }
        let data = HashMap::from([("form-TOTAL_FORMS".to_owned(), "1000".to_owned())]);
        assert_eq!(total_forms(&data, "form").unwrap(), 1000);
    }

    #[test]
    fn total_forms_missing_errors() {
        let data: HashMap<String, String> = HashMap::new();
        let r = total_forms(&data, "form");
        assert!(matches!(r, Err(FormSetError::MissingTotalForms(_))));
    }

    #[test]
    fn total_forms_malformed_errors() {
        let mut data = HashMap::new();
        data.insert("form-TOTAL_FORMS".into(), "not-a-number".into());
        let r = total_forms(&data, "form");
        assert!(matches!(r, Err(FormSetError::InvalidTotalForms { .. })));
    }

    #[test]
    fn total_forms_supports_custom_prefix() {
        let mut data = HashMap::new();
        data.insert("rows-TOTAL_FORMS".into(), "5".into());
        assert_eq!(total_forms(&data, "rows").unwrap(), 5);
    }

    // ---------- row_payload ----------

    #[test]
    fn row_payload_strips_prefix_and_index() {
        let mut data = HashMap::new();
        data.insert("form-0-title".into(), "Hello".into());
        data.insert("form-0-body".into(), "World".into());
        data.insert("form-1-title".into(), "Second".into());
        let row = row_payload(&data, "form", 0);
        assert_eq!(row.get("title").map(String::as_str), Some("Hello"));
        assert_eq!(row.get("body").map(String::as_str), Some("World"));
        assert!(!row.contains_key("form-0-title"));
        assert!(!row.contains_key("Second")); // other rows excluded
    }

    #[test]
    fn row_payload_for_missing_index_is_empty() {
        let mut data = HashMap::new();
        data.insert("form-0-title".into(), "x".into());
        let row = row_payload(&data, "form", 99);
        assert!(row.is_empty());
    }

    /// Every row from one pass over the keys, as `row_payload` reads each.
    #[test]
    fn row_payloads_match_row_payload() {
        let data: HashMap<String, String> = [
            ("form-0-title", "a"),
            ("form-1-title", "b"),
            ("form-1-x-y", "dash"),
            ("form-01-title", "padded"),
            ("form-+1-title", "plus"),
            ("form-7-title", "past n"),
            ("form-TOTAL_FORMS", "3"),
            ("other-0-title", "z"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_owned(), v.to_owned()))
        .collect();
        let rows = row_payloads(&data, "form", 3);
        assert_eq!(rows.len(), 3);
        for (idx, row) in rows.iter().enumerate() {
            assert_eq!(*row, row_payload(&data, "form", idx), "row {idx}");
        }
    }

    /// Many keys and many rows stay linear, not keys times rows.
    #[test]
    fn parse_formset_is_linear_in_keys() {
        let mut data: HashMap<String, String> = (0..200_000)
            .map(|i| (format!("junk{i}"), String::new()))
            .collect();
        data.insert("form-TOTAL_FORMS".into(), MAX_FORMS.to_string());
        for i in 0..MAX_FORMS {
            data.insert(format!("form-{i}-title"), "t".into());
        }
        let started = std::time::Instant::now();
        let rows = parse_formset::<TitleRow>(&data, "form").unwrap().unwrap();
        assert_eq!(rows.len(), MAX_FORMS);
        let took = started.elapsed();
        assert!(took < std::time::Duration::from_secs(3), "{took:?}");
    }

    // ---------- parse_formset ----------

    /// Test form that requires `title` to be non-empty.
    #[derive(Debug, PartialEq, Eq)]
    struct TitleRow {
        title: String,
    }
    impl Form for TitleRow {
        fn parse(data: &HashMap<String, String>) -> Result<Self, FormErrors> {
            let mut errs = FormErrors::default();
            let title = match data.get("title") {
                Some(s) if !s.is_empty() => s.clone(),
                _ => {
                    errs.add("title", "required");
                    String::new()
                }
            };
            if errs.is_empty() {
                Ok(Self { title })
            } else {
                Err(errs)
            }
        }
    }

    #[test]
    fn parse_formset_all_rows_succeed() {
        let mut data = HashMap::new();
        data.insert("form-TOTAL_FORMS".into(), "2".into());
        data.insert("form-0-title".into(), "First".into());
        data.insert("form-1-title".into(), "Second".into());
        let outcome = parse_formset::<TitleRow>(&data, "form").unwrap();
        let rows = outcome.unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].title, "First");
        assert_eq!(rows[1].title, "Second");
    }

    #[test]
    fn parse_formset_per_row_errors_threaded_by_index() {
        let mut data = HashMap::new();
        data.insert("form-TOTAL_FORMS".into(), "3".into());
        // idx 0: missing title → row 0 errors.
        data.insert("form-1-title".into(), "ok".into());
        // idx 2: missing title → row 2 errors.
        let outcome = parse_formset::<TitleRow>(&data, "form").unwrap();
        let errors = outcome.unwrap_err();
        assert_eq!(errors.len(), 3);
        assert!(!errors[0].is_empty(), "row 0 should have errors");
        assert!(errors[1].is_empty(), "row 1 parsed cleanly");
        assert!(!errors[2].is_empty(), "row 2 should have errors");
    }

    #[test]
    fn parse_formset_zero_rows() {
        let mut data = HashMap::new();
        data.insert("form-TOTAL_FORMS".into(), "0".into());
        let outcome = parse_formset::<TitleRow>(&data, "form").unwrap();
        let rows = outcome.unwrap();
        assert!(rows.is_empty());
    }

    #[test]
    fn parse_formset_missing_management_errors() {
        let data: HashMap<String, String> = HashMap::new();
        let r = parse_formset::<TitleRow>(&data, "form");
        assert!(matches!(r, Err(FormSetError::MissingTotalForms(_))));
    }

    // ---------- management_form_html ----------

    #[test]
    fn management_form_html_contains_all_four_fields() {
        let html = management_form_html("form", 2, 3);
        assert!(html.contains(r#"name="form-TOTAL_FORMS" value="3""#));
        assert!(html.contains(r#"name="form-INITIAL_FORMS" value="2""#));
        assert!(html.contains(r#"name="form-MIN_NUM_FORMS""#));
        assert!(html.contains(r#"name="form-MAX_NUM_FORMS""#));
    }

    #[test]
    fn management_form_html_round_trips_through_parser() {
        // Render with 4 total, then parse the management form back.
        let html = management_form_html("custom", 1, 4);
        // The HTML form would submit these as form-encoded values;
        // we simulate that by extracting the totals.
        assert!(html.contains(r#"name="custom-TOTAL_FORMS" value="4""#));
        let mut data = HashMap::new();
        data.insert("custom-TOTAL_FORMS".into(), "4".into());
        assert_eq!(total_forms(&data, "custom").unwrap(), 4);
    }
}