1use 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
26pub const SITEMAP_INDEX_PATH: &str = "/sitemap.xml";
28
29pub const MAX_URLS_PER_SITEMAP: usize = 45_000;
32
33pub const MAX_BYTES_PER_SITEMAP: usize = 45 * 1024 * 1024;
37
38#[derive(Debug, thiserror::Error)]
40pub enum SitemapError {
41 #[error("invalid sitemap entry for `{location}`")]
43 Url {
44 location: String,
45 #[source]
46 source: sitemap_rs::url_error::UrlError,
47 },
48
49 #[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 #[error("invalid sitemap index ({count} sitemaps)")]
60 Index {
61 count: usize,
62 #[source]
63 source: sitemap_rs::sitemap_index_error::SitemapIndexError,
64 },
65
66 #[error("failed to serialize the sitemap")]
68 Write {
69 #[source]
70 source: std::io::Error,
71 },
72
73 #[error("the serialized sitemap was not valid UTF-8")]
76 Encoding,
77}
78
79#[derive(Debug, Clone)]
86pub struct SitemapUrl {
87 path: String,
88 last_modified: Option<Timestamp>,
89 images: Vec<String>,
90}
91
92impl SitemapUrl {
93 #[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 #[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 #[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 #[must_use]
128 pub fn path(&self) -> &str {
129 &self.path
130 }
131
132 #[must_use]
134 pub const fn last_modified(&self) -> Option<Timestamp> {
135 self.last_modified
136 }
137
138 #[must_use]
140 pub fn images(&self) -> &[String] {
141 &self.images
142 }
143
144 #[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 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#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct SitemapSet {
193 index: String,
194 chunks: Vec<String>,
195}
196
197impl SitemapSet {
198 #[must_use]
200 pub fn index(&self) -> &str {
201 &self.index
202 }
203
204 #[must_use]
207 pub fn chunks(&self) -> &[String] {
208 &self.chunks
209 }
210
211 #[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#[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 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
273fn 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 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
308fn 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
318fn 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}