domain_map/
lib.rs

1//! This module provides a simple datastructure that can store
2//! values associated with a domain name style key.
3//! Wildcard keys are supported.
4use config::get_or_create_sub_module;
5use mlua::prelude::LuaUserData;
6use mlua::{FromLua, Lua, MetaMethod, UserDataMethods};
7use mod_memoize::CacheValue;
8use serde::{Deserialize, Serialize};
9use std::collections::{BTreeMap, HashMap};
10use std::fmt::Debug;
11use std::sync::Arc;
12
13#[derive(Clone)]
14struct Node<V: Clone> {
15    value: Option<V>,
16    label: String,
17    children: HashMap<String, Self>,
18}
19
20impl<V: Debug + Clone> Debug for Node<V> {
21    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
22        fmt.debug_struct("Node")
23            .field("value", &self.value)
24            .field("label", &self.label)
25            .field("children", &self.children)
26            .finish()
27    }
28}
29
30/// A DomainMap is conceptually similar to a HashMap. The differences
31/// are that the keys are always domain name strings like "example.com"
32/// and that a lookup that doesn't have an exact match in the map is
33/// allowed to resolve through a wildcard entry, such as "*.example.com",
34/// if one has been inserted.
35/// A lookup for "example.com" will not match the wildcard "*.example.com"
36/// because it has fewer segments than the wildcard entry.
37#[derive(Default, Clone, Serialize, Deserialize)]
38#[serde(from = "BTreeMap<String, V>", into = "BTreeMap<String,V>")]
39pub struct DomainMap<V: Clone> {
40    top: Arc<HashMap<String, Node<V>>>,
41}
42
43impl LuaUserData for DomainMap<CacheValue> {
44    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
45        mod_memoize::Memoized::impl_memoize(methods);
46        methods.add_meta_method(MetaMethod::Index, |lua, this, key: String| {
47            if let Some(value) = this.get(&key) {
48                let value = value.as_lua(lua)?;
49                Ok(Some(value))
50            } else {
51                Ok(None)
52            }
53        });
54        methods.add_meta_method_mut(
55            MetaMethod::NewIndex,
56            |lua, this, (key, value): (String, mlua::Value)| {
57                let value = CacheValue::from_lua(value, lua)?;
58                this.insert(&key, value);
59                Ok(())
60            },
61        );
62    }
63}
64
65impl<V: Debug + Clone> Debug for DomainMap<V> {
66    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
67        fmt.debug_struct("DomainMap")
68            .field("top", &self.top)
69            .finish()
70    }
71}
72
73impl<V: Clone> DomainMap<V> {
74    pub fn new() -> Self {
75        Self {
76            top: Arc::new(HashMap::new()),
77        }
78    }
79
80    pub fn insert(&mut self, pattern: &str, value: V) {
81        let mut current = Arc::make_mut(&mut self.top);
82        let mut iter = pattern.rsplit('.').peekable();
83        while let Some(seg) = iter.next() {
84            let node = current.entry(seg.to_string()).or_insert_with(|| Node {
85                value: None,
86                label: seg.to_string(),
87                children: HashMap::new(),
88            });
89
90            if iter.peek().is_none() {
91                // No further segments: this is where we set our value
92                node.value.replace(value);
93                return;
94            }
95            current = &mut node.children;
96        }
97    }
98
99    pub fn get(&self, pattern: &str) -> Option<&V> {
100        let mut current = &*self.top;
101        let mut iter = pattern.rsplit('.').peekable();
102        while let Some(seg) = iter.next() {
103            match current.get(seg) {
104                Some(node) => {
105                    if iter.peek().is_none() {
106                        // This node holds our exact match
107                        return node.value.as_ref();
108                    }
109                    current = &node.children;
110                    continue;
111                }
112                None => {
113                    // No exact match; see if there is a wildcard
114                    let wild = current.get("*")?;
115                    return wild.value.as_ref();
116                }
117            }
118        }
119        None
120    }
121}
122
123impl<V: Clone> From<BTreeMap<String, V>> for DomainMap<V> {
124    fn from(map: BTreeMap<String, V>) -> Self {
125        let mut result = DomainMap::new();
126        for (k, v) in map {
127            result.insert(&k, v);
128        }
129        result
130    }
131}
132
133fn walk<'a, V: Clone>(
134    nodes: &'a HashMap<String, Node<V>>,
135    stack: &mut Vec<&'a str>,
136    result: &mut BTreeMap<String, V>,
137) {
138    for (key, value) in nodes {
139        stack.insert(0, key);
140        if let Some(v) = &value.value {
141            result.insert(stack.join("."), v.clone());
142        }
143        walk(&value.children, stack, result);
144        stack.remove(0);
145    }
146}
147
148impl<V: Clone> From<DomainMap<V>> for BTreeMap<String, V> {
149    fn from(map: DomainMap<V>) -> Self {
150        let mut result = BTreeMap::new();
151        let mut stack = vec![];
152        walk(&map.top, &mut stack, &mut result);
153
154        result
155    }
156}
157
158pub fn register(lua: &Lua) -> anyhow::Result<()> {
159    let dmap_mod = get_or_create_sub_module(lua, "domain_map")?;
160
161    dmap_mod.set(
162        "new",
163        lua.create_function(|lua, value: Option<HashMap<String, mlua::Value>>| {
164            let mut dmap: DomainMap<mod_memoize::CacheValue> = DomainMap::new();
165
166            if let Some(value) = value {
167                for (k, v) in value {
168                    let v = CacheValue::from_lua(v, lua)?;
169                    dmap.insert(&k, v);
170                }
171            }
172
173            Ok(dmap)
174        })?,
175    )?;
176
177    Ok(())
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn basic() {
186        let mut map: DomainMap<u32> = DomainMap::new();
187        map.insert("*.example.com", 42);
188        map.insert("example.com", 24);
189        map.insert("omg.wtf.woot.example.com", 128);
190        println!("{map:#?}");
191
192        assert_eq!(map.get("foo.com"), None);
193        assert_eq!(map.get("example.com"), Some(&24));
194        assert_eq!(map.get("lemon.example.com"), Some(&42));
195        assert_eq!(map.get("lemon.cake.example.com"), Some(&42));
196        assert_eq!(map.get("woot.example.com"), None);
197        assert_eq!(map.get("wtf.woot.example.com"), None);
198        assert_eq!(map.get("omg.wtf.woot.example.com"), Some(&128));
199
200        let serialized: BTreeMap<_, _> = map.into();
201        k9::snapshot!(
202            &serialized,
203            r#"
204{
205    "*.example.com": 42,
206    "example.com": 24,
207    "omg.wtf.woot.example.com": 128,
208}
209"#
210        );
211
212        let round_trip: DomainMap<_> = serialized.into();
213        assert_eq!(round_trip.get("lemon.example.com"), Some(&42));
214
215        let serialized_again: BTreeMap<_, _> = round_trip.into();
216        k9::snapshot!(
217            &serialized_again,
218            r#"
219{
220    "*.example.com": 42,
221    "example.com": 24,
222    "omg.wtf.woot.example.com": 128,
223}
224"#
225        );
226    }
227
228    #[test]
229    fn clone_is_shared_until_written() {
230        let mut map: DomainMap<u32> = DomainMap::new();
231        map.insert("example.com", 1);
232
233        let mut copy = map.clone();
234        assert!(Arc::ptr_eq(&map.top, &copy.top));
235
236        copy.insert("other.com", 2);
237        assert!(!Arc::ptr_eq(&map.top, &copy.top));
238        assert_eq!(map.get("other.com"), None);
239        assert_eq!(copy.get("other.com"), Some(&2));
240        assert_eq!(copy.get("example.com"), Some(&1));
241    }
242}