Skip to main content

webserver_base/sitemap/
mod.rs

1//! Sitemap generation: always an index, always at least one url set.
2//!
3//! Which URLs a site has comes from [`Pages`](crate::webserver::Pages), so the
4//! sitemap is derived from the route table rather than kept beside it.
5//!
6//! The shape is deliberately uniform. `/sitemap.xml` is a `<sitemapindex>` on a
7//! three-page site and on a three-million-page one, so `robots.txt` and any
8//! Search Console submission point at one URL forever. A site that grows past
9//! the protocol's 50,000-URL limit simply gains another `/sitemap-N.xml` inside
10//! the index; nothing outside the server changes, and nothing has to be
11//! resubmitted. The alternative — a bare `<urlset>` that silently becomes an
12//! index at the boundary — invalidates that submission at exactly the moment
13//! the site matters most.
14
15use jiff::Timestamp;
16use jiff_02::Zoned;
17use jiff_02::tz::TimeZone;
18use sitemap_rs::image::Image;
19use sitemap_rs::sitemap::Sitemap;
20use sitemap_rs::sitemap_index::SitemapIndex;
21use sitemap_rs::url::Url;
22use sitemap_rs::url_builder::UrlBuilder;
23use sitemap_rs::url_set::UrlSet;
24use tracing::{debug, instrument};
25
26/// The route the sitemap index is served at.
27pub const SITEMAP_INDEX_PATH: &str = "/sitemap.xml";
28
29/// URLs per url set. The protocol allows 50,000; the margin absorbs the
30/// difference between an entry's typical and worst-case size.
31pub const MAX_URLS_PER_SITEMAP: usize = 45_000;
32
33/// Bytes per url set. The protocol allows 50 MB uncompressed. `sitemap-rs`
34/// enforces only the URL count, so a set of image-heavy entries can pass that
35/// check and still be rejected — this is the guard for that case.
36pub const MAX_BYTES_PER_SITEMAP: usize = 45 * 1024 * 1024;
37
38/// Why a sitemap could not be produced.
39#[derive(Debug, thiserror::Error)]
40pub enum SitemapError {
41    /// A single `<url>` entry was rejected.
42    #[error("invalid sitemap entry for `{location}`")]
43    Url {
44        location: String,
45        #[source]
46        source: sitemap_rs::url_error::UrlError,
47    },
48
49    /// A `<urlset>` was rejected.
50    #[error("invalid sitemap url set ({count} urls)")]
51    UrlSet {
52        count: usize,
53        #[source]
54        source: sitemap_rs::url_set_error::UrlSetError,
55    },
56
57    /// The `<sitemapindex>` was rejected — more than 50,000 url sets, which is
58    /// 2.25 billion URLs.
59    #[error("invalid sitemap index ({count} sitemaps)")]
60    Index {
61        count: usize,
62        #[source]
63        source: sitemap_rs::sitemap_index_error::SitemapIndexError,
64    },
65
66    /// The XML could not be serialized.
67    #[error("failed to serialize the sitemap")]
68    Write {
69        #[source]
70        source: std::io::Error,
71    },
72
73    /// Serialized XML was not valid UTF-8, which cannot happen for input this
74    /// crate produces.
75    #[error("the serialized sitemap was not valid UTF-8")]
76    Encoding,
77}
78
79/// One entry in a sitemap. Holds a site-relative path; the origin is prepended
80/// at build time, so a URL cannot be listed under the wrong host.
81///
82/// Deliberately absent: `<changefreq>` and `<priority>`. Google ignores both —
83/// priority is subjective and change frequency is guessed — so carrying them
84/// would be markup with no consumer.
85#[derive(Debug, Clone)]
86pub struct SitemapUrl {
87    path: String,
88    last_modified: Option<Timestamp>,
89    images: Vec<String>,
90}
91
92impl SitemapUrl {
93    /// An entry for a site-relative `path`, e.g. `/blog/rust-tips`.
94    #[must_use]
95    pub fn new(path: impl Into<String>) -> Self {
96        Self {
97            path: path.into(),
98            last_modified: None,
99            images: Vec::new(),
100        }
101    }
102
103    /// Sets `<lastmod>` for this page specifically.
104    ///
105    /// Prefer a real modification date. Google uses `lastmod` only when it is
106    /// "consistently and verifiably accurate" — it fetches the page and checks
107    /// — and one bad pattern discredits the whole file, so a made-up date is
108    /// worse than none.
109    #[must_use]
110    pub const fn with_last_modified(mut self, last_modified: Timestamp) -> Self {
111        self.last_modified = Some(last_modified);
112        self
113    }
114
115    /// Adds `<image:image>` entries, as site-relative or absolute URLs.
116    #[must_use]
117    pub fn extend_images<I, S>(mut self, images: I) -> Self
118    where
119        I: IntoIterator<Item = S>,
120        S: Into<String>,
121    {
122        self.images.extend(images.into_iter().map(Into::into));
123        self
124    }
125
126    /// The site-relative path.
127    #[must_use]
128    pub fn path(&self) -> &str {
129        &self.path
130    }
131
132    /// The `<lastmod>` override, if one was set.
133    #[must_use]
134    pub const fn last_modified(&self) -> Option<Timestamp> {
135        self.last_modified
136    }
137
138    /// The `<image:image>` entries, as supplied.
139    #[must_use]
140    pub fn images(&self) -> &[String] {
141        &self.images
142    }
143
144    /// Rewrites every image path through `resolve`.
145    ///
146    /// Images are declared by their logical path but served only at their
147    /// content-hashed one, so without this the sitemap advertises URLs that
148    /// 404 — and an image sitemap full of dead links is worse than none.
149    #[must_use]
150    pub fn map_images<F>(mut self, resolve: F) -> Self
151    where
152        F: Fn(&str) -> String,
153    {
154        self.images = self.images.iter().map(|image| resolve(image)).collect();
155        self
156    }
157
158    /// Builds the `sitemap-rs` entry, resolving `path` against `base_url`.
159    fn build(
160        &self,
161        base_url: &str,
162        fallback_last_modified: Option<Timestamp>,
163    ) -> Result<Url, SitemapError> {
164        let location: String = absolute(base_url, &self.path);
165
166        let mut builder: UrlBuilder = Url::builder(location.clone());
167        if let Some(last_modified) = self.last_modified.or(fallback_last_modified) {
168            builder.last_modified(to_zoned(last_modified));
169        }
170
171        if !self.images.is_empty() {
172            builder.images(
173                self.images
174                    .iter()
175                    .map(|image| Image::new(absolute(base_url, image)))
176                    .collect(),
177            );
178        }
179
180        builder
181            .build()
182            .map_err(|source| SitemapError::Url { location, source })
183    }
184}
185
186/// A complete sitemap set: one index naming one or more url sets.
187///
188/// Held in memory and served from there. Nothing is written to disk, so a
189/// production image needs no writable filesystem, and there is no generated
190/// file to hash, cache, or accidentally commit.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct SitemapSet {
193    index: String,
194    chunks: Vec<String>,
195}
196
197impl SitemapSet {
198    /// The `<sitemapindex>` document, served at [`SITEMAP_INDEX_PATH`].
199    #[must_use]
200    pub fn index(&self) -> &str {
201        &self.index
202    }
203
204    /// The `<urlset>` documents, in order. Chunk `n` is served at
205    /// `/sitemap-{n+1}.xml`.
206    #[must_use]
207    pub fn chunks(&self) -> &[String] {
208        &self.chunks
209    }
210
211    /// Every path this set is served at, index first.
212    ///
213    /// Index first is load-bearing for `robots.txt`: Google discards anything
214    /// past 500 KiB, and truncation is positional, so the one line that must
215    /// survive goes at the top.
216    #[must_use]
217    pub fn paths(&self) -> Vec<String> {
218        let mut paths: Vec<String> = vec![String::from(SITEMAP_INDEX_PATH)];
219        paths.extend((1..=self.chunks.len()).map(|n| format!("/sitemap-{n}.xml")));
220        paths
221    }
222}
223
224/// Builds the sitemap index and its url sets for `urls`.
225///
226/// `fallback_last_modified` is used for entries that name no date of their own;
227/// pass `None` to omit `<lastmod>` rather than assert something unverifiable.
228///
229/// # Errors
230///
231/// [`SitemapError`] if an entry, a url set, or the index is invalid, or if the
232/// XML cannot be serialized.
233#[instrument(skip_all)]
234pub fn build_sitemaps(
235    base_url: &str,
236    urls: &[SitemapUrl],
237    fallback_last_modified: Option<Timestamp>,
238) -> Result<SitemapSet, SitemapError> {
239    let mut chunks: Vec<String> = Vec::new();
240
241    // An empty site still gets one (empty) url set, so the index is never a
242    // dangling reference and the served shape never varies.
243    for batch in urls.chunks(MAX_URLS_PER_SITEMAP).chain(if urls.is_empty() {
244        Some([].as_slice())
245    } else {
246        None
247    }) {
248        chunks.extend(render_url_set(base_url, batch, fallback_last_modified)?);
249    }
250
251    let sitemaps: Vec<Sitemap> = (1..=chunks.len())
252        .map(|n| {
253            let location: String = absolute(base_url, &format!("/sitemap-{n}.xml"));
254            let last_modified: Option<Zoned> = fallback_last_modified.map(to_zoned);
255            Ok(Sitemap::new(location, last_modified))
256        })
257        .collect::<Result<Vec<Sitemap>, SitemapError>>()?;
258
259    let count: usize = sitemaps.len();
260    let index: SitemapIndex =
261        SitemapIndex::new(sitemaps).map_err(|source| SitemapError::Index { count, source })?;
262
263    let mut buffer: Vec<u8> = Vec::new();
264    index
265        .write(&mut buffer)
266        .map_err(|source| SitemapError::Write { source })?;
267    let index: String = String::from_utf8(buffer).map_err(|_| SitemapError::Encoding)?;
268
269    debug!("built {} url(s) across {count} sitemap(s)", urls.len());
270    Ok(SitemapSet { index, chunks })
271}
272
273/// Serializes one batch, splitting it further if the result exceeds the
274/// protocol's byte limit.
275fn render_url_set(
276    base_url: &str,
277    batch: &[SitemapUrl],
278    fallback_last_modified: Option<Timestamp>,
279) -> Result<Vec<String>, SitemapError> {
280    let built: Vec<Url> = batch
281        .iter()
282        .map(|url| url.build(base_url, fallback_last_modified))
283        .collect::<Result<Vec<Url>, SitemapError>>()?;
284
285    let count: usize = built.len();
286    let url_set: UrlSet =
287        UrlSet::new(built).map_err(|source| SitemapError::UrlSet { count, source })?;
288
289    let mut buffer: Vec<u8> = Vec::new();
290    url_set
291        .write(&mut buffer)
292        .map_err(|source| SitemapError::Write { source })?;
293
294    if buffer.len() <= MAX_BYTES_PER_SITEMAP || batch.len() < 2 {
295        return Ok(vec![
296            String::from_utf8(buffer).map_err(|_| SitemapError::Encoding)?,
297        ]);
298    }
299
300    // Too large despite an acceptable URL count — image-heavy entries. Halve
301    // and retry; each half is re-measured, so this terminates.
302    let (left, right) = batch.split_at(batch.len() / 2);
303    let mut rendered: Vec<String> = render_url_set(base_url, left, fallback_last_modified)?;
304    rendered.extend(render_url_set(base_url, right, fallback_last_modified)?);
305    Ok(rendered)
306}
307
308/// Converts a `<lastmod>` date to the type `sitemap-rs` takes, which is a
309/// jiff 0.2 `Zoned`: that crate is the only user of jiff 0.2 here, so the
310/// conversion goes through unix seconds. UTC in, UTC out, so it is written with
311/// a `+00:00` offset. Whole seconds only: `<lastmod>` never carried a fraction.
312fn to_zoned(date: Timestamp) -> Zoned {
313    jiff_02::Timestamp::new(date.as_second(), 0)
314        .unwrap_or(jiff_02::Timestamp::UNIX_EPOCH)
315        .to_zoned(TimeZone::UTC)
316}
317
318/// Joins a site origin and a path, tolerating a slash on either side or both.
319fn absolute(base_url: &str, path: &str) -> String {
320    if path.starts_with("http://") || path.starts_with("https://") {
321        return path.to_string();
322    }
323    let base: &str = base_url.trim_end_matches('/');
324    let path: &str = path.trim_start_matches('/');
325    if path.is_empty() {
326        format!("{base}/")
327    } else {
328        format!("{base}/{path}")
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use jiff::Timestamp;
335
336    use super::{SitemapSet, SitemapUrl, absolute, build_sitemaps};
337
338    #[test]
339    fn joining_never_doubles_or_drops_a_slash() {
340        let cases: [(&str, &str, &str); 5] = [
341            ("https://a.com", "/blog", "https://a.com/blog"),
342            ("https://a.com/", "/blog", "https://a.com/blog"),
343            ("https://a.com", "blog", "https://a.com/blog"),
344            ("https://a.com", "/", "https://a.com/"),
345            ("https://a.com", "", "https://a.com/"),
346        ];
347        for (base, path, expected) in cases {
348            let actual: String = absolute(base, path);
349            assert_eq!(expected, actual, "base {base:?} path {path:?}");
350        }
351    }
352
353    #[test]
354    fn an_absolute_image_url_is_left_alone() {
355        let expected: String = String::from("https://cdn.example.com/card.png");
356        let actual: String = absolute("https://a.com", "https://cdn.example.com/card.png");
357        assert_eq!(expected, actual);
358    }
359
360    #[test]
361    fn a_small_site_still_gets_an_index_so_the_shape_never_changes() {
362        let urls: Vec<SitemapUrl> = vec![SitemapUrl::new("/"), SitemapUrl::new("/blog")];
363        let set: SitemapSet =
364            build_sitemaps("https://www.example.com", &urls, None).expect("builds");
365
366        assert!(set.index().contains("<sitemapindex"));
367        assert!(
368            set.index()
369                .contains("https://www.example.com/sitemap-1.xml")
370        );
371
372        let expected: usize = 1;
373        let actual: usize = set.chunks().len();
374        assert_eq!(expected, actual);
375
376        assert!(set.chunks()[0].contains("<loc>https://www.example.com/</loc>"));
377        assert!(set.chunks()[0].contains("<loc>https://www.example.com/blog</loc>"));
378    }
379
380    #[test]
381    fn a_site_with_no_pages_still_produces_a_well_formed_pair() {
382        let set: SitemapSet = build_sitemaps("https://www.example.com", &[], None).expect("builds");
383
384        let expected: usize = 1;
385        let actual: usize = set.chunks().len();
386        assert_eq!(expected, actual);
387        assert!(set.index().contains("<sitemapindex"));
388    }
389
390    #[test]
391    fn urls_beyond_the_limit_spill_into_another_url_set() {
392        let urls: Vec<SitemapUrl> = (0..super::MAX_URLS_PER_SITEMAP + 10)
393            .map(|n| SitemapUrl::new(format!("/page/{n}")))
394            .collect();
395        let set: SitemapSet =
396            build_sitemaps("https://www.example.com", &urls, None).expect("builds");
397
398        let expected: usize = 2;
399        let actual: usize = set.chunks().len();
400        assert_eq!(expected, actual);
401        assert!(
402            set.index()
403                .contains("https://www.example.com/sitemap-2.xml")
404        );
405    }
406
407    #[test]
408    fn the_index_path_comes_first_so_it_survives_truncation() {
409        let urls: Vec<SitemapUrl> = (0..=super::MAX_URLS_PER_SITEMAP)
410            .map(|n| SitemapUrl::new(format!("/page/{n}")))
411            .collect();
412        let set: SitemapSet =
413            build_sitemaps("https://www.example.com", &urls, None).expect("builds");
414
415        let expected: Vec<String> = vec![
416            String::from("/sitemap.xml"),
417            String::from("/sitemap-1.xml"),
418            String::from("/sitemap-2.xml"),
419        ];
420        let actual: Vec<String> = set.paths();
421        assert_eq!(expected, actual);
422    }
423
424    #[test]
425    fn a_timestamp_converts_to_the_sitemap_crates_zoned_without_shifting_the_instant() {
426        let date: Timestamp = "2026-01-02T03:04:05.678Z".parse().expect("a real instant");
427
428        let zoned: super::Zoned = super::to_zoned(date);
429
430        assert_eq!(date.as_second(), zoned.timestamp().as_second());
431        assert_eq!(0, zoned.timestamp().subsec_nanosecond());
432        assert_eq!("2026-01-02T03:04:05+00:00[UTC]", zoned.to_string());
433    }
434
435    #[test]
436    fn a_page_without_a_date_gets_no_lastmod_rather_than_a_false_one() {
437        let urls: Vec<SitemapUrl> = vec![SitemapUrl::new("/")];
438        let set: SitemapSet =
439            build_sitemaps("https://www.example.com", &urls, None).expect("builds");
440
441        assert!(!set.chunks()[0].contains("<lastmod>"));
442    }
443
444    #[test]
445    fn a_page_date_wins_over_the_site_wide_fallback() {
446        let page_date: Timestamp = "2026-01-02T03:04:05Z".parse().expect("a real instant");
447        let site_date: Timestamp = "2020-01-01T00:00:00Z".parse().expect("a real instant");
448
449        let urls: Vec<SitemapUrl> = vec![
450            SitemapUrl::new("/blog").with_last_modified(page_date),
451            SitemapUrl::new("/"),
452        ];
453        let set: SitemapSet =
454            build_sitemaps("https://www.example.com", &urls, Some(site_date)).expect("builds");
455
456        assert!(set.chunks()[0].contains("2026-01-02"));
457        assert!(set.chunks()[0].contains("2020-01-01"));
458    }
459
460    #[test]
461    fn a_utc_date_is_written_with_seconds_and_an_explicit_offset() {
462        let date: Timestamp = "2026-01-02T03:04:05Z".parse().expect("a real instant");
463        let urls: Vec<SitemapUrl> = vec![SitemapUrl::new("/").with_last_modified(date)];
464        let set: SitemapSet =
465            build_sitemaps("https://www.example.com", &urls, Some(date)).expect("builds");
466
467        assert!(
468            set.chunks()[0].contains("<lastmod>2026-01-02T03:04:05+00:00</lastmod>"),
469            "{}",
470            set.chunks()[0]
471        );
472        assert!(
473            set.index()
474                .contains("<lastmod>2026-01-02T03:04:05+00:00</lastmod>"),
475            "{}",
476            set.index()
477        );
478    }
479
480    #[test]
481    fn images_are_rewritten_to_the_paths_they_are_actually_served_at() {
482        let url: SitemapUrl = SitemapUrl::new("/")
483            .extend_images(["/static/image/social/card.webp"])
484            .map_images(|image| image.replace("card.webp", "card.abc123.webp"));
485
486        let expected: Vec<String> = vec![String::from("/static/image/social/card.abc123.webp")];
487        let actual: Vec<String> = url.images().to_vec();
488        assert_eq!(expected, actual);
489    }
490
491    #[test]
492    fn images_are_resolved_against_the_site_origin() {
493        let urls: Vec<SitemapUrl> =
494            vec![SitemapUrl::new("/").extend_images(["/static/image/social/card.webp"])];
495        let set: SitemapSet =
496            build_sitemaps("https://www.example.com", &urls, None).expect("builds");
497
498        assert!(set.chunks()[0].contains("https://www.example.com/static/image/social/card.webp"));
499    }
500}