Skip to main content

kernel/
address.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Address types and URL classification helpers.
5//!
6//! All functions here are WASM-clean: they rely on `url::Url::parse`,
7//! `mime_guess`, and `infer` — no platform I/O.
8
9use rkyv::{Archive, Deserialize, Serialize};
10
11/// Address type hint for renderer selection.
12///
13/// Always derived from the URL scheme — never stored independently.
14/// Obtain via `node.primary_address().address_kind()`.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Archive, Serialize, Deserialize)]
16pub enum AddressKind {
17    /// Served over HTTP/HTTPS — default; Servo renders.
18    #[default]
19    Http,
20    /// Local filesystem path (`file://` URL).
21    File,
22    /// Inline data URL payload.
23    Data,
24    /// Graphshell clip-address route (`verso://clip/...` or legacy `graphshell://clip/...`).
25    GraphshellClip,
26    /// Local filesystem directory path.
27    Directory,
28    /// Any other or unresolved scheme.
29    Unknown,
30}
31
32/// Typed address carrying both the scheme classification and the raw URL string.
33///
34/// Replaces the two-field stopgap of `url: String` + `AddressKind`. The raw
35/// URL string is always recoverable via [`Address::as_url_str`]. Structured
36/// parsing (hostname extraction, path manipulation) continues to happen at the
37/// render/utility layer via `cached_host_from_url` and host-side address utilities.
38///
39/// Uses `String` payloads rather than `url::Url` / `PathBuf` so the type
40/// remains `rkyv`-serializable and WASM-clean without pulling parser
41/// dependencies into the graph model layer.
42#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
43#[rkyv(derive(Debug, PartialEq))]
44pub enum Address {
45    /// HTTP or HTTPS content URL.
46    Http(String),
47    /// Local filesystem file (`file://` URL, non-directory).
48    File(String),
49    /// Inline data URL payload (`data:` scheme).
50    Data(String),
51    /// Graphshell clip route (`verso://clip/<id>` or `graphshell://clip/<id>`).
52    /// The payload is the clip id, not the full URL.
53    Clip(String),
54    /// Local filesystem directory path (`file://` URL ending with `/`).
55    Directory(String),
56    /// Any other or unresolved scheme — stores the raw URL.
57    Custom(String),
58}
59
60impl Address {
61    /// Return the raw URL string for this address.
62    pub fn as_url_str(&self) -> &str {
63        match self {
64            Address::Http(s)
65            | Address::File(s)
66            | Address::Data(s)
67            | Address::Directory(s)
68            | Address::Custom(s)
69            | Address::Clip(s) => s.as_str(),
70        }
71    }
72
73    /// Derive the legacy `AddressKind` from this address.
74    ///
75    /// Provided as a bridge accessor during the migration so callers that
76    /// still pattern-match on `AddressKind` continue to compile unchanged.
77    pub fn address_kind(&self) -> AddressKind {
78        match self {
79            Address::Http(_) => AddressKind::Http,
80            Address::File(_) => AddressKind::File,
81            Address::Data(_) => AddressKind::Data,
82            Address::Clip(_) => AddressKind::GraphshellClip,
83            Address::Directory(_) => AddressKind::Directory,
84            Address::Custom(_) => AddressKind::Unknown,
85        }
86    }
87}
88
89impl chartulary::ContainerAddress for Address {
90    fn to_address(&self) -> chartulary::Address {
91        chartulary::Address::new(self.as_url_str())
92    }
93}
94
95/// Role of an address claim on a node.
96///
97/// Per the [node identity + duplicates brief](https://github.com/merely-made/mere/blob/main/design_docs/mere_docs/research/2026-05-18_node_identity_and_duplicates_brief.md):
98/// a node carries a `Vec<AddressClaim>`; one of them must be `Primary`
99/// (the canonical retrieval target), the rest are `Alias`es (equivalent
100/// addresses — mirrors, cross-protocol pairs, user-declared aliases).
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
102#[rkyv(derive(Debug, PartialEq))]
103pub enum AddressRole {
104    /// Canonical retrieval target. Exactly one Primary per node.
105    Primary,
106    /// Equivalent address pointing at the same content (mirror,
107    /// cross-protocol pair, declared alias).
108    Alias,
109}
110
111/// An address claim attached to a graph node.
112///
113/// Multiple claims per node enable user-declared aliases (mirrors,
114/// cross-protocol equivalents) without conflating identity with address.
115/// Identity is `Node.id: Uuid`; addresses are properties.
116#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
117#[rkyv(derive(Debug, PartialEq))]
118pub struct AddressClaim {
119    pub address: Address,
120    pub role: AddressRole,
121}
122
123impl AddressClaim {
124    /// Construct a Primary claim.
125    pub fn primary(address: Address) -> Self {
126        Self {
127            address,
128            role: AddressRole::Primary,
129        }
130    }
131
132    /// Construct an Alias claim.
133    pub fn alias(address: Address) -> Self {
134        Self {
135            address,
136            role: AddressRole::Alias,
137        }
138    }
139
140    /// True if this claim has `Primary` role.
141    pub fn is_primary(&self) -> bool {
142        matches!(self.role, AddressRole::Primary)
143    }
144}
145
146/// Construct a typed [`Address`] from a raw URL string.
147///
148/// Uses the same scheme-detection logic as the legacy `address_kind_from_url`,
149/// but embeds the URL (or clip id for clip routes) directly in the variant.
150pub fn address_from_url(url: &str) -> Address {
151    let lower = url.to_ascii_lowercase();
152    if lower.starts_with("http://") || lower.starts_with("https://") {
153        Address::Http(url.to_owned())
154    } else if lower.starts_with("data:") {
155        Address::Data(url.to_owned())
156    } else if lower.starts_with("verso://clip/") || lower.starts_with("graphshell://clip/") {
157        Address::Clip(url.to_owned())
158    } else if lower.starts_with("file://") {
159        if file_url_uses_directory_syntax(url) {
160            Address::Directory(url.to_owned())
161        } else {
162            Address::File(url.to_owned())
163        }
164    } else {
165        Address::Custom(url.to_owned())
166    }
167}
168
169/// Infer `AddressKind` from a URL scheme.
170pub fn address_kind_from_url(url: &str) -> AddressKind {
171    let lower = url.to_ascii_lowercase();
172    if lower.starts_with("http://") || lower.starts_with("https://") {
173        AddressKind::Http
174    } else if lower.starts_with("data:") {
175        AddressKind::Data
176    } else if lower.starts_with("verso://clip/") || lower.starts_with("graphshell://clip/") {
177        AddressKind::GraphshellClip
178    } else if lower.starts_with("file://") {
179        if file_url_uses_directory_syntax(url) {
180            AddressKind::Directory
181        } else {
182            AddressKind::File
183        }
184    } else {
185        AddressKind::Unknown
186    }
187}
188
189fn file_url_uses_directory_syntax(url: &str) -> bool {
190    // AddressKind classification must be deterministic from URL semantics alone,
191    // independent of local filesystem state.
192    url::Url::parse(url)
193        .ok()
194        .is_some_and(|parsed| parsed.path().ends_with('/'))
195}
196
197pub fn cached_host_from_url(url: &str) -> Option<String> {
198    url::Url::parse(url)
199        .ok()
200        .and_then(|parsed| parsed.host_str().map(str::to_owned))
201}
202
203/// Detect MIME type from URL + optional content bytes.
204///
205/// Detection order:
206/// 1) Extension lookup via `mime_guess` (cheap, synchronous)
207/// 2) Content-byte sniffing via `infer` only when extension lookup is
208///    missing or ambiguous
209///
210/// Returns `None` when neither source yields a known MIME type.
211pub fn detect_mime(url: &str, content_bytes: Option<&[u8]>) -> Option<String> {
212    let no_fragment = url.split('#').next().unwrap_or(url);
213    let no_query = no_fragment.split('?').next().unwrap_or(no_fragment);
214    // Strip file:// scheme so mime_guess sees a plain path.
215    let path = no_query
216        .strip_prefix("file://")
217        .unwrap_or(no_query)
218        .trim_start_matches('/');
219    // Reconstruct a rooted path string for mime_guess.
220    let guess_path = format!("/{path}");
221    let guessed: Vec<String> = mime_guess::from_path(&guess_path)
222        .into_iter()
223        .map(|m| m.to_string())
224        .collect();
225
226    let is_ambiguous = guessed.len() > 1
227        || guessed
228            .first()
229            .map(|m| m == "application/octet-stream")
230            .unwrap_or(false);
231
232    if !guessed.is_empty() && !is_ambiguous {
233        return guessed.first().cloned();
234    }
235
236    if let Some(bytes) = content_bytes {
237        if let Some(kind) = infer::get(bytes) {
238            return Some(kind.mime_type().to_string());
239        }
240    }
241
242    guessed.first().cloned()
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn detect_mime_returns_pdf_for_pdf_path() {
251        assert_eq!(
252            detect_mime("file:///home/user/document.pdf", None),
253            Some("application/pdf".to_string())
254        );
255    }
256
257    #[test]
258    fn detect_mime_returns_text_plain_for_txt_path() {
259        assert_eq!(
260            detect_mime("file:///notes/readme.txt", None),
261            Some("text/plain".to_string())
262        );
263    }
264
265    #[test]
266    fn detect_mime_returns_none_for_no_extension() {
267        assert!(detect_mime("https://example.com/page", None).is_none());
268    }
269
270    #[test]
271    fn detect_mime_uses_magic_bytes_when_extension_is_missing() {
272        let pdf_header = b"%PDF-1.7\n1 0 obj\n";
273        assert_eq!(
274            detect_mime("https://example.com/no-extension", Some(pdf_header)),
275            Some("application/pdf".to_string())
276        );
277    }
278
279    #[test]
280    fn detect_mime_prefers_extension_when_unambiguous() {
281        let pdf_header = b"%PDF-1.7\n1 0 obj\n";
282        assert_eq!(
283            detect_mime("file:///home/user/readme.txt", Some(pdf_header)),
284            Some("text/plain".to_string())
285        );
286    }
287
288    #[test]
289    fn detect_mime_falls_back_to_extension_when_magic_unknown() {
290        let unknown = b"not a known magic signature";
291        assert_eq!(
292            detect_mime("file:///home/user/data.json", Some(unknown)),
293            Some("application/json".to_string())
294        );
295    }
296
297    #[test]
298    fn address_kind_from_url_http() {
299        assert_eq!(
300            address_kind_from_url("http://example.com"),
301            AddressKind::Http
302        );
303        assert_eq!(
304            address_kind_from_url("https://example.com"),
305            AddressKind::Http
306        );
307    }
308
309    #[test]
310    fn address_kind_from_url_file() {
311        assert_eq!(
312            address_kind_from_url("file:///home/user/file.txt"),
313            AddressKind::File
314        );
315    }
316
317    #[test]
318    fn address_kind_from_url_data_clip_directory_and_unknown() {
319        assert_eq!(
320            address_kind_from_url("data:text/plain,hello"),
321            AddressKind::Data
322        );
323        assert_eq!(
324            address_kind_from_url("verso://clip/clip-123"),
325            AddressKind::GraphshellClip
326        );
327        assert_eq!(
328            address_kind_from_url("file:///tmp/sample-dir/"),
329            AddressKind::Directory
330        );
331        assert_eq!(
332            address_kind_from_url("gemini://gemini.circumlunar.space/"),
333            AddressKind::Unknown
334        );
335        assert_eq!(
336            address_kind_from_url("ftp://files.example.com/"),
337            AddressKind::Unknown
338        );
339    }
340
341    #[test]
342    fn address_kind_from_url_file_directory_classification_is_syntax_based() {
343        assert_eq!(
344            address_kind_from_url("file:///tmp/sample-dir/"),
345            AddressKind::Directory
346        );
347        assert_eq!(
348            address_kind_from_url("file:///tmp/sample-dir"),
349            AddressKind::File
350        );
351    }
352
353    #[test]
354    fn address_from_url_http() {
355        assert_eq!(
356            address_from_url("https://example.com"),
357            Address::Http("https://example.com".to_string())
358        );
359        assert_eq!(
360            address_from_url("http://example.com/path"),
361            Address::Http("http://example.com/path".to_string())
362        );
363    }
364
365    #[test]
366    fn address_from_url_file_and_directory() {
367        assert_eq!(
368            address_from_url("file:///home/user/file.txt"),
369            Address::File("file:///home/user/file.txt".to_string())
370        );
371        assert_eq!(
372            address_from_url("file:///tmp/mydir/"),
373            Address::Directory("file:///tmp/mydir/".to_string())
374        );
375    }
376
377    #[test]
378    fn address_from_url_data_and_custom() {
379        assert_eq!(
380            address_from_url("data:text/plain,hello"),
381            Address::Data("data:text/plain,hello".to_string())
382        );
383        assert_eq!(
384            address_from_url("gemini://gemini.circumlunar.space/"),
385            Address::Custom("gemini://gemini.circumlunar.space/".to_string())
386        );
387    }
388
389    #[test]
390    fn address_from_url_clip_stores_full_url() {
391        assert_eq!(
392            address_from_url("verso://clip/clip-abc-123"),
393            Address::Clip("verso://clip/clip-abc-123".to_string())
394        );
395        assert_eq!(
396            address_from_url("graphshell://clip/clip-xyz"),
397            Address::Clip("graphshell://clip/clip-xyz".to_string())
398        );
399    }
400
401    #[test]
402    fn address_as_url_str_roundtrips_for_all_variants() {
403        let cases = [
404            "https://example.com",
405            "file:///home/user/file.txt",
406            "file:///tmp/mydir/",
407            "data:text/plain,hello",
408            "gemini://example.com/",
409            "verso://clip/clip-abc",
410            "graphshell://clip/clip-xyz",
411        ];
412        for url in cases {
413            let addr = address_from_url(url);
414            assert_eq!(
415                addr.as_url_str(),
416                url,
417                "as_url_str should return the original URL for {url}"
418            );
419        }
420    }
421
422    #[test]
423    fn address_address_kind_bridge_matches_legacy_inference() {
424        let cases = [
425            ("https://example.com", AddressKind::Http),
426            ("http://example.com", AddressKind::Http),
427            ("file:///home/user/file.txt", AddressKind::File),
428            ("file:///tmp/mydir/", AddressKind::Directory),
429            ("data:text/plain,hello", AddressKind::Data),
430            ("verso://clip/clip-123", AddressKind::GraphshellClip),
431            ("graphshell://clip/clip-456", AddressKind::GraphshellClip),
432            ("gemini://example.com/", AddressKind::Unknown),
433        ];
434        for (url, expected_kind) in cases {
435            assert_eq!(
436                address_from_url(url).address_kind(),
437                expected_kind,
438                "address_kind() mismatch for {url}"
439            );
440            assert_eq!(
441                address_kind_from_url(url),
442                expected_kind,
443                "address_kind_from_url mismatch for {url}"
444            );
445        }
446    }
447}