essence-engine 0.2.0

A fast web retrieval engine with HTTP-to-browser fallback, producing LLM-ready Markdown
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
use crate::error::{Result, ScrapeError};
use reqwest::Client;
use std::collections::HashSet;
use std::future::Future;
use std::pin::Pin;
use tracing::{debug, info};
use url::Url;

/// Sitemap parser
pub struct SitemapParser {
    client: Client,
}

impl SitemapParser {
    /// Create a new SitemapParser
    pub fn new() -> Result<Self> {
        let client = Client::builder()
            .user_agent("Mozilla/5.0 (compatible; Essence/0.1.0; +https://essence.foundation)")
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(|e| ScrapeError::Internal(format!("Failed to build HTTP client: {}", e)))?;

        Ok(Self { client })
    }

    /// Create a new SitemapParser with a custom HTTP client
    pub fn with_client(client: Client) -> Self {
        Self { client }
    }

    /// Fetch sitemap with optional caching
    ///
    /// - `cache_ttl`: None = no cache, Some(secs) = cache for N seconds (currently ignored, reserved for future use)
    pub async fn fetch_with_cache(
        &self,
        base_url: &str,
        _cache_ttl: Option<u64>,
    ) -> Result<Vec<String>> {
        self.fetch_sitemap_internal(base_url).await
    }

    /// Fetch and parse sitemap.xml from a base URL (internal implementation)
    async fn fetch_sitemap_internal(&self, base_url: &str) -> Result<Vec<String>> {
        let _base = Url::parse(base_url)
            .map_err(|e| ScrapeError::InvalidUrl(format!("Invalid base URL: {}", e)))?;

        let mut all_urls = HashSet::new();

        // Strategy 1: Check robots.txt for Sitemap directive
        if let Ok(sitemap_url) = self.check_robots_txt(base_url).await {
            info!("Found sitemap URL in robots.txt: {}", sitemap_url);
            if self
                .fetch_and_parse_sitemap(&sitemap_url, &mut all_urls)
                .await
                .is_ok()
                && !all_urls.is_empty()
            {
                info!(
                    "Successfully fetched {} URLs from robots.txt sitemap",
                    all_urls.len()
                );
                return Ok(all_urls.into_iter().collect());
            }
        }

        // Strategy 2: Try common sitemap locations
        let sitemap_urls = vec![
            format!("{}/sitemap.xml", base_url.trim_end_matches('/')),
            format!("{}/sitemap_index.xml", base_url.trim_end_matches('/')),
            format!("{}/sitemap-index.xml", base_url.trim_end_matches('/')),
        ];

        for sitemap_url in sitemap_urls {
            debug!("Trying sitemap location: {}", sitemap_url);
            match self
                .fetch_and_parse_sitemap(&sitemap_url, &mut all_urls)
                .await
            {
                Ok(_) => {
                    if !all_urls.is_empty() {
                        info!(
                            "Found {} URLs from sitemap at {}",
                            all_urls.len(),
                            sitemap_url
                        );
                        break; // Found a sitemap, stop trying
                    }
                }
                Err(e) => {
                    debug!("Failed to fetch sitemap at {}: {}", sitemap_url, e);
                    continue;
                }
            }
        }

        Ok(all_urls.into_iter().collect())
    }

    /// Check robots.txt for Sitemap directive
    async fn check_robots_txt(&self, base_url: &str) -> Result<String> {
        let robots_url = format!("{}/robots.txt", base_url.trim_end_matches('/'));
        debug!("Checking robots.txt at: {}", robots_url);

        let response = self
            .client
            .get(&robots_url)
            .timeout(std::time::Duration::from_secs(10))
            .send()
            .await
            .map_err(ScrapeError::RequestFailed)?;

        if !response.status().is_success() {
            return Err(ScrapeError::Internal(format!(
                "robots.txt returned status: {}",
                response.status()
            )));
        }

        let text = response
            .text()
            .await
            .map_err(|e| ScrapeError::Internal(format!("Failed to read robots.txt: {}", e)))?;

        // Parse "Sitemap: <url>" directive (case-insensitive)
        for line in text.lines() {
            let trimmed = line.trim();
            if trimmed.to_lowercase().starts_with("sitemap:") {
                if let Some(url) = trimmed.split_whitespace().nth(1) {
                    return Ok(url.to_string());
                }
            }
        }

        Err(ScrapeError::Internal(
            "No sitemap directive in robots.txt".to_string(),
        ))
    }

    /// Fetch and parse a single sitemap URL
    fn fetch_and_parse_sitemap<'a>(
        &'a self,
        sitemap_url: &'a str,
        all_urls: &'a mut HashSet<String>,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        Box::pin(async move {
            let response = self
                .client
                .get(sitemap_url)
                .timeout(std::time::Duration::from_secs(10))
                .send()
                .await
                .map_err(ScrapeError::RequestFailed)?;

            if !response.status().is_success() {
                return Err(ScrapeError::Internal(format!(
                    "Sitemap returned status: {}",
                    response.status()
                )));
            }

            let content = response
                .text()
                .await
                .map_err(|e| ScrapeError::Internal(format!("Failed to read sitemap content: {}", e)))?;

            self.parse_sitemap_content(&content, all_urls).await
        })
    }

    /// Parse sitemap XML content and extract URLs
    fn parse_sitemap_content<'a>(
        &'a self,
        content: &'a str,
        all_urls: &'a mut HashSet<String>,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        Box::pin(async move {
            // Check if this is a sitemap index (contains <sitemapindex> tag)
            if content.contains("<sitemapindex") {
                debug!("Detected sitemap index format");
                let sitemap_pattern =
                    regex::Regex::new(r"(?s)<sitemap[^>]*>.*?<loc>([^<]+)</loc>.*?</sitemap>")
                        .map_err(|e| ScrapeError::Internal(format!("Regex error: {}", e)))?;

                let mut sitemap_count = 0;
                for cap in sitemap_pattern.captures_iter(content) {
                    if let Some(url_match) = cap.get(1) {
                        let url = url_match.as_str().trim();
                        debug!("Found nested sitemap: {}", url);
                        sitemap_count += 1;
                        match self.fetch_and_parse_sitemap(url, all_urls).await {
                            Ok(_) => debug!("Successfully parsed nested sitemap: {}", url),
                            Err(e) => debug!("Failed to parse nested sitemap {}: {}", url, e),
                        }
                    }
                }
                info!(
                    "Processed {} nested sitemaps from sitemap index",
                    sitemap_count
                );
            } else if content.contains("<sitemap>") {
                // Fallback: old-style detection for sitemap indexes without proper <sitemapindex> wrapper
                debug!("Detected sitemap index format (legacy)");
                let sitemap_pattern =
                    regex::Regex::new(r"(?s)<sitemap[^>]*>.*?<loc>([^<]+)</loc>.*?</sitemap>")
                        .map_err(|e| ScrapeError::Internal(format!("Regex error: {}", e)))?;

                for cap in sitemap_pattern.captures_iter(content) {
                    if let Some(url_match) = cap.get(1) {
                        let url = url_match.as_str().trim();
                        debug!("Found nested sitemap: {}", url);
                        let _ = self.fetch_and_parse_sitemap(url, all_urls).await;
                    }
                }
            } else {
                // This is a regular sitemap (urlset), extract URLs
                debug!("Detected regular sitemap format");
                let url_pattern =
                    regex::Regex::new(r"(?s)<url[^>]*>.*?<loc>([^<]+)</loc>.*?</url>")
                        .map_err(|e| ScrapeError::Internal(format!("Regex error: {}", e)))?;

                for cap in url_pattern.captures_iter(content) {
                    if let Some(url_match) = cap.get(1) {
                        let url = url_match.as_str().trim().to_string();
                        all_urls.insert(url);
                    }
                }
            }

            Ok(())
        })
    }
}

/// Backward-compatible function API for fetching sitemaps without caching
pub async fn fetch_sitemap(base_url: &str, client: &Client) -> Result<Vec<String>> {
    let parser = SitemapParser::with_client(client.clone());
    parser.fetch_sitemap_internal(base_url).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    /// Cache entry for sitemap URLs (used for serialization tests)
    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct SitemapCacheEntry {
        urls: Vec<String>,
        fetched_at: i64,
        ttl_seconds: u64,
    }

    #[test]
    fn test_parse_regular_sitemap() {
        let sitemap_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com/page1</loc>
  </url>
  <url>
    <loc>https://example.com/page2</loc>
  </url>
</urlset>"#;

        let mut urls = HashSet::new();
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let parser = SitemapParser::new().unwrap();
            let result = parser.parse_sitemap_content(sitemap_xml, &mut urls).await;
            assert!(result.is_ok());
        });

        assert_eq!(urls.len(), 2);
        assert!(urls.contains("https://example.com/page1"));
        assert!(urls.contains("https://example.com/page2"));
    }

    #[test]
    fn test_detect_sitemap_index() {
        let sitemap_index_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <sitemap>
    <loc>https://example.com/sitemap1.xml</loc>
  </sitemap>
  <sitemap>
    <loc>https://example.com/sitemap2.xml</loc>
  </sitemap>
</sitemapindex>"#;

        assert!(sitemap_index_xml.contains("<sitemapindex"));
        assert!(sitemap_index_xml.contains("<sitemap>"));
    }

    #[test]
    fn test_parse_sitemap_index_extracts_sitemap_urls() {
        let sitemap_index_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <sitemap>
    <loc>https://example.com/sitemap-posts.xml</loc>
    <lastmod>2025-10-01T00:00:00Z</lastmod>
  </sitemap>
  <sitemap>
    <loc>https://example.com/sitemap-pages.xml</loc>
    <lastmod>2025-10-02T00:00:00Z</lastmod>
  </sitemap>
  <sitemap>
    <loc>https://example.com/sitemap-products.xml</loc>
  </sitemap>
</sitemapindex>"#;

        let sitemap_pattern =
            regex::Regex::new(r"(?s)<sitemap[^>]*>.*?<loc>([^<]+)</loc>.*?</sitemap>").unwrap();
        let sitemap_urls: Vec<String> = sitemap_pattern
            .captures_iter(sitemap_index_xml)
            .filter_map(|cap| cap.get(1).map(|m| m.as_str().to_string()))
            .collect();

        assert_eq!(sitemap_urls.len(), 3);
        assert!(sitemap_urls.contains(&"https://example.com/sitemap-posts.xml".to_string()));
        assert!(sitemap_urls.contains(&"https://example.com/sitemap-pages.xml".to_string()));
        assert!(sitemap_urls.contains(&"https://example.com/sitemap-products.xml".to_string()));
    }

    #[test]
    fn test_parse_regular_sitemap_doesnt_match_url_in_sitemap_index() {
        let sitemap_index_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <sitemap>
    <loc>https://example.com/sitemap-posts.xml</loc>
  </sitemap>
</sitemapindex>"#;

        let url_pattern =
            regex::Regex::new(r"(?s)<url[^>]*>.*?<loc>([^<]+)</loc>.*?</url>").unwrap();
        let urls: Vec<String> = url_pattern
            .captures_iter(sitemap_index_xml)
            .filter_map(|cap| cap.get(1).map(|m| m.as_str().to_string()))
            .collect();

        assert_eq!(
            urls.len(),
            0,
            "URL pattern should not match sitemap index entries"
        );
    }

    #[test]
    fn test_parse_regular_sitemap_with_url_tags() {
        let sitemap_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com/page1</loc>
    <lastmod>2025-10-01T00:00:00Z</lastmod>
  </url>
  <url>
    <loc>https://example.com/page2</loc>
  </url>
</urlset>"#;

        let url_pattern =
            regex::Regex::new(r"(?s)<url[^>]*>.*?<loc>([^<]+)</loc>.*?</url>").unwrap();
        let urls: Vec<String> = url_pattern
            .captures_iter(sitemap_xml)
            .filter_map(|cap| cap.get(1).map(|m| m.as_str().to_string()))
            .collect();

        assert_eq!(urls.len(), 2);
        assert!(urls.contains(&"https://example.com/page1".to_string()));
        assert!(urls.contains(&"https://example.com/page2".to_string()));
    }

    #[tokio::test]
    async fn test_fetch_with_cache_disabled() {
        let parser = SitemapParser::new().unwrap();

        let result = parser
            .fetch_with_cache("https://www.sitemaps.org/sitemap.xml", None)
            .await;

        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_sitemap_cache_entry_serialization() {
        let entry = SitemapCacheEntry {
            urls: vec!["https://example.com/page1".to_string()],
            fetched_at: 1234567890,
            ttl_seconds: 3600,
        };

        let json = serde_json::to_string(&entry).unwrap();
        let deserialized: SitemapCacheEntry = serde_json::from_str(&json).unwrap();

        assert_eq!(entry.urls, deserialized.urls);
        assert_eq!(entry.fetched_at, deserialized.fetched_at);
        assert_eq!(entry.ttl_seconds, deserialized.ttl_seconds);
    }

    #[test]
    fn test_sitemap_parser_creation() {
        let parser = SitemapParser::new();
        assert!(parser.is_ok());

        let client = Client::new();
        let _parser = SitemapParser::with_client(client);
    }

    #[tokio::test]
    async fn test_backward_compatibility() {
        let client = Client::new();
        let result = fetch_sitemap("https://www.sitemaps.org/sitemap.xml", &client).await;

        assert!(result.is_ok() || result.is_err());
    }
}