Skip to main content

reflex/pulse/model/
ids.rs

1//! Stable identities and slugs.
2//!
3//! Identity is semantic ("the module `src/pulse`", "the changelog"), never positional
4//! or derived from a file's line numbers, so ids survive edits. A page's URL comes from
5//! its id through [`SlugAllocator`], which remembers earlier choices in
6//! `.reflex/pulse/slugs.json` so published links stay stable.
7
8use serde::{Deserialize, Serialize};
9use std::collections::{BTreeMap, BTreeSet};
10use std::fmt;
11use std::path::Path;
12
13macro_rules! id_type {
14    ($(#[$doc:meta])* $name:ident) => {
15        $(#[$doc])*
16        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
17        #[serde(transparent)]
18        pub struct $name(pub String);
19
20        impl $name {
21            pub fn new(s: impl Into<String>) -> Self {
22                Self(s.into())
23            }
24            pub fn as_str(&self) -> &str {
25                &self.0
26            }
27        }
28
29        impl fmt::Display for $name {
30            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31                f.write_str(&self.0)
32            }
33        }
34
35        impl From<&str> for $name {
36            fn from(s: &str) -> Self {
37                Self(s.to_string())
38            }
39        }
40    };
41}
42
43id_type!(
44    /// A page, e.g. `int/module/src/pulse` or `docs/changelog`.
45    PageId
46);
47id_type!(
48    /// An anchor inside a page, e.g. `dependencies`.
49    AnchorId
50);
51id_type!(
52    /// A module: a directory of source files, e.g. `src/pulse`.
53    ModuleId
54);
55id_type!(
56    /// A fact, e.g. `module:src/pulse:files`.
57    FactId
58);
59id_type!(
60    /// A symbol, e.g. `rust:reflex_search::query::QueryEngine#struct`. Filled from M3.
61    SymbolId
62);
63
64/// Lowercase kebab slug of one path segment: `[a-z0-9-]`, no leading/trailing `-`.
65pub fn slugify(segment: &str) -> String {
66    let mut out = String::with_capacity(segment.len());
67    let mut dash = false;
68    for c in segment.chars() {
69        if c.is_ascii_alphanumeric() {
70            out.push(c.to_ascii_lowercase());
71            dash = false;
72        } else if !dash && !out.is_empty() {
73            out.push('-');
74            dash = true;
75        }
76    }
77    while out.ends_with('-') {
78        out.pop();
79    }
80    if out.is_empty() {
81        out.push('x');
82    }
83    out
84}
85
86/// A heading's anchor, compatible with GitHub/Starlight heading slugs for ASCII text.
87pub fn anchor_for(text: &str) -> AnchorId {
88    AnchorId(slugify(text))
89}
90
91/// Assigns each page a URL path segment (the part after the tab prefix) and keeps it
92/// stable across runs.
93#[derive(Debug, Default, Serialize, Deserialize)]
94pub struct SlugAllocator {
95    /// Page id → slug, from earlier runs and this one.
96    assigned: BTreeMap<PageId, String>,
97    #[serde(skip)]
98    taken: BTreeSet<String>,
99    #[serde(skip)]
100    used: BTreeSet<PageId>,
101}
102
103impl SlugAllocator {
104    /// Load `.reflex/pulse/slugs.json`, or start empty.
105    pub fn load(path: &Path) -> Self {
106        let mut me: Self = std::fs::read(path)
107            .ok()
108            .and_then(|b| serde_json::from_slice(&b).ok())
109            .unwrap_or_default();
110        me.taken = me.assigned.values().cloned().collect();
111        me
112    }
113
114    /// The slug for `id`, preferring `wanted` (already slugified segments joined by `/`).
115    ///
116    /// A page keeps the slug it had last run. A new page that collides with another
117    /// page's slug gets `-2`, `-3`, … in id order, so output is deterministic.
118    pub fn assign(&mut self, id: &PageId, wanted: &str) -> String {
119        self.used.insert(id.clone());
120        if let Some(existing) = self.assigned.get(id) {
121            return existing.clone();
122        }
123        let mut slug = wanted.to_string();
124        let mut n = 2;
125        while self.taken.contains(&slug) {
126            slug = format!("{wanted}-{n}");
127            n += 1;
128        }
129        self.taken.insert(slug.clone());
130        self.assigned.insert(id.clone(), slug.clone());
131        slug
132    }
133
134    /// Save the slugs of pages used this run. Slugs of pages that disappeared are
135    /// dropped, so the name can be reused.
136    pub fn save(&self, path: &Path) -> std::io::Result<()> {
137        let kept: BTreeMap<&PageId, &String> = self
138            .assigned
139            .iter()
140            .filter(|(id, _)| self.used.contains(*id))
141            .collect();
142        if let Some(parent) = path.parent() {
143            std::fs::create_dir_all(parent)?;
144        }
145        let tmp = crate::atomic_write::tmp_path_for(path);
146        std::fs::write(
147            &tmp,
148            serde_json::to_vec_pretty(&serde_json::json!({ "assigned": kept }))?,
149        )?;
150        crate::atomic_write::atomic_replace(&tmp, path)
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn slugify_segments() {
160        assert_eq!(slugify("src"), "src");
161        assert_eq!(slugify("Query Engine"), "query-engine");
162        assert_eq!(slugify("build.rs"), "build-rs");
163        assert_eq!(slugify("__init__"), "init");
164        assert_eq!(slugify("--"), "x");
165        assert_eq!(slugify("v2.0.1"), "v2-0-1");
166    }
167
168    #[test]
169    fn slugs_are_stable_and_collisions_deterministic() {
170        let dir = tempfile::TempDir::new().unwrap();
171        let path = dir.path().join("slugs.json");
172        let mut a = SlugAllocator::load(&path);
173        assert_eq!(a.assign(&"p1".into(), "src/a-b"), "src/a-b");
174        assert_eq!(a.assign(&"p2".into(), "src/a-b"), "src/a-b-2");
175        a.save(&path).unwrap();
176
177        // Next run: p2 keeps its slug even if assigned first.
178        let mut b = SlugAllocator::load(&path);
179        assert_eq!(b.assign(&"p2".into(), "src/a-b"), "src/a-b-2");
180        assert_eq!(b.assign(&"p1".into(), "src/a-b"), "src/a-b");
181        assert_eq!(b.assign(&"p3".into(), "src/a-b"), "src/a-b-3");
182    }
183
184    #[test]
185    fn vanished_pages_free_their_slug() {
186        let dir = tempfile::TempDir::new().unwrap();
187        let path = dir.path().join("slugs.json");
188        let mut a = SlugAllocator::load(&path);
189        a.assign(&"old".into(), "x");
190        a.save(&path).unwrap();
191        let b = SlugAllocator::load(&path);
192        b.save(&path).unwrap(); // "old" not used this run
193        let mut c = SlugAllocator::load(&path);
194        assert_eq!(c.assign(&"new".into(), "x"), "x");
195    }
196}