rustango 0.58.0

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
//! RSS 2.0 and Atom 1.0 feeds.
//!
//! Build a [`Feed`] and call [`render_rss`] or [`render_atom`]. Adding
//! the route is up to you: serve the RSS string with
//! `Content-Type: application/rss+xml`, the Atom one with
//! `application/atom+xml`.
//!
//! ```ignore
//! use rustango::syndication::{Feed, FeedItem, render_rss};
//! use chrono::Utc;
//!
//! let feed = Feed {
//!     title: "Example blog".into(),
//!     link: "https://example.com/".into(),
//!     description: "Latest articles.".into(),
//!     language: Some("en".into()),
//!     items: vec![
//!         FeedItem::new("Hello, world", "https://example.com/articles/hello")
//!             .with_description("First post")
//!             .with_pub_date(Utc::now())
//!             .with_author("alice@example.com"),
//!     ],
//! };
//! let xml = render_rss(&feed);
//! ```
//!
//! [`Feed`]: crate::syndication::Feed
//! [`render_rss`]: crate::syndication::render_rss
//! [`render_atom`]: crate::syndication::render_atom

use chrono::{DateTime, Utc};

// ------------------------------------------------------------------ Feed / FeedItem

/// Feed-level metadata.
#[derive(Debug, Clone)]
pub struct Feed {
    pub title: String,
    /// The site URL: RSS `<link>`, Atom self link.
    pub link: String,
    pub description: String,
    /// ISO-639-1 language tag such as `"en"`. RSS only.
    pub language: Option<String>,
    /// When the feed last changed. If `None`, rendering uses the
    /// newest `FeedItem::pub_date`.
    pub last_build_date: Option<DateTime<Utc>>,
    pub items: Vec<FeedItem>,
}

/// One entry in a feed.
#[derive(Debug, Clone)]
pub struct FeedItem {
    pub title: String,
    /// The item URL: RSS `<link>` and `<guid>`, Atom `<id>`.
    pub link: String,
    pub description: Option<String>,
    pub pub_date: Option<DateTime<Utc>>,
    /// The author. RSS wants an email address; Atom takes any string.
    pub author: Option<String>,
    /// Overrides the `<guid>` or `<id>`. Defaults to `link`.
    pub guid: Option<String>,
}

impl FeedItem {
    /// Build an item from the two required fields.
    #[must_use]
    pub fn new(title: impl Into<String>, link: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            link: link.into(),
            description: None,
            pub_date: None,
            author: None,
            guid: None,
        }
    }

    #[must_use]
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    #[must_use]
    pub fn with_pub_date(mut self, when: DateTime<Utc>) -> Self {
        self.pub_date = Some(when);
        self
    }

    #[must_use]
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.author = Some(author.into());
        self
    }

    #[must_use]
    pub fn with_guid(mut self, guid: impl Into<String>) -> Self {
        self.guid = Some(guid.into());
        self
    }
}

// ------------------------------------------------------------------ render_rss

/// Render an RSS 2.0 document: one `<channel>` holding the metadata
/// and the `<item>` elements.
#[must_use]
pub fn render_rss(feed: &Feed) -> String {
    let mut out = String::with_capacity(512 + feed.items.len() * 256);
    out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    out.push_str("<rss version=\"2.0\">\n");
    out.push_str("  <channel>\n");
    push_text_element(&mut out, "title", &feed.title, 4);
    push_text_element(&mut out, "link", &feed.link, 4);
    push_text_element(&mut out, "description", &feed.description, 4);
    if let Some(lang) = &feed.language {
        push_text_element(&mut out, "language", lang, 4);
    }
    let last_build = feed
        .last_build_date
        .or_else(|| feed.items.iter().filter_map(|i| i.pub_date).max());
    if let Some(ts) = last_build {
        push_text_element(&mut out, "lastBuildDate", &format_rfc822(ts), 4);
    }
    for item in &feed.items {
        out.push_str("    <item>\n");
        push_text_element(&mut out, "title", &item.title, 6);
        push_text_element(&mut out, "link", &item.link, 6);
        if let Some(desc) = &item.description {
            push_text_element(&mut out, "description", desc, 6);
        }
        if let Some(author) = &item.author {
            push_text_element(&mut out, "author", author, 6);
        }
        if let Some(ts) = item.pub_date {
            push_text_element(&mut out, "pubDate", &format_rfc822(ts), 6);
        }
        let guid = item.guid.as_deref().unwrap_or(&item.link);
        push_text_element(&mut out, "guid", guid, 6);
        out.push_str("    </item>\n");
    }
    out.push_str("  </channel>\n");
    out.push_str("</rss>\n");
    out
}

// ------------------------------------------------------------------ render_atom

/// Render an Atom 1.0 document.
///
/// Atom requires `<id>`, `<title>` and `<updated>` on the feed and on
/// every entry. Missing values are filled in: `feed.link` for the
/// feed `<id>`, and the newest `pub_date`, or now, for `<updated>`.
#[must_use]
pub fn render_atom(feed: &Feed) -> String {
    let mut out = String::with_capacity(512 + feed.items.len() * 256);
    out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    out.push_str("<feed xmlns=\"http://www.w3.org/2005/Atom\">\n");
    push_text_element(&mut out, "title", &feed.title, 2);
    push_text_element(&mut out, "id", &feed.link, 2);
    // Atom uses `<link rel="alternate" href="..."/>`.
    out.push_str("  <link href=\"");
    let mut esc_link = String::new();
    escape_xml_text(&mut esc_link, &feed.link);
    out.push_str(&esc_link);
    out.push_str("\" rel=\"alternate\"/>\n");
    push_text_element(&mut out, "subtitle", &feed.description, 2);
    let updated = feed
        .last_build_date
        .or_else(|| feed.items.iter().filter_map(|i| i.pub_date).max())
        .unwrap_or_else(Utc::now);
    push_text_element(&mut out, "updated", &format_iso8601(updated), 2);
    for item in &feed.items {
        out.push_str("  <entry>\n");
        push_text_element(&mut out, "title", &item.title, 4);
        let id = item.guid.as_deref().unwrap_or(&item.link);
        push_text_element(&mut out, "id", id, 4);
        out.push_str("    <link href=\"");
        let mut esc = String::new();
        escape_xml_text(&mut esc, &item.link);
        out.push_str(&esc);
        out.push_str("\" rel=\"alternate\"/>\n");
        if let Some(desc) = &item.description {
            push_text_element(&mut out, "summary", desc, 4);
        }
        if let Some(author) = &item.author {
            out.push_str("    <author>\n");
            push_text_element(&mut out, "name", author, 6);
            out.push_str("    </author>\n");
        }
        let entry_updated = item.pub_date.unwrap_or(updated);
        push_text_element(&mut out, "updated", &format_iso8601(entry_updated), 4);
        out.push_str("  </entry>\n");
    }
    out.push_str("</feed>\n");
    out
}

// ------------------------------------------------------------------ helpers

fn push_text_element(out: &mut String, name: &str, text: &str, indent: usize) {
    for _ in 0..indent {
        out.push(' ');
    }
    out.push('<');
    out.push_str(name);
    out.push('>');
    escape_xml_text(out, text);
    out.push_str("</");
    out.push_str(name);
    out.push_str(">\n");
}

use crate::text::xml_escape_into as escape_xml_text;

/// The RFC 2822 date RSS 2.0 wants in `<pubDate>` and
/// `<lastBuildDate>`.
fn format_rfc822(ts: DateTime<Utc>) -> String {
    ts.to_rfc2822()
}

/// The RFC 3339 date Atom wants in `<updated>`. UTC renders as `Z`.
fn format_iso8601(ts: DateTime<Utc>) -> String {
    ts.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

// ------------------------------------------------------------------ tests

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;

    fn ts(y: i32, mo: u32, d: u32) -> DateTime<Utc> {
        Utc.with_ymd_and_hms(y, mo, d, 12, 0, 0).unwrap()
    }

    fn sample_feed() -> Feed {
        Feed {
            title: "Example".into(),
            link: "https://example.com/".into(),
            description: "Test feed".into(),
            language: Some("en".into()),
            last_build_date: None,
            items: vec![
                FeedItem::new("First post", "https://example.com/articles/first")
                    .with_description("body 1")
                    .with_pub_date(ts(2025, 1, 1))
                    .with_author("alice@example.com"),
                FeedItem::new("Second post", "https://example.com/articles/second")
                    .with_pub_date(ts(2025, 3, 15)),
            ],
        }
    }

    #[test]
    fn item_builder_chains() {
        let i = FeedItem::new("t", "https://x/")
            .with_description("d")
            .with_pub_date(ts(2025, 1, 1))
            .with_author("a")
            .with_guid("g");
        assert_eq!(i.title, "t");
        assert_eq!(i.description.as_deref(), Some("d"));
        assert!(i.pub_date.is_some());
        assert_eq!(i.author.as_deref(), Some("a"));
        assert_eq!(i.guid.as_deref(), Some("g"));
    }

    // ---------- RSS ----------

    #[test]
    fn rss_has_declaration_and_channel() {
        let xml = render_rss(&sample_feed());
        assert!(xml.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"));
        assert!(xml.contains("<rss version=\"2.0\">"));
        assert!(xml.contains("<channel>"));
        assert!(xml.contains("<title>Example</title>"));
        assert!(xml.contains("<link>https://example.com/</link>"));
        assert!(xml.contains("<description>Test feed</description>"));
        assert!(xml.contains("<language>en</language>"));
        assert!(xml.ends_with("</rss>\n"));
    }

    #[test]
    fn rss_emits_all_items_in_order() {
        let xml = render_rss(&sample_feed());
        let first_idx = xml.find("First post").unwrap();
        let second_idx = xml.find("Second post").unwrap();
        assert!(first_idx < second_idx, "items should render in input order");
    }

    #[test]
    fn rss_uses_link_as_default_guid() {
        let xml = render_rss(&sample_feed());
        assert!(xml.contains("<guid>https://example.com/articles/first</guid>"));
    }

    #[test]
    fn rss_uses_explicit_guid_when_set() {
        let mut f = sample_feed();
        f.items[0] = FeedItem::new("Pinned", "https://example.com/articles/pinned")
            .with_guid("urn:my-app:pinned-42");
        let xml = render_rss(&f);
        assert!(xml.contains("<guid>urn:my-app:pinned-42</guid>"));
    }

    #[test]
    fn rss_last_build_date_defaults_to_max_pub_date() {
        let xml = render_rss(&sample_feed());
        // sample items: 2025-01-01 and 2025-03-15 → max is 2025-03-15.
        let expected = format_rfc822(ts(2025, 3, 15));
        assert!(
            xml.contains(&format!("<lastBuildDate>{expected}</lastBuildDate>")),
            "lastBuildDate should default to latest pub_date; got: {xml}"
        );
    }

    #[test]
    fn rss_emits_pubdate_in_rfc822() {
        let xml = render_rss(&sample_feed());
        let expected = format_rfc822(ts(2025, 1, 1));
        assert!(
            xml.contains(&format!("<pubDate>{expected}</pubDate>")),
            "pubDate not in RFC 822 shape: {xml}"
        );
    }

    #[test]
    fn rss_omits_optional_fields_when_unset() {
        let f = Feed {
            title: "Minimal".into(),
            link: "https://x/".into(),
            description: "d".into(),
            language: None,
            last_build_date: None,
            items: vec![FeedItem::new("a", "https://x/a")],
        };
        let xml = render_rss(&f);
        assert!(!xml.contains("<language>"));
        assert!(!xml.contains("<lastBuildDate>"));
        // RSS 2.0 requires the channel <description>, so it stays. An
        // item with no description leaves the tag out, so only the
        // channel one appears.
        assert_eq!(
            xml.matches("<description>").count(),
            1,
            "channel description should appear once, item description omitted: {xml}"
        );
        assert!(!xml.contains("<author>"));
        assert!(!xml.contains("<pubDate>"));
    }

    #[test]
    fn rss_escapes_xml_special_chars() {
        let f = Feed {
            title: "Q&A <special>".into(),
            link: "https://example.com/?q=rust&lang=en".into(),
            description: "X > Y < Z".into(),
            language: None,
            last_build_date: None,
            items: vec![],
        };
        let xml = render_rss(&f);
        assert!(xml.contains("<title>Q&amp;A &lt;special&gt;</title>"));
        assert!(xml.contains("https://example.com/?q=rust&amp;lang=en"));
        assert!(xml.contains("<description>X &gt; Y &lt; Z</description>"));
    }

    // ---------- Atom ----------

    #[test]
    fn atom_has_declaration_and_feed_namespace() {
        let xml = render_atom(&sample_feed());
        assert!(xml.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"));
        assert!(xml.contains("<feed xmlns=\"http://www.w3.org/2005/Atom\">"));
        assert!(xml.contains("<title>Example</title>"));
        assert!(xml.contains("<id>https://example.com/</id>"));
        assert!(xml.contains("<link href=\"https://example.com/\" rel=\"alternate\"/>"));
        assert!(xml.ends_with("</feed>\n"));
    }

    #[test]
    fn atom_renders_entries() {
        let xml = render_atom(&sample_feed());
        // Each item becomes an <entry> with title, id and link.
        assert!(xml.contains("<entry>"));
        assert!(xml.contains("<title>First post</title>"));
        assert!(xml.contains("<id>https://example.com/articles/first</id>"));
        assert!(
            xml.contains("<link href=\"https://example.com/articles/first\" rel=\"alternate\"/>")
        );
    }

    #[test]
    fn atom_emits_author_as_nested_name() {
        let xml = render_atom(&sample_feed());
        assert!(
            xml.contains("<author>\n      <name>alice@example.com</name>\n    </author>"),
            "Atom author should render as <author><name>...</name></author>: {xml}"
        );
    }

    #[test]
    fn atom_updated_falls_back_to_max_pub_date() {
        let xml = render_atom(&sample_feed());
        let expected = format_iso8601(ts(2025, 3, 15));
        assert!(
            xml.contains(&format!("<updated>{expected}</updated>")),
            "feed-level <updated> should default to latest item pub_date: {xml}"
        );
    }

    #[test]
    fn atom_entry_updated_falls_back_to_feed_updated() {
        let mut f = sample_feed();
        // Strip pub_dates so we exercise the fallback path.
        for it in &mut f.items {
            it.pub_date = None;
        }
        f.last_build_date = Some(ts(2025, 6, 1));
        let xml = render_atom(&f);
        let expected = format_iso8601(ts(2025, 6, 1));
        // The feed and every entry carry this timestamp.
        let count = xml
            .matches(&format!("<updated>{expected}</updated>"))
            .count();
        assert!(
            count >= 3,
            "expected feed + 2 entries to share updated; got {count}: {xml}"
        );
    }
}