Skip to main content

saola_kit/context/
hosts.rs

1use std::collections::BTreeMap;
2
3use super::route_index::ContextSpec;
4
5#[derive(Debug, thiserror::Error, PartialEq, Eq)]
6pub enum ContextError {
7    #[error("Host «{host}» is claimed by both context «{first}» and «{second}».")]
8    DuplicateHost {
9        host: String,
10        first: String,
11        second: String,
12    },
13    #[error("href(«{name}»): no request and no 'context' option, so only full route names are accepted.")]
14    MissingContext { name: String },
15    #[error("href(«{name}») is ambiguous: {}. Use the full name.", .matches.join(", "))]
16    AmbiguousRoute { name: String, matches: Vec<String> },
17    #[error("href(«{name}»): route not defined.")]
18    RouteNotFound { name: String },
19    #[error("href(«{name}»): Missing required parameter «{param}».")]
20    MissingParameter { name: String, param: String },
21}
22
23/// Normalizes and maps declared hosts across Saola contexts.
24pub struct ContextHosts;
25
26impl ContextHosts {
27    /// Normalizes a list of host/URL declarations: lowercased, without scheme, port, or path,
28    /// skipping empty entries and preserving first-seen order without duplicates.
29    pub fn normalize<I, S>(domains: I) -> Vec<String>
30    where
31        I: IntoIterator<Item = S>,
32        S: AsRef<str>,
33    {
34        let mut hosts = Vec::new();
35        for raw in domains {
36            if let Some(host) = Self::normalize_one(raw.as_ref())
37                && !hosts.contains(&host)
38            {
39                hosts.push(host);
40            }
41        }
42        hosts
43    }
44
45    pub fn normalize_one(raw: &str) -> Option<String> {
46        let trimmed = raw.trim();
47        if trimmed.is_empty() {
48            return None;
49        }
50        let lower = trimmed.to_ascii_lowercase();
51        let without_scheme = strip_scheme(&lower);
52        let without_path = without_scheme.split('/').next().unwrap_or("");
53        let host = strip_port(without_path);
54        if host.is_empty() {
55            None
56        } else {
57            Some(host.to_owned())
58        }
59    }
60
61    /// Maps every claimed host to its owning context slug. Two different contexts cannot claim the same host.
62    pub fn table<'a>(
63        contexts: impl IntoIterator<Item = &'a ContextSpec>,
64    ) -> Result<BTreeMap<String, String>, ContextError> {
65        let mut table: BTreeMap<String, String> = BTreeMap::new();
66        for context in contexts {
67            for host in &context.hosts {
68                if let Some(existing) = table.get(host)
69                    && existing != &context.slug
70                {
71                    return Err(ContextError::DuplicateHost {
72                        host: host.clone(),
73                        first: existing.clone(),
74                        second: context.slug.clone(),
75                    });
76                }
77                table.insert(host.clone(), context.slug.clone());
78            }
79        }
80        Ok(table)
81    }
82}
83
84fn strip_scheme(s: &str) -> &str {
85    if let Some(pos) = s.find("://") {
86        let scheme = &s[..pos];
87        let mut chars = scheme.chars();
88        if chars.next().is_some_and(|c| c.is_ascii_alphabetic())
89            && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
90        {
91            return &s[pos + 3..];
92        }
93    }
94    s
95}
96
97fn strip_port(s: &str) -> &str {
98    if let Some(rest) = s.strip_prefix('[') {
99        if let Some(end) = rest.find(']') {
100            return &s[..=end + 1];
101        }
102        return s;
103    }
104    s.split(':').next().unwrap_or("")
105}