Skip to main content

navree_kernel/
key.rs

1//! Identities used by the container: modules, providers and scopes.
2
3use std::any::TypeId;
4use std::borrow::Cow;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7
8/// Identity of a module: its Rust type plus a readable name.
9///
10/// Two module values with the same `ModuleId` are the same module: the kernel
11/// registers each id once (see [`Module::is_configured`](crate::Module::is_configured)).
12#[derive(Clone, Copy, Debug)]
13pub struct ModuleId {
14    type_id: TypeId,
15    name: &'static str,
16    type_name: &'static str,
17}
18
19impl ModuleId {
20    /// The id of module type `M`, named after the short type name of `M`.
21    pub fn of<M: ?Sized + 'static>() -> Self {
22        let type_name = std::any::type_name::<M>();
23        Self {
24            type_id: TypeId::of::<M>(),
25            name: short_type_name(type_name),
26            type_name,
27        }
28    }
29
30    /// The id of module type `M` under `name`: two values of one type with
31    /// different names are two modules.
32    ///
33    /// ```
34    /// use navree_kernel::ModuleId;
35    ///
36    /// struct PaymentsModule;
37    /// let upi = ModuleId::named::<PaymentsModule>("upi");
38    /// let cards = ModuleId::named::<PaymentsModule>("cards");
39    /// assert_ne!(upi, cards);
40    /// assert_eq!(upi.name(), "upi");
41    /// assert_eq!(upi.type_name(), cards.type_name());
42    /// ```
43    pub fn named<M: ?Sized + 'static>(name: &'static str) -> ModuleId {
44        Self {
45            type_id: TypeId::of::<M>(),
46            name,
47            type_name: std::any::type_name::<M>(),
48        }
49    }
50
51    /// The readable module name (the short type name, e.g. `UsersModule`).
52    pub fn name(&self) -> &'static str {
53        self.name
54    }
55
56    /// The full type path (`navree_plugin_announcements::AnnouncementsModule`),
57    /// from `std::any::type_name`: for reading and for the plugin checks, not
58    /// for matching in an app; it may change in any release.
59    ///
60    /// ```
61    /// use navree_kernel::ModuleId;
62    ///
63    /// struct AnnouncementsModule;
64    /// let id = ModuleId::of::<AnnouncementsModule>();
65    /// assert_eq!(id.name(), "AnnouncementsModule");
66    /// assert!(id.type_name().ends_with("::AnnouncementsModule"));
67    /// ```
68    pub fn type_name(&self) -> &'static str {
69        self.type_name
70    }
71}
72
73// `type_name` follows from `type_id`, so identity is (type, name).
74impl PartialEq for ModuleId {
75    fn eq(&self, other: &Self) -> bool {
76        self.type_id == other.type_id && self.name == other.name
77    }
78}
79
80impl Eq for ModuleId {}
81
82impl Hash for ModuleId {
83    fn hash<H: Hasher>(&self, state: &mut H) {
84        self.type_id.hash(state);
85        self.name.hash(state);
86    }
87}
88
89impl fmt::Display for ModuleId {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str(self.name)
92    }
93}
94
95/// Key of a provider in the container: a type plus an optional name, so
96/// `Db` and `Db("analytics")` can coexist.
97#[derive(Clone, Debug)]
98pub struct ProviderKey {
99    type_id: TypeId,
100    type_name: &'static str,
101    name: Option<Cow<'static, str>>,
102}
103
104impl ProviderKey {
105    /// The unnamed key of type `T` (which may be a trait object such as `dyn Mailer`).
106    pub fn of<T: ?Sized + 'static>() -> Self {
107        Self {
108            type_id: TypeId::of::<T>(),
109            type_name: std::any::type_name::<T>(),
110            name: None,
111        }
112    }
113
114    /// The key of type `T` registered under `name`.
115    pub fn named<T: ?Sized + 'static>(name: impl Into<Cow<'static, str>>) -> Self {
116        Self {
117            name: Some(name.into()),
118            ..Self::of::<T>()
119        }
120    }
121
122    /// The full Rust type name of the provided type (e.g. `navree_db::Db`).
123    pub fn type_name(&self) -> &'static str {
124        self.type_name
125    }
126
127    /// The provider name, if the key is named.
128    pub fn name(&self) -> Option<&str> {
129        self.name.as_deref()
130    }
131
132    pub(crate) fn type_id(&self) -> TypeId {
133        self.type_id
134    }
135}
136
137// `type_name` is derived from `type_id`, so identity is (type, name).
138impl PartialEq for ProviderKey {
139    fn eq(&self, other: &Self) -> bool {
140        self.type_id == other.type_id && self.name == other.name
141    }
142}
143
144impl Eq for ProviderKey {}
145
146impl Hash for ProviderKey {
147    fn hash<H: Hasher>(&self, state: &mut H) {
148        self.type_id.hash(state);
149        self.name.hash(state);
150    }
151}
152
153impl fmt::Display for ProviderKey {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        match &self.name {
156            Some(name) => write!(f, "{}(\"{name}\")", self.type_name),
157            None => f.write_str(self.type_name),
158        }
159    }
160}
161
162/// How long a provided instance lives.
163#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
164#[non_exhaustive]
165pub enum Scope {
166    /// Built once per app (eagerly at boot) and shared as `Arc<T>`.
167    #[default]
168    Singleton,
169    /// Built once per unit of work ([`RequestScope`](crate::RequestScope)).
170    Request,
171    /// Built on every resolution.
172    Transient,
173}
174
175impl fmt::Display for Scope {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        f.write_str(match self {
178            Scope::Singleton => "singleton",
179            Scope::Request => "request",
180            Scope::Transient => "transient",
181        })
182    }
183}
184
185/// Strips the module path from a type name, keeping generic arguments:
186/// `app::users::UsersModule` → `UsersModule`, `a::Wrap<b::C>` → `Wrap<b::C>`.
187pub(crate) fn short_type_name(full: &'static str) -> &'static str {
188    let generics = full.find('<').unwrap_or(full.len());
189    match full[..generics].rfind("::") {
190        Some(pos) => &full[pos + 2..],
191        None => full,
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn short_type_name_strips_paths_but_keeps_generics() {
201        assert_eq!(short_type_name("app::users::UsersModule"), "UsersModule");
202        assert_eq!(short_type_name("Plain"), "Plain");
203        assert_eq!(short_type_name("a::Wrap<b::C>"), "Wrap<b::C>");
204    }
205
206    #[test]
207    fn named_keys_differ_from_unnamed_and_display_their_name() {
208        let plain = ProviderKey::of::<u8>();
209        let named = ProviderKey::named::<u8>("analytics");
210        assert_ne!(plain, named);
211        assert_eq!(named, ProviderKey::named::<u8>(String::from("analytics")));
212        assert_eq!(named.to_string(), "u8(\"analytics\")");
213        assert_eq!(named.name(), Some("analytics"));
214    }
215
216    struct Plain;
217    struct Wrap<T>(T);
218    struct Pair<A, B>(A, B);
219
220    #[test]
221    fn module_ids_carry_the_full_type_path_and_compare_as_before() {
222        let plain = ModuleId::of::<Plain>();
223        assert_eq!(plain.type_name(), "navree_kernel::key::tests::Plain");
224        assert_eq!(plain.name(), "Plain");
225        assert_eq!(plain, ModuleId::of::<Plain>());
226        // The shapes the plugin checks rely on (a tripwire on `std::any::type_name`).
227        assert_eq!(
228            ModuleId::of::<Wrap<Plain>>().type_name(),
229            "navree_kernel::key::tests::Wrap<navree_kernel::key::tests::Plain>"
230        );
231        assert_eq!(
232            ModuleId::of::<Pair<Plain, String>>().type_name(),
233            "navree_kernel::key::tests::Pair<navree_kernel::key::tests::Plain, alloc::string::String>"
234        );
235        assert_eq!(
236            ModuleId::of::<&'static Plain>().type_name(),
237            "&navree_kernel::key::tests::Plain"
238        );
239        assert_eq!(
240            ModuleId::of::<(Plain, u8)>().type_name(),
241            "(navree_kernel::key::tests::Plain, u8)"
242        );
243        assert_eq!(
244            ModuleId::of::<[Plain; 1]>().type_name(),
245            "[navree_kernel::key::tests::Plain; 1]"
246        );
247        // Hashing agrees with equality, which ignores the type path.
248        let mut ids = std::collections::HashSet::new();
249        ids.insert(ModuleId::of::<Plain>());
250        assert!(ids.contains(&ModuleId::named::<Plain>("Plain")));
251    }
252
253    #[test]
254    fn module_ids_named_differently_are_two_modules() {
255        assert_ne!(
256            ModuleId::named::<Plain>("upi"),
257            ModuleId::named::<Plain>("cards")
258        );
259        assert_eq!(
260            ModuleId::named::<Plain>("upi").type_name(),
261            ModuleId::of::<Plain>().type_name()
262        );
263        struct Payments(&'static str);
264        impl crate::Module for Payments {
265            fn id(&self) -> ModuleId {
266                ModuleId::named::<Payments>(self.0)
267            }
268            fn register(&self, _: &mut crate::ModuleBuilder) {}
269        }
270        let report = crate::Navree::app()
271            .module(Payments("upi"))
272            .module(Payments("cards"))
273            .validate()
274            .expect("two modules of one type");
275        let names: Vec<&str> = report.modules.iter().map(|m| m.name).collect();
276        assert_eq!(names, ["upi", "cards", "App"]);
277    }
278}