ferrunix_core/registry.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
//! Holds all registered types that can be injected or constructed.
#![allow(clippy::missing_docs_in_private_items)]
use std::any::TypeId;
use std::marker::PhantomData;
use crate::dependency_builder::{self, DepBuilder};
use crate::types::{
BoxedAny, BoxedCtor, BoxedSingletonGetter, RefAny, Registerable,
SingletonCell, Validator,
};
use crate::{
registration::RegistrationFunc, registration::DEFAULT_REGISTRY,
types::HashMap, types::OnceCell, types::Ref, types::RwLock,
};
/// All possible "objects" that can be held by the registry.
enum Object {
Transient(BoxedCtor),
Singleton(BoxedSingletonGetter, SingletonCell),
}
/// Registry for all types that can be constructed or otherwise injected.
pub struct Registry {
objects: RwLock<HashMap<TypeId, Object>>,
validation: RwLock<HashMap<TypeId, Validator>>,
}
impl Registry {
/// Create a new, empty, registry. This registry contains no pre-registered
/// types.
///
/// Types that are auto-registered are also not included in this registry.
///
/// To get access to the auto-registered types (types that are annotated by
/// the derive macro), the global registry [`Registry::global`] needs to
/// be used.
#[must_use]
pub fn empty() -> Self {
Self {
objects: RwLock::new(HashMap::new()),
validation: RwLock::new(HashMap::new()),
}
}
/// Create an empty registry, and add all autoregistered types into it.
///
/// This is the constructor for the global registry that can be acquired
/// with [`Registry::global`].
#[must_use]
pub fn autoregistered() -> Self {
let registry = Self::empty();
for register in inventory::iter::<RegistrationFunc> {
(register.0)(®istry);
}
registry
}
/// Register a new transient object, without dependencies.
///
/// To register a type with dependencies, use the builder returned from
/// [`Registry::with_deps`].
///
/// # Parameters
/// * `ctor`: A constructor function returning the newly constructed `T`.
/// This constructor will be called for every `T` that is requested.
pub fn transient<T>(&self, ctor: fn() -> T)
where
T: Registerable,
{
self.objects.write().insert(
TypeId::of::<T>(),
Object::Transient(Box::new(move |_| -> Option<BoxedAny> {
let obj = ctor();
Some(Box::new(obj))
})),
);
self.validation
.write()
.insert(TypeId::of::<T>(), Box::new(|_| true));
}
/// Register a new singleton object, without dependencies.
///
/// To register a type with dependencies, use the builder returned from
/// [`Registry::with_deps`].
///
/// # Parameters
/// * `ctor`: A constructor function returning the newly constructed `T`.
/// This constructor will be called once, lazily, when the first
/// instance of `T` is requested.
pub fn singleton<T>(&self, ctor: fn() -> T)
where
T: Registerable,
{
let getter = Box::new(
move |_this: &Self, cell: &SingletonCell| -> Option<RefAny> {
let rc = cell.get_or_init(|| Ref::new(ctor()));
Some(Ref::clone(rc))
},
);
self.objects.write().insert(
TypeId::of::<T>(),
Object::Singleton(getter, OnceCell::new()),
);
self.validation
.write()
.insert(TypeId::of::<T>(), Box::new(|_| true));
}
/// Retrieves a newly constructed `T` from this registry.
///
/// Returns `None` if `T` wasn't registered or failed to construct.
pub fn get_transient<T>(&self) -> Option<T>
where
T: Registerable,
{
if let Some(Object::Transient(ctor)) =
self.objects.read().get(&TypeId::of::<T>())
{
let boxed = (ctor)(self)?;
if let Ok(obj) = boxed.downcast::<T>() {
return Some(*obj);
}
}
None
}
/// Retrieves the singleton `T` from this registry.
///
/// Returns `None` if `T` wasn't registered or failed to construct. The
/// singleton is a ref-counted pointer object (either `Arc` or `Rc`).
pub fn get_singleton<T>(&self) -> Option<Ref<T>>
where
T: Registerable,
{
if let Some(Object::Singleton(getter, cell)) =
self.objects.read().get(&TypeId::of::<T>())
{
let singleton = (getter)(self, cell)?;
if let Ok(obj) = singleton.downcast::<T>() {
return Some(obj);
}
}
None
}
/// Register a new transient or singleton with dependencies.
pub fn with_deps<T, Deps>(&self) -> Builder<'_, T, Deps>
where
Deps: DepBuilder<T>,
{
Builder {
registry: self,
_marker: PhantomData,
_marker1: PhantomData,
}
}
/// Check whether all registered types have the required dependencies.
///
/// Returns true if for all registered types all of it's dependencies can be
/// constructed, false otherwise.
///
/// This is a potentially expensive call since it needs to go through the
/// entire dependency tree for each registered type.
///
/// Nontheless, it's recommended to call this before using the [`Registry`].
pub fn validate_all(&self) -> bool {
let lock = self.validation.read();
lock.iter().all(|(_, validator)| (validator)(self))
}
/// Check whether the type `T` is registered in this registry, and all
/// dependencies of the type `T` are also registered.
///
/// Returns true if the type and it's dependencies can be constructed, false
/// otherwise.
pub fn validate<T>(&self) -> bool
where
T: Registerable,
{
let lock = self.validation.read();
lock.get(&TypeId::of::<T>())
.map_or(false, |validator| (validator)(self))
}
/// Access the global registry.
///
/// This registry contains the types that are marked for auto-registration
/// via the derive macro.
#[cfg(feature = "multithread")]
pub fn global() -> &'static Self {
DEFAULT_REGISTRY.get_or_init(Self::autoregistered)
}
/// Access the global registry.
///
/// This registry contains the types that are marked for auto-registration
/// via the derive macro.
#[cfg(not(feature = "multithread"))]
pub fn global() -> std::rc::Rc<Self> {
DEFAULT_REGISTRY.with(|val| {
let ret =
val.get_or_init(|| std::rc::Rc::new(Self::autoregistered()));
std::rc::Rc::clone(ret)
})
}
/// Reset the global registry, removing all previously registered types, and
/// re-running the auto-registration routines.
///
/// # Safety
/// Ensure that no other thread is currently using [`Registry::global()`].
#[allow(unsafe_code)]
pub unsafe fn reset_global() {
let registry = Self::global();
{
let mut lock = registry.objects.write();
lock.clear();
}
for register in inventory::iter::<RegistrationFunc> {
#[cfg(not(feature = "multithread"))]
(register.0)(®istry);
#[cfg(feature = "multithread")]
(register.0)(registry);
}
}
}
impl std::fmt::Debug for Registry {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_struct("Registry").finish()
}
}
/// A builder for objects with dependencies. This can be created by using
/// [`Registry::with_deps`].
#[allow(clippy::single_char_lifetime_names)]
pub struct Builder<'a, T, Deps> {
registry: &'a Registry,
_marker: PhantomData<T>,
_marker1: PhantomData<Deps>,
}
impl<T, Deps> Builder<'_, T, Deps>
where
Deps: DepBuilder<T> + 'static,
T: Registerable,
{
/// Register a new transient object, with dependencies specified in
/// `.with_deps`.
///
/// The `ctor` parameter is a constructor function returning the newly
/// constructed `T`. The constructor accepts a single argument `Deps` (a
/// tuple implementing [`crate::dependency_builder::DepBuilder`]). It's
/// best to destructure the tuple to accept each dependency separately.
/// This constructor will be called for every `T` that is requested.
///
/// # Example
/// ```no_run
/// # use ferrunix_core::{Registry, Singleton, Transient};
/// # let registry = Registry::empty();
/// # struct Template {
/// # template: &'static str,
/// # }
/// registry
/// .with_deps::<_, (Transient<u8>, Singleton<Template>)>()
/// .transient(|(num, template)| {
/// // access `num` and `template` here.
/// u16::from(*num)
/// });
/// ```
///
/// For single dependencies, the destructured tuple needs to end with a
/// comma: `(dep,)`.
pub fn transient(&self, ctor: fn(Deps) -> T) {
self.registry.objects.write().insert(
TypeId::of::<T>(),
Object::Transient(Box::new(move |this| -> Option<BoxedAny> {
#[allow(clippy::option_if_let_else)]
match Deps::build(
this,
ctor,
dependency_builder::private::SealToken,
) {
Some(obj) => Some(Box::new(obj)),
None => None,
}
})),
);
self.registry.validation.write().insert(
TypeId::of::<T>(),
Box::new(|registry: &Registry| {
let type_ids =
Deps::as_typeids(dependency_builder::private::SealToken);
type_ids.iter().all(|el| {
if let Some(validator) = registry.validation.read().get(el)
{
return (validator)(registry);
}
false
})
}),
);
}
/// Register a new singleton object, with dependencies specified in
/// `.with_deps`.
///
/// The `ctor` parameter is a constructor function returning the newly
/// constructed `T`. The constructor accepts a single argument `Deps` (a
/// tuple implementing [`crate::dependency_builder::DepBuilder`]). It's
/// best to destructure the tuple to accept each dependency separately.
/// This constructor will be called once, lazily, when the first
/// instance of `T` is requested.
///
/// # Example
/// ```no_run
/// # use ferrunix_core::{Registry, Singleton, Transient};
/// # let registry = Registry::empty();
/// # struct Template {
/// # template: &'static str,
/// # }
/// registry
/// .with_deps::<_, (Transient<u8>, Singleton<Template>)>()
/// .transient(|(num, template)| {
/// // access `num` and `template` here.
/// u16::from(*num)
/// });
/// ```
///
/// For single dependencies, the destructured tuple needs to end with a
/// comma: `(dep,)`.
pub fn singleton(&self, ctor: fn(Deps) -> T) {
let getter = Box::new(
move |this: &Registry, cell: &SingletonCell| -> Option<RefAny> {
#[allow(clippy::option_if_let_else)]
match Deps::build(
this,
ctor,
dependency_builder::private::SealToken,
) {
Some(obj) => {
let rc = cell.get_or_init(|| Ref::new(obj));
Some(Ref::clone(rc))
}
None => None,
}
},
);
self.registry.objects.write().insert(
TypeId::of::<T>(),
Object::Singleton(getter, OnceCell::new()),
);
self.registry.validation.write().insert(
TypeId::of::<T>(),
Box::new(|registry: &Registry| {
let type_ids =
Deps::as_typeids(dependency_builder::private::SealToken);
type_ids.iter().all(|el| {
if let Some(validator) = registry.validation.read().get(el)
{
return (validator)(registry);
}
false
})
}),
);
}
}
impl<T, Dep> std::fmt::Debug for Builder<'_, T, Dep> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt.debug_struct("Builder").finish()
}
}