hosting-di 0.1.0

Service collection, provider and scopes for the hosting crate
Documentation
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use crate::container::{ConstructFn, Container, Erased};
use crate::graph::Graph;
use crate::key::Key;
use crate::{
    BoxError, BuildError, BuildIssue, CastFrom, Dependency, Lifetime, Resolver, Service,
    ServiceProvider,
};
use std::any::{Any, type_name};
use std::fmt;
use std::sync::Arc;

/// Services registered for an application, frozen into a [`ServiceProvider`]
/// by [`build`](Self::build).
///
/// Registering a type again adds another registration: a single resolve uses
/// the last one, and `resolve_all` returns every one in order. Singletons are
/// constructed outside any scope, so a singleton that depends on a scoped
/// service fails to resolve rather than holding on to one scope's instance.
/// Transients are constructed in the scope that requested them.
///
/// # Validation
///
/// [`build`](Self::build) always rejects dependency cycles. Two more checks
/// are opt-in, and every problem found is reported in one [`BuildError`]:
///
/// ```
/// # use hosting_di::{Dependency, ResolveError, Resolver, Service};
/// use hosting_di::{BuildIssue, ServiceCollection};
/// # struct Pool;
/// # struct Database;
/// # impl Service for Database {
/// #     fn dependencies() -> Vec<Dependency> {
/// #         vec![Dependency::on::<Pool>()]
/// #     }
/// #     fn construct(_: &Resolver<'_>) -> Result<Self, ResolveError> {
/// #         Ok(Database)
/// #     }
/// # }
/// let mut services = ServiceCollection::new();
/// services
///     .validate_dependencies()
///     .validate_scopes()
///     .add_singleton::<Database>(); // needs a Pool, which isn't registered
///
/// let err = services.build().unwrap_err();
/// assert!(matches!(err.issues(), [BuildIssue::MissingDependency { .. }]));
/// ```
#[derive(Debug, Default)]
pub struct ServiceCollection {
    registrations: Vec<Registration>,
    validation: Validation,
}

/// Opt-in checks run by `build`.
#[derive(Debug, Default)]
struct Validation {
    dependencies: bool,
    scopes: bool,
}

pub(crate) struct Registration {
    pub(crate) key: Key,
    /// Type name of what is constructed; differs from the key's name when a
    /// service is registered as a trait.
    pub(crate) implementation: &'static str,
    pub(crate) lifetime: Lifetime,
    pub(crate) source: Source,
    /// Declared dependencies; `None` for factories and instances.
    pub(crate) dependencies: Option<fn() -> Vec<Dependency>>,
    /// A `fn(Erased) -> Option<Arc<I>>` for the registered service type `I`.
    pub(crate) cast: Box<dyn Any + Send + Sync>,
    /// Index into the storage of this registration's lifetime, set by the container.
    pub(crate) slot: usize,
}

impl fmt::Debug for Registration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Registration")
            .field("service", &self.key.name)
            .field("implementation", &self.implementation)
            .field("lifetime", &self.lifetime)
            .finish_non_exhaustive()
    }
}

pub(crate) enum Source {
    Construct(ConstructFn),
    Instance(Erased),
}

impl ServiceCollection {
    /// Creates an empty collection.
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers `T` with one instance shared for the life of the provider.
    pub fn add_singleton<T: Service>(&mut self) -> &mut Self {
        self.add::<T>(Lifetime::Singleton)
    }

    /// Registers `T` with one instance per scope.
    pub fn add_scoped<T: Service>(&mut self) -> &mut Self {
        self.add::<T>(Lifetime::Scoped)
    }

    /// Registers `T` with a new instance on every resolution.
    pub fn add_transient<T: Service>(&mut self) -> &mut Self {
        self.add::<T>(Lifetime::Transient)
    }

    /// Registers `T` as an implementation of the trait object `I`, with one
    /// instance shared for the life of the provider.
    ///
    /// `T` is reachable only as `I`; register it separately to resolve it by
    /// its own type.
    pub fn add_singleton_as<I, T>(&mut self) -> &mut Self
    where
        I: ?Sized + CastFrom<T> + Send + Sync + 'static,
        T: Service,
    {
        self.add_service::<I, T>(Lifetime::Singleton, trait_cast::<I, T>())
    }

    /// Registers `T` as an implementation of `I`, with one instance per scope.
    pub fn add_scoped_as<I, T>(&mut self) -> &mut Self
    where
        I: ?Sized + CastFrom<T> + Send + Sync + 'static,
        T: Service,
    {
        self.add_service::<I, T>(Lifetime::Scoped, trait_cast::<I, T>())
    }

    /// Registers `T` as an implementation of `I`, constructed on every
    /// resolution.
    pub fn add_transient_as<I, T>(&mut self) -> &mut Self
    where
        I: ?Sized + CastFrom<T> + Send + Sync + 'static,
        T: Service,
    {
        self.add_service::<I, T>(Lifetime::Transient, trait_cast::<I, T>())
    }

    /// Whether anything is registered as `T`.
    ///
    /// Covers every form of registration, so it can guard any of them, for
    /// example to add a default only when the application hasn't.
    pub fn contains<T: ?Sized + 'static>(&self) -> bool {
        let key = Key::of::<T>();
        self.registrations
            .iter()
            .any(|registration| registration.key == key)
    }

    /// Like [`add_singleton`](Self::add_singleton), but only if nothing is
    /// registered as `T` yet.
    pub fn try_add_singleton<T: Service>(&mut self) -> &mut Self {
        if self.contains::<T>() {
            return self;
        }
        self.add_singleton::<T>()
    }

    /// Like [`add_scoped`](Self::add_scoped), but only if nothing is
    /// registered as `T` yet.
    pub fn try_add_scoped<T: Service>(&mut self) -> &mut Self {
        if self.contains::<T>() {
            return self;
        }
        self.add_scoped::<T>()
    }

    /// Like [`add_transient`](Self::add_transient), but only if nothing is
    /// registered as `T` yet.
    pub fn try_add_transient<T: Service>(&mut self) -> &mut Self {
        if self.contains::<T>() {
            return self;
        }
        self.add_transient::<T>()
    }

    /// Like [`add_singleton_as`](Self::add_singleton_as), but only if nothing
    /// is registered as `I` yet, whatever its implementation.
    pub fn try_add_singleton_as<I, T>(&mut self) -> &mut Self
    where
        I: ?Sized + CastFrom<T> + Send + Sync + 'static,
        T: Service,
    {
        if self.contains::<I>() {
            return self;
        }
        self.add_singleton_as::<I, T>()
    }

    /// Like [`add_scoped_as`](Self::add_scoped_as), but only if nothing is
    /// registered as `I` yet, whatever its implementation.
    pub fn try_add_scoped_as<I, T>(&mut self) -> &mut Self
    where
        I: ?Sized + CastFrom<T> + Send + Sync + 'static,
        T: Service,
    {
        if self.contains::<I>() {
            return self;
        }
        self.add_scoped_as::<I, T>()
    }

    /// Like [`add_transient_as`](Self::add_transient_as), but only if nothing
    /// is registered as `I` yet, whatever its implementation.
    pub fn try_add_transient_as<I, T>(&mut self) -> &mut Self
    where
        I: ?Sized + CastFrom<T> + Send + Sync + 'static,
        T: Service,
    {
        if self.contains::<I>() {
            return self;
        }
        self.add_transient_as::<I, T>()
    }

    /// Registers a factory for `T` with one instance shared for the life of the
    /// provider.
    ///
    /// Errors from resolving dependencies inside the factory keep their original
    /// path; any other error is reported as a construction failure of `T`.
    /// Like constructors, factories must not block on other threads that
    /// resolve from the same container.
    pub fn add_singleton_with<T, F>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<T, BoxError> + Send + Sync + 'static,
    {
        self.add_factory(Lifetime::Singleton, factory)
    }

    /// Registers a factory for `T` with one instance per scope.
    pub fn add_scoped_with<T, F>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<T, BoxError> + Send + Sync + 'static,
    {
        self.add_factory(Lifetime::Scoped, factory)
    }

    /// Registers a factory for `T` that runs on every resolution.
    pub fn add_transient_with<T, F>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<T, BoxError> + Send + Sync + 'static,
    {
        self.add_factory(Lifetime::Transient, factory)
    }

    /// Registers an already constructed singleton.
    pub fn add_singleton_instance<T: Send + Sync + 'static>(&mut self, instance: T) -> &mut Self {
        self.push_unchecked::<T>(Lifetime::Singleton, Source::Instance(Arc::new(instance)))
    }

    /// Registers a factory producing the trait object `I`, with one instance
    /// shared for the life of the provider.
    ///
    /// Unlike [`add_singleton_as`](Self::add_singleton_as), the trait needs no
    /// `#[abstraction]`, so traits from other crates can be registered. The
    /// concrete type behind the returned `Arc` is not known, so errors and
    /// logs name these registrations by `I`.
    pub fn add_singleton_as_with<I, F>(&mut self, factory: F) -> &mut Self
    where
        I: ?Sized + Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<Arc<I>, BoxError> + Send + Sync + 'static,
    {
        self.add_factory_as(Lifetime::Singleton, factory)
    }

    /// Registers a factory producing the trait object `I`, with one instance
    /// per scope.
    pub fn add_scoped_as_with<I, F>(&mut self, factory: F) -> &mut Self
    where
        I: ?Sized + Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<Arc<I>, BoxError> + Send + Sync + 'static,
    {
        self.add_factory_as(Lifetime::Scoped, factory)
    }

    /// Registers a factory producing the trait object `I`, run on every
    /// resolution.
    ///
    /// The returned `Arc` is stored behind one more allocation, so each
    /// resolution allocates once beyond what the factory does.
    pub fn add_transient_as_with<I, F>(&mut self, factory: F) -> &mut Self
    where
        I: ?Sized + Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<Arc<I>, BoxError> + Send + Sync + 'static,
    {
        self.add_factory_as(Lifetime::Transient, factory)
    }

    /// Registers an already constructed trait object as a singleton.
    pub fn add_singleton_instance_as<I>(&mut self, instance: Arc<I>) -> &mut Self
    where
        I: ?Sized + Send + Sync + 'static,
    {
        self.push_trait_object::<I>(Lifetime::Singleton, Source::Instance(Arc::new(instance)))
    }

    /// Rejects at build any declared dependency that has no registration.
    ///
    /// Without it, a missing dependency surfaces when the service is first
    /// resolved. A `Vec<Arc<T>>` dependency is never missing, since it may be
    /// empty, and factories are not checked because their dependencies are
    /// not declared.
    pub fn validate_dependencies(&mut self) -> &mut Self {
        self.validation.dependencies = true;
        self
    }

    /// Rejects at build any singleton that depends on a scoped service,
    /// directly or through transients.
    ///
    /// Without it, such a singleton fails to resolve with
    /// [`ResolveError::ScopedFromRoot`](crate::ResolveError::ScopedFromRoot);
    /// it never silently keeps one scope's instance.
    pub fn validate_scopes(&mut self) -> &mut Self {
        self.validation.scopes = true;
        self
    }

    /// Freezes the registrations into a provider.
    ///
    /// Fails if registered services depend on each other in a cycle, or if an
    /// enabled check finds a problem; every problem found is reported.
    pub fn build(self) -> Result<ServiceProvider, BuildError> {
        let graph = Graph::new(&self.registrations);
        let mut issues: Vec<BuildIssue> = graph
            .cycles()
            .into_iter()
            .map(|path| BuildIssue::Cycle { path })
            .collect();
        if self.validation.dependencies {
            issues.extend(
                graph
                    .missing()
                    .into_iter()
                    .map(|path| BuildIssue::MissingDependency { path }),
            );
        }
        if self.validation.scopes {
            issues.extend(
                graph
                    .captive()
                    .into_iter()
                    .map(|path| BuildIssue::CaptiveDependency { path }),
            );
        }
        if !issues.is_empty() {
            return Err(BuildError::new(issues));
        }
        Ok(ServiceProvider::new(Container::new(self.registrations)))
    }

    fn add<T: Service>(&mut self, lifetime: Lifetime) -> &mut Self {
        self.add_service::<T, T>(lifetime, concrete_cast::<T>())
    }

    fn add_service<I: ?Sized + 'static, T: Service>(
        &mut self,
        lifetime: Lifetime,
        cast: Cast,
    ) -> &mut Self {
        let construct: ConstructFn =
            Arc::new(|resolver| T::construct(resolver).map(|service| Arc::new(service) as Erased));
        self.push(Registration {
            key: Key::of::<I>(),
            implementation: type_name::<T>(),
            lifetime,
            source: Source::Construct(construct),
            dependencies: Some(T::dependencies),
            cast,
            slot: 0,
        })
    }

    fn add_factory<T, F>(&mut self, lifetime: Lifetime, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<T, BoxError> + Send + Sync + 'static,
    {
        self.push_unchecked::<T>(lifetime, Source::Construct(factory_construct(factory)))
    }

    /// Registers a factory or instance whose dependencies are not declared.
    fn push_unchecked<T: Send + Sync + 'static>(
        &mut self,
        lifetime: Lifetime,
        source: Source,
    ) -> &mut Self {
        let key = Key::of::<T>();
        self.push(Registration {
            key,
            implementation: key.name,
            lifetime,
            source,
            dependencies: None,
            cast: concrete_cast::<T>(),
            slot: 0,
        })
    }

    fn add_factory_as<I, F>(&mut self, lifetime: Lifetime, factory: F) -> &mut Self
    where
        I: ?Sized + Send + Sync + 'static,
        F: Fn(&Resolver<'_>) -> Result<Arc<I>, BoxError> + Send + Sync + 'static,
    {
        self.push_trait_object::<I>(lifetime, Source::Construct(factory_construct(factory)))
    }

    /// Registers an `Arc<I>` stored as is, since an unsized `I` cannot be
    /// erased directly.
    fn push_trait_object<I>(&mut self, lifetime: Lifetime, source: Source) -> &mut Self
    where
        I: ?Sized + Send + Sync + 'static,
    {
        let key = Key::of::<I>();
        let cast: fn(Erased) -> Option<Arc<I>> = |instance| {
            instance
                .downcast::<Arc<I>>()
                .ok()
                .map(|arc| Arc::clone(arc.as_ref()))
        };
        self.push(Registration {
            key,
            implementation: key.name,
            lifetime,
            source,
            dependencies: None,
            cast: Box::new(cast),
            slot: 0,
        })
    }

    fn push(&mut self, registration: Registration) -> &mut Self {
        self.registrations.push(registration);
        self
    }
}

/// Wraps a factory as a constructor, passing a dependency's resolution error
/// through unchanged.
fn factory_construct<T, F>(factory: F) -> ConstructFn
where
    T: Send + Sync + 'static,
    F: Fn(&Resolver<'_>) -> Result<T, BoxError> + Send + Sync + 'static,
{
    Arc::new(move |resolver| match factory(resolver) {
        Ok(service) => Ok(Arc::new(service) as Erased),
        Err(error) => Err(resolver.failure(error)),
    })
}

/// A boxed `fn(Erased) -> Option<Arc<I>>` for the registered service type `I`.
type Cast = Box<dyn Any + Send + Sync>;

fn trait_cast<I, T>() -> Cast
where
    I: ?Sized + CastFrom<T> + 'static,
    T: Send + Sync + 'static,
{
    let cast: fn(Erased) -> Option<Arc<I>> = |instance| instance.downcast::<T>().ok().map(I::cast);
    Box::new(cast)
}

fn concrete_cast<T: Send + Sync + 'static>() -> Cast {
    let cast: fn(Erased) -> Option<Arc<T>> = |instance| instance.downcast().ok();
    Box::new(cast)
}