rama-http 0.3.0-rc1

rama http layers, services and other utilities
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
use quick_xml::{
    Writer,
    events::{BytesEnd, BytesStart, BytesText, Event},
};

use super::names::elem;
use super::read::AtomHeader;
use super::types::{
    AtomCategory, AtomContent, AtomEntry, AtomLink, AtomPerson, AtomText, AtomTextKind,
};
use crate::protocols::rss::feed_ext::names::{attr, content};
use crate::protocols::rss::feed_ext::write as ext_write;
use crate::protocols::rss::ns;
use crate::protocols::rss::ser::{
    XmlWriteError, write_cdata_escaped, write_opt_text_elem, write_text_elem,
};

/// Open `<feed>` and emit all feed-level metadata + extension blocks. Stops
/// just before entries so the caller can stream them in.
///
/// Always declares the well-known extension namespaces (`itunes`, `podcast`,
/// `dc`, `media`); see the comment in [`crate::protocols::rss::rss2::write_rss2_channel_open`]
/// for why.
pub(in crate::protocols::rss) fn write_atom_feed_open<W: std::io::Write>(
    w: &mut Writer<W>,
    header: &AtomHeader,
) -> Result<(), XmlWriteError> {
    let mut feed_tag = BytesStart::new(elem::FEED);
    ns::push_xmlns_atom_default(&mut feed_tag);
    ns::push_xmlns_itunes(&mut feed_tag);
    ns::push_xmlns_podcast(&mut feed_tag);
    ns::push_xmlns_dc(&mut feed_tag);
    ns::push_xmlns_media(&mut feed_tag);
    ns::push_xmlns_content(&mut feed_tag);
    ns::push_xmlns_psc(&mut feed_tag);

    w.write_event(Event::Start(feed_tag))?;

    write_text_elem(w, elem::ID, &header.id.to_string())?;
    write_atom_text(w, elem::TITLE, &header.title)?;
    write_text_elem(w, elem::UPDATED, &header.updated.to_string())?;

    for author in &header.authors {
        write_atom_person(w, elem::AUTHOR, author)?;
    }
    for link in &header.links {
        write_atom_link(w, link)?;
    }
    for cat in &header.categories {
        write_atom_category(w, cat)?;
    }
    for contrib in &header.contributors {
        write_atom_person(w, elem::CONTRIBUTOR, contrib)?;
    }
    if let Some(generator) = &header.generator {
        let mut tag = BytesStart::new(elem::GENERATOR);
        if let Some(uri) = &generator.uri {
            let uri = uri.to_string();
            tag.push_attribute((attr::URI, uri.as_str()));
        }
        if let Some(ver) = &generator.version {
            tag.push_attribute((attr::VERSION, ver.as_str()));
        }
        w.write_event(Event::Start(tag))?;
        w.write_event(Event::Text(BytesText::new(&generator.value)))?;
        w.write_event(Event::End(BytesEnd::new(elem::GENERATOR)))?;
    }
    if let Some(icon) = &header.icon {
        write_text_elem(w, elem::ICON, &icon.to_string())?;
    }
    if let Some(logo) = &header.logo {
        write_text_elem(w, elem::LOGO, &logo.to_string())?;
    }
    if let Some(rights) = &header.rights {
        write_atom_text(w, elem::RIGHTS, rights)?;
    }
    if let Some(subtitle) = &header.subtitle {
        write_atom_text(w, elem::SUBTITLE, subtitle)?;
    }

    if let Some(itunes) = &header.extensions.itunes {
        ext_write::write_itunes_feed(w, itunes)?;
    }
    if let Some(podcast) = &header.extensions.podcast {
        ext_write::write_podcast_feed(w, podcast)?;
    }
    if let Some(dc) = &header.extensions.dublin_core {
        ext_write::write_dc_feed_fields(w, dc)?;
    }

    Ok(())
}

/// Close `</feed>`. Pairs with [`write_atom_feed_open`].
pub(in crate::protocols::rss) fn write_atom_feed_close<W: std::io::Write>(
    w: &mut Writer<W>,
) -> Result<(), XmlWriteError> {
    w.write_event(Event::End(BytesEnd::new(elem::FEED)))?;
    Ok(())
}

pub(in crate::protocols::rss) fn write_atom_entry<W: std::io::Write>(
    w: &mut Writer<W>,
    entry: &AtomEntry,
) -> Result<(), XmlWriteError> {
    w.write_event(Event::Start(BytesStart::new(elem::ENTRY)))?;

    write_text_elem(w, elem::ID, &entry.id.to_string())?;
    write_atom_text(w, elem::TITLE, &entry.title)?;
    write_text_elem(w, elem::UPDATED, &entry.updated.to_string())?;

    for author in &entry.authors {
        write_atom_person(w, elem::AUTHOR, author)?;
    }
    for link in &entry.links {
        write_atom_link(w, link)?;
    }
    if let Some(summary) = &entry.summary {
        write_atom_text(w, elem::SUMMARY, summary)?;
    }
    if let Some(content) = &entry.content {
        write_atom_content(w, content)?;
    }
    for cat in &entry.categories {
        write_atom_category(w, cat)?;
    }
    for contrib in &entry.contributors {
        write_atom_person(w, elem::CONTRIBUTOR, contrib)?;
    }
    if let Some(published) = &entry.published {
        write_text_elem(w, elem::PUBLISHED, &published.to_string())?;
    }
    if let Some(rights) = &entry.rights {
        write_atom_text(w, elem::RIGHTS, rights)?;
    }
    if let Some(source) = &entry.source {
        w.write_event(Event::Start(BytesStart::new(elem::SOURCE)))?;
        if let Some(id) = &source.id {
            write_text_elem(w, elem::ID, &id.to_string())?;
        }
        if let Some(title) = &source.title {
            write_atom_text(w, elem::TITLE, title)?;
        }
        if let Some(updated) = &source.updated {
            write_text_elem(w, elem::UPDATED, &updated.to_string())?;
        }
        w.write_event(Event::End(BytesEnd::new(elem::SOURCE)))?;
    }

    if let Some(dc) = &entry.extensions.dublin_core {
        ext_write::write_dc_item_fields(w, dc)?;
    }
    if let Some(itunes) = &entry.extensions.itunes {
        ext_write::write_itunes_item(w, itunes)?;
    }
    if let Some(podcast) = &entry.extensions.podcast {
        ext_write::write_podcast_item(w, podcast)?;
    }
    if let Some(media) = &entry.extensions.media {
        ext_write::write_media_item(w, media)?;
    }
    if let Some(chapters) = &entry.extensions.podlove {
        ext_write::write_podlove_chapters(w, chapters)?;
    }
    // Atom has native <content>, so <content:encoded> is rare in Atom
    // feeds — but the parser fills the field if the input carries it
    // (mixed feeds happen), so the writer must round-trip it through.
    if let Some(c) = &entry.extensions.content
        && let Some(encoded) = &c.encoded
    {
        w.write_event(Event::Start(BytesStart::new(content::ENCODED_TAG)))?;
        write_cdata_escaped(w, encoded)?;
        w.write_event(Event::End(BytesEnd::new(content::ENCODED_TAG)))?;
    }

    w.write_event(Event::End(BytesEnd::new(elem::ENTRY)))?;
    Ok(())
}

fn write_atom_content<W: std::io::Write>(
    w: &mut Writer<W>,
    content: &AtomContent,
) -> Result<(), XmlWriteError> {
    let mut tag = BytesStart::new(elem::CONTENT);
    if let Some(src) = &content.src {
        // Out-of-line content: the MIME type lives in `out_of_line_type`;
        // we fall back to the inline kind ("text"/"html"/"xhtml") if the
        // caller didn't set one, so misuse can never produce a malformed
        // `type=` attribute.
        let src = src.to_string();
        tag.push_attribute((attr::SRC, src.as_str()));
        let mime = content
            .out_of_line_type
            .as_deref()
            .unwrap_or_else(|| content.value.kind.type_attr());
        tag.push_attribute((attr::TYPE, mime));
        w.write_event(Event::Empty(tag))?;
    } else {
        tag.push_attribute((attr::TYPE, content.value.kind.type_attr()));
        w.write_event(Event::Start(tag))?;
        write_atom_text_body(w, &content.value)?;
        w.write_event(Event::End(BytesEnd::new(elem::CONTENT)))?;
    }
    Ok(())
}

fn write_atom_text<W: std::io::Write>(
    w: &mut Writer<W>,
    name: &str,
    text: &AtomText,
) -> Result<(), XmlWriteError> {
    let mut tag = BytesStart::new(name);
    tag.push_attribute((attr::TYPE, text.kind.type_attr()));
    w.write_event(Event::Start(tag))?;
    write_atom_text_body(w, text)?;
    w.write_event(Event::End(BytesEnd::new(name)))?;
    Ok(())
}

fn write_atom_text_body<W: std::io::Write>(
    w: &mut Writer<W>,
    text: &AtomText,
) -> Result<(), XmlWriteError> {
    let s = text.value.as_str();
    match text.kind {
        AtomTextKind::Text => {
            w.write_event(Event::Text(BytesText::new(s)))?;
        }
        AtomTextKind::Html => {
            write_cdata_escaped(w, s)?;
        }
        AtomTextKind::Xhtml => {
            // RFC 4287 §3.1.1.3: xhtml content is a single XHTML-namespaced
            // <div> whose children are real markup, emitted verbatim. Guard
            // against malformed input so we never emit a broken document.
            if !xhtml_well_formed(s) {
                return Err(XmlWriteError::from(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "atom xhtml content is not well-formed XML",
                )));
            }
            let mut div = BytesStart::new(elem::DIV);
            div.push_attribute(("xmlns", ns::XHTML_NS));
            w.write_event(Event::Start(div))?;
            w.write_event(Event::Text(BytesText::from_escaped(s)))?;
            w.write_event(Event::End(BytesEnd::new(elem::DIV)))?;
        }
    }
    Ok(())
}

/// Returns `true` if `fragment` is balanced, well-formed XML *and* contains
/// only the event kinds permitted inside an Atom `type="xhtml"` `<div>`
/// (per RFC 4287 §3.1.1.3): elements, text, CDATA, and comments. Document-
/// level constructs — XML declaration, DOCTYPE, and processing instructions —
/// are not legal inside a content element and would produce invalid XML if
/// emitted verbatim, so they are rejected here even though `quick-xml`'s
/// tokenizer accepts them.
///
/// Validates depth-counted in-place; no allocation. (Earlier versions
/// wrapped the fragment in a synthetic `<x>…</x>` so it would parse as a
/// single rooted document — that allocation is unnecessary, we just need
/// to assert depth ends at zero.)
fn xhtml_well_formed(fragment: &str) -> bool {
    let mut reader = quick_xml::Reader::from_str(fragment);
    let mut depth: i32 = 0;
    loop {
        match reader.read_event() {
            Ok(Event::Eof) => return depth == 0,
            Ok(Event::Start(_)) => depth += 1,
            Ok(Event::End(_)) => {
                depth -= 1;
                if depth < 0 {
                    return false;
                }
            }
            Ok(
                Event::Empty(_)
                | Event::Text(_)
                | Event::CData(_)
                | Event::Comment(_)
                // entity references (`&amp;` etc.) are valid xhtml text content
                | Event::GeneralRef(_),
            ) => {}
            Ok(Event::Decl(_) | Event::DocType(_) | Event::PI(_)) | Err(_) => return false,
        }
    }
}

fn write_atom_person<W: std::io::Write>(
    w: &mut Writer<W>,
    tag_name: &str,
    person: &AtomPerson,
) -> Result<(), XmlWriteError> {
    w.write_event(Event::Start(BytesStart::new(tag_name)))?;
    write_text_elem(w, elem::NAME, &person.name)?;
    write_opt_text_elem(w, elem::EMAIL, person.email.as_deref())?;
    if let Some(uri) = &person.uri {
        write_text_elem(w, elem::URI, &uri.to_string())?;
    }
    w.write_event(Event::End(BytesEnd::new(tag_name)))?;
    Ok(())
}

fn write_atom_link<W: std::io::Write>(
    w: &mut Writer<W>,
    link: &AtomLink,
) -> Result<(), XmlWriteError> {
    let mut tag = BytesStart::new(elem::LINK);
    let href = link.href.to_string();
    tag.push_attribute((attr::HREF, href.as_str()));
    if let Some(rel) = &link.rel {
        tag.push_attribute((attr::REL, rel.as_str()));
    }
    if let Some(type_) = &link.type_ {
        tag.push_attribute((attr::TYPE, type_.as_str()));
    }
    if let Some(lang) = &link.hreflang {
        tag.push_attribute((attr::HREFLANG, lang.as_str()));
    }
    if let Some(title) = &link.title {
        tag.push_attribute((attr::TITLE, title.as_str()));
    }
    if let Some(len) = link.length {
        tag.push_attribute((attr::LENGTH, len.to_string().as_str()));
    }
    w.write_event(Event::Empty(tag))?;
    Ok(())
}

fn write_atom_category<W: std::io::Write>(
    w: &mut Writer<W>,
    cat: &AtomCategory,
) -> Result<(), XmlWriteError> {
    let mut tag = BytesStart::new(elem::CATEGORY);
    tag.push_attribute((attr::TERM, cat.term.as_str()));
    if let Some(scheme) = &cat.scheme {
        tag.push_attribute((attr::SCHEME, scheme.as_str()));
    }
    if let Some(label) = &cat.label {
        tag.push_attribute((attr::LABEL, label.as_str()));
    }
    w.write_event(Event::Empty(tag))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use jiff::Timestamp;
    use rama_net::uri::Uri;

    use crate::protocols::rss::atom::types::{AtomContent, AtomEntry, AtomFeed, AtomText};

    #[test]
    fn builder_enforces_all_required_fields() {
        let ts = Timestamp::now();
        let feed = AtomFeed::builder()
            .updated(ts)
            .id(Uri::from_static("urn:uuid:test"))
            .title("Test Feed")
            .build();
        assert_eq!(feed.id.to_string(), "urn:uuid:test");
        assert_eq!(feed.title, AtomText::text("Test Feed"));
        assert_eq!(feed.updated, ts);
    }

    #[tokio::test]
    #[cfg(feature = "html")]
    async fn feed_serializes_to_valid_xml() {
        use crate::protocols::html::p;
        use crate::protocols::rss::atom::types::{AtomLink, AtomPerson};

        let ts = Timestamp::now();
        let feed = AtomFeed::builder()
            .id(Uri::from_static("https://example.com/feed"))
            .title("My Blog")
            .updated(ts)
            .with_author(AtomPerson::new("Author"))
            .with_link(AtomLink::alternate(Uri::from_static("https://example.com")))
            .with_entry(
                AtomEntry::new(Uri::from_static("https://example.com/1"), "Post 1", ts)
                    .with_content(AtomContent::html(p!("Hello"))),
            )
            .build();

        let xml_bytes = feed.to_xml().await.expect("serialize");
        let xml = String::from_utf8(xml_bytes).expect("utf-8");
        assert!(xml.contains("<?xml"));
        assert!(xml.contains(r#"xmlns="http://www.w3.org/2005/Atom""#));
        assert!(xml.contains("<id>https://example.com/feed</id>"));
        assert!(xml.contains("My Blog"));
        assert!(xml.contains("<entry>"));
        assert!(xml.contains("Post 1"));
    }

    #[test]
    #[cfg(feature = "html")]
    fn atom_text_preserves_type() {
        use crate::protocols::html::b;

        let text = AtomText::html(b!("bold"));
        assert_eq!(text.kind.type_attr(), "html");
        assert_eq!(text.value, "<b>bold</b>");
    }

    #[tokio::test]
    async fn xhtml_malformed_content_errors() {
        let ts = Timestamp::UNIX_EPOCH;
        let bad = AtomFeed::builder()
            .id(Uri::from_static("urn:f"))
            .title("T")
            .updated(ts)
            .with_entry(
                AtomEntry::new(Uri::from_static("urn:1"), "E", ts).with_content(AtomContent {
                    value: AtomText::xhtml("<p>broken"),
                    src: None,
                    out_of_line_type: None,
                }),
            )
            .build();
        bad.to_xml()
            .await
            .expect_err("malformed xhtml should fail to serialize");

        let ok = AtomFeed::builder()
            .id(Uri::from_static("urn:f"))
            .title("T")
            .updated(ts)
            .with_entry(
                AtomEntry::new(Uri::from_static("urn:1"), "E", ts).with_content(AtomContent {
                    value: AtomText::xhtml("<p>ok</p>"),
                    src: None,
                    out_of_line_type: None,
                }),
            )
            .build();
        ok.to_xml().await.expect("valid xhtml should serialize");
    }

    #[tokio::test]
    async fn xhtml_content_wrapped_in_namespaced_div() {
        let ts = Timestamp::UNIX_EPOCH;
        let feed = AtomFeed::builder()
            .id(Uri::from_static("urn:f"))
            .title("T")
            .updated(ts)
            .with_entry(
                AtomEntry::new(Uri::from_static("urn:1"), "E", ts).with_content(AtomContent {
                    value: AtomText::xhtml("<p>hi</p>"),
                    src: None,
                    out_of_line_type: None,
                }),
            )
            .build();
        let xml_bytes = feed.to_xml().await.expect("serialize");
        let xml = String::from_utf8(xml_bytes).expect("utf-8");
        assert!(
            xml.contains(
                r#"<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>hi</p></div></content>"#
            ),
            "{xml}"
        );
    }
}