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
use crate::container::{
    Container, ConvertContainer, InstanceContainer, SingletonContainer, TransientContainer,
};
use crate::index::{ParentIndex, SelfIndex};
use frunk::hlist::{HList, Selector};
use frunk::{HCons, HNil};
use std::ops::Deref;
use std::rc::Rc;
use std::sync::Arc;

/// `ServiceProvider` struct is used as an IoC-container in which you declare your dependencies.
///
/// Algorithm for working in `ServiceProvider` is:
/// 1. Create an empty by `ServiceProvider::new` function.
/// 2. Declare your dependencies using `add_*` methods (more about theirs read below).
/// 3. Fork `ServiceProvider` when you need working with scoped sessions (like when you processing web request).
/// 4. Get needed dependencies from container using `Resolver::resolve` trait.
///
/// If you do not register all of needed dependencies, then compiler do not compile your code. If error
/// puts you into a stupor, read our [manual] about how read errors.
///
/// [manual]: https://github.com/p0lunin/teloc/blob/master/HOW-TO-READ-ERRORS.md
///
/// Example of usage `ServiceProvider`:
/// ```
/// use std::rc::Rc;
/// use teloc::*;
///
/// struct ConstService {
///     number: Rc<i32>,
/// }
///
/// #[inject]
/// impl ConstService {
///     pub fn new(number: Rc<i32>) -> Self {
///         ConstService { number }
///     }
/// }
///
/// #[derive(Dependency)]
/// struct Controller {
///     number_service: ConstService,
/// }
///
/// let container = ServiceProvider::new()
///     .add_transient::<ConstService>()
///     .add_transient::<Controller>();
/// let scope = container.fork().add_instance(Rc::new(10));
/// let controller: Controller = scope.resolve();
/// assert_eq!(*controller.number_service.number, 10);
/// ```
#[derive(Debug)]
pub struct ServiceProvider<Parent, Conts> {
    parent: Parent,
    containers: Conts,
}

#[derive(Debug)]
pub struct EmptyServiceProvider;

impl ServiceProvider<EmptyServiceProvider, HNil> {
    /// Create an empty instance of `ServiceProvider`
    pub fn new() -> Self {
        ServiceProvider {
            parent: EmptyServiceProvider,
            containers: HNil,
        }
    }
}

impl Default for ServiceProvider<EmptyServiceProvider, HNil> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Parent, Conts> ServiceProvider<Parent, Conts> {
    pub(crate) fn dependencies(&self) -> &Conts {
        &self.containers
    }

    /// Forking `ServiceProvider` creates a new `ServiceProvider` with reference to the parent.
    /// `resolve` method on forked `ServiceProvider` will find dependencies form self and parent.
    pub fn fork(&self) -> ServiceProvider<&Self, HNil> {
        ServiceProvider {
            parent: self,
            containers: HNil,
        }
    }

    /// Forking `ServiceProvider` creates a new `ServiceProvider` with reference to the parent.
    /// `resolve` method on forked `ServiceProvider` will find dependencies form self and parent.
    pub fn fork_rc(self: &Rc<ServiceProvider<Parent, Conts>>) -> ServiceProvider<Rc<Self>, HNil> {
        ServiceProvider {
            parent: self.clone(),
            containers: HNil,
        }
    }

    /// Forking `ServiceProvider` creates a new `ServiceProvider` with reference to the parent.
    /// `resolve` method on forked `ServiceProvider` will find dependencies form self and parent.
    pub fn fork_arc(
        self: &Arc<ServiceProvider<Parent, Conts>>,
    ) -> ServiceProvider<Arc<Self>, HNil> {
        ServiceProvider {
            parent: self.clone(),
            containers: HNil,
        }
    }
}

// Clippy requires to create type aliases
type ContainerTransientAddConvert<Parent, T, U, Conts> =
    ServiceProvider<Parent, HCons<ConvertContainer<TransientContainer<T>, T, U>, Conts>>;
type ContainerSingletonAddConvert<Parent, T, U, Conts> =
    ServiceProvider<Parent, HCons<ConvertContainer<SingletonContainer<T>, T, U>, Conts>>;
type ContainerInstanceAddConvert<Parent, T, U, Conts> =
    ServiceProvider<Parent, HCons<ConvertContainer<InstanceContainer<T>, T, U>, Conts>>;

impl<Parent, Conts: HList> ServiceProvider<Parent, Conts> {
    /// Method used primary for internal actions. In common usage you don't need to use it. It add dependencies to the store. You need
    /// to put in first generic parameter some `ContainerElem` type.
    /// Usage:
    ///
    /// ```
    /// use teloc::*;
    /// use teloc::dev::container::TransientContainer;
    ///
    /// struct Service {
    ///     data: i32,
    /// }
    ///
    /// let sp = ServiceProvider::new()
    ///     ._add::<TransientContainer<Service>>(());
    /// ```
    pub fn _add<Cont: Container>(
        self,
        data: Cont::Data,
    ) -> ServiceProvider<Parent, HCons<Cont, Conts>> {
        let ServiceProvider { parent, containers } = self;
        ServiceProvider {
            parent,
            containers: containers.prepend(Container::init(data)),
        }
    }

    /// Add dependency with the `Transient` lifetime. Transient services will be created each time
    /// when it called. Use this lifetime for lightweight stateless services.
    ///
    /// Can be resolved only by ownership.
    ///
    /// Usage:
    /// ```
    /// use teloc::*;
    /// use uuid::Uuid;
    ///
    /// struct Service { uuid: Uuid }
    /// #[inject]
    /// impl Service {
    ///     fn new() -> Self { Self { uuid: Uuid::new_v4() } }
    /// }
    ///
    /// let sp = ServiceProvider::new()
    ///     .add_transient::<Service>();
    ///
    /// let s1: Service = sp.resolve();
    /// let s2: Service = sp.resolve();
    ///
    /// assert_ne!(s1.uuid, s2.uuid);
    /// ```
    pub fn add_transient<T>(self) -> ServiceProvider<Parent, HCons<TransientContainer<T>, Conts>>
    where
        TransientContainer<T>: Container<Data = ()>,
    {
        self._add::<TransientContainer<T>>(())
    }

    /// Add dependency with the `Singleton` lifetime. Singleton services will be created only one
    /// time when it will be called first time. It will be same between different calls in parent
    /// and forked `ServiceProvider`
    ///
    /// Can be resolved by reference or by cloning. If you wish to clone this dependency then it
    /// must implement `DependencyClone` trait. For more information see `DependencyClone` trait.
    ///
    /// Usage:
    /// ```
    /// use teloc::*;
    /// use uuid::Uuid;
    ///
    /// struct Service { uuid: Uuid }
    /// #[inject]
    /// impl Service {
    ///     fn new() -> Self { Self { uuid: Uuid::new_v4() } }
    /// }
    ///
    /// let sp = ServiceProvider::new()
    ///     .add_singleton::<Service>();
    /// let scope = sp.fork();
    ///
    /// let s1: &Service = sp.resolve();
    /// let s2: &Service = scope.resolve();
    ///
    /// assert_eq!(s1.uuid, s2.uuid);
    /// ```
    ///
    /// Usage with cloning:
    ///
    /// ```
    /// use teloc::*;
    /// use uuid::Uuid;
    /// use std::rc::Rc;
    ///
    /// struct Service { uuid: Uuid }
    /// #[inject]
    /// impl Service {
    ///     fn new() -> Self { Self { uuid: Uuid::new_v4() } }
    /// }
    ///
    /// let sp = ServiceProvider::new()
    ///     .add_singleton::<Rc<Service>>();
    ///
    /// let s1: Rc<Service> = sp.resolve();
    /// let s2: Rc<Service> = sp.resolve();
    ///
    /// assert_eq!(s1.uuid, s2.uuid)
    /// ```
    pub fn add_singleton<T>(self) -> ServiceProvider<Parent, HCons<SingletonContainer<T>, Conts>>
    where
        SingletonContainer<T>: Container<Data = ()>,
    {
        self._add::<SingletonContainer<T>>(())
    }

    /// Add anything instance to provider. It likes singleton, but it cannot get dependencies from
    /// the provider. Use it for adding single objects like configs.
    ///
    /// Can be resolved by reference or by cloning. If you wish to clone this dependency then it
    /// must implement `DependencyClone` trait. For more information see `DependencyClone` trait.
    ///
    /// Usage:
    /// ```
    /// use teloc::*;
    ///
    /// #[derive(Debug, PartialEq)]
    /// struct Config { token: String, ip: String }
    ///
    /// struct Service<'a> { token: &'a str, ip: &'a str }
    /// #[inject]
    /// impl<'a> Service<'a> {
    ///     fn new(config: &'a Config) -> Self { Self { token: &config.token, ip: &config.ip } }
    /// }
    ///
    /// let config = Config { token: "1234ABCDE".into(), ip: "192.168.0.1".into() };
    ///
    /// let sp = ServiceProvider::new()
    ///     .add_instance(&config)
    ///     .add_transient::<Service>();
    ///
    /// let config_ref: &Config = sp.resolve();
    /// let s: Service = sp.resolve();
    ///
    /// assert_eq!(&config, config_ref);
    /// assert_eq!(&config_ref.token, s.token);
    /// assert_eq!(&config_ref.ip, s.ip);
    /// ```
    pub fn add_instance<T>(
        self,
        data: T,
    ) -> ServiceProvider<Parent, HCons<InstanceContainer<T>, Conts>>
    where
        InstanceContainer<T>: Container<Data = T>,
    {
        self._add::<InstanceContainer<T>>(data)
    }

    /// Same as `ServiceProvider::add_transient`, but can be used for convert one type to another
    /// when resolving. Can be used for creating `Box<dyn Trait>` instances, for example.
    ///
    /// Suffix `_c` means 'convert'.
    ///
    /// Usage:
    /// ```
    /// use teloc::*;
    ///
    /// trait NumberService {
    ///     fn get_num(&self) -> i32;
    /// }
    ///
    /// struct TenService {
    ///     number: i32,
    /// }
    /// impl NumberService for TenService {
    ///     fn get_num(&self) -> i32 {
    ///         self.number
    ///     }
    /// }
    /// #[inject]
    /// impl TenService {
    ///     fn new() -> Self {
    ///         Self { number: 10 }
    ///     }
    /// }
    ///impl From<Box<TenService>> for Box<dyn NumberService> {
    ///     fn from(x: Box<TenService>) -> Self {
    ///         x
    ///     }
    /// }
    ///
    /// #[derive(Dependency)]
    /// struct Controller {
    ///     number_service: Box<dyn NumberService>,
    /// }
    ///
    /// let container = ServiceProvider::new()
    ///     .add_transient_c::<Box<dyn NumberService>, Box<TenService>>()
    ///     .add_transient::<Controller>();
    /// let controller: Controller = container.resolve();
    ///
    /// assert_eq!(controller.number_service.get_num(), 10);
    /// ```
    pub fn add_transient_c<U, T>(self) -> ContainerTransientAddConvert<Parent, T, U, Conts>
    where
        T: Into<U>,
        ConvertContainer<TransientContainer<T>, T, U>: Container<Data = ()>,
        TransientContainer<T>: Container<Data = ()>,
    {
        self._add::<ConvertContainer<TransientContainer<T>, T, U>>(())
    }

    /// Same as `Provider::add_transient_c` but for `Singleton` lifetime.
    pub fn add_singleton_c<U, T>(self) -> ContainerSingletonAddConvert<Parent, T, U, Conts>
    where
        T: Into<U>,
        ConvertContainer<SingletonContainer<T>, T, U>: Container<Data = ()>,
        SingletonContainer<T>: Container<Data = ()>,
    {
        self._add::<ConvertContainer<SingletonContainer<T>, T, U>>(())
    }

    /// Same as `Provider::add_transient_c` but for `Instance` lifetime.
    pub fn add_instance_c<U, T>(
        self,
        instance: T,
    ) -> ContainerInstanceAddConvert<Parent, T, U, Conts>
    where
        T: Into<U>,
        ConvertContainer<InstanceContainer<T>, T, U>: Container<Data = T>,
        InstanceContainer<T>: Container<Data = T>,
    {
        self._add::<ConvertContainer<InstanceContainer<T>, T, U>>(instance)
    }
}

impl<Parent, Conts, T, Index> Selector<T, SelfIndex<Index>> for ServiceProvider<Parent, Conts>
where
    Conts: Selector<T, Index>,
{
    fn get(&self) -> &T {
        self.dependencies().get()
    }

    /// NEVER CALL THIS
    fn get_mut(&mut self) -> &mut T {
        unreachable!()
    }
}

impl<Parent, Conts, T, Index> Selector<T, ParentIndex<Index>> for ServiceProvider<Parent, Conts>
where
    Parent: Deref,
    Parent::Target: Selector<T, Index>,
{
    fn get(&self) -> &T {
        self.parent.deref().get()
    }

    /// NEVER CALL THIS
    fn get_mut(&mut self) -> &mut T {
        unreachable!()
    }
}