Skip to main content

kernel/
address.rs

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