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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
use std::{any::Any, sync::Arc};

use crate::Dependency;

use super::{Inject, Key, Provider, Result};

impl Inject {
    /// Retrieve a reference to a Dependency if it exists. Return a NotFound error if the TypeId
    /// isn't present.
    pub async fn get_type<T: Any + Send + Sync>(&self) -> Result<Arc<T>> {
        self.get_key(Key::from_type_id::<T>()).await
    }

    /// Retrieve a reference to a Dependency if it exists.
    pub async fn get_type_opt<T: Any + Send + Sync>(&self) -> Result<Option<Arc<T>>> {
        self.get_key_opt(Key::from_type_id::<T>()).await
    }

    /// Override an existing Dependency directly, using core::future::ready to wrap it in an
    /// immediately resolving Pending Future. Return true if the Key was already present.
    pub async fn override_type<T: Any + Send + Sync>(&self, dep: T) -> Result<bool> {
        self.override_key(Key::from_type_id::<T>(), dep).await
    }

    /// Provide a Dependency directly, using core::future::ready to wrap it in an immediately
    /// resolving Pending Future.
    pub async fn inject_type<T: Any + Send + Sync>(&self, dep: T) -> Result<()> {
        self.inject_key(Key::from_type_id::<T>(), dep).await
    }

    /// Replace an existing Dependency directly, using core::future::ready to wrap it in an
    /// immediately resolving Pending Future. Return a NotFound error if the TypeId isn't present.
    pub async fn replace_type<T: Any + Send + Sync>(&self, dep: T) -> Result<()> {
        self.replace_key(Key::from_type_id::<T>(), dep).await
    }

    /// Inject a Dependency Provider
    pub async fn provide_type<T: Any + Send + Sync>(
        &self,
        provider: impl Provider<T> + Provider<Dependency> + 'static,
    ) -> Result<()> {
        self.provide_key::<T>(Key::from_type_id::<T>(), provider)
            .await
    }

    /// Inject a replacement Dependency Provider if the TypeId is present
    pub async fn replace_type_with<T: Any + Send + Sync>(
        &self,
        provider: impl Provider<T> + Provider<Dependency> + 'static,
    ) -> Result<()> {
        self.replace_key_with::<T>(Key::from_type_id::<T>(), provider)
            .await
    }

    /// Remove a Dependency from the container and try to unwrap it from the Arc, which will only
    /// succeed if there are no other strong pointers to the value. Any Arcs handed out will still
    /// be valid, but the container will no longer hold a reference. Return a NotFound error if the
    /// TypeId isn't present.
    pub async fn consume_type<T: Any + Send + Sync>(&self) -> Result<T> {
        self.consume_key(Key::from_type_id::<T>()).await
    }

    /// Remove a Dependency from the container and try to unwrap it from the Arc, which will only
    /// succeed if there are no other strong pointers to the value. Any Arcs handed out will still
    /// be valid, but the container will no longer hold a reference.
    pub async fn consume_type_opt<T: Any + Send + Sync>(&self) -> Result<Option<T>> {
        self.consume_key_opt(Key::from_type_id::<T>()).await
    }

    /// Temporarily remove a dependency from the container and try to unwrap it from the Arc, which
    /// will only succeed if there are no other strong pointers to the value. Then, apply a function
    /// to it, and then inject sit back into the container.
    pub async fn modify_type<T, F>(&self, modify: F) -> Result<()>
    where
        T: Any + Send + Sync,
        F: FnOnce(T) -> Result<T>,
    {
        self.modify_key(Key::from_type_id::<T>(), modify).await
    }

    /// Discard a Dependency from the container. Any Arcs handed out will still be valid, but
    /// the container will no longer hold a reference.
    pub async fn remove_type<T: Any + Send + Sync>(&self) -> Result<()> {
        self.remove_key(Key::from_type_id::<T>()).await
    }

    /// Destroy the container and discard all Dependencies except for the given TypeId. Any Arcs
    /// handed out will still be valid, but the container will be fully unloaded and all references
    /// will be dropped. Return a NotFound error if the TypeId isn't present.
    pub async fn eject_type<T: Any + Send + Sync>(self) -> Result<T> {
        self.eject_key(Key::from_type_id::<T>()).await
    }

    /// Destroy the container and discard all Dependencies except for the given TypeId. Any Arcs
    /// handed out will still be valid, but the container will be fully unloaded and all references
    /// will be dropped.
    pub async fn eject_type_opt<T: Any + Send + Sync>(self) -> Result<Option<T>> {
        self.eject_key_opt(Key::from_type_id::<T>()).await
    }
}

#[cfg(test)]
pub(crate) mod test {
    use fake::Fake;
    use std::any::type_name;

    use crate::inject::{
        container::test::{HasId, OtherService, TestService},
        provider::test::{HasIdProvider, OtherServiceProvider, TestServiceProvider},
    };

    use super::*;

    #[tokio::test]
    async fn test_inject_success() -> Result<()> {
        let i = Inject::default();

        let service = TestService::new(fake::uuid::UUIDv4.fake());

        i.inject_type(service).await?;

        assert!(
            i.0.read()
                .await
                .contains_key(&Key::from_type_id::<TestService>()),
            "key does not exist in injection container"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_inject_occupied() -> Result<()> {
        let i = Inject::default();

        i.inject_type(TestService::new(fake::uuid::UUIDv4.fake()))
            .await?;

        // Inject the same type a second time
        let result = i
            .inject_type(TestService::new(fake::uuid::UUIDv4.fake()))
            .await;

        if let Err(err) = result {
            assert_eq!(
                format!("{} has already been provided", type_name::<TestService>()),
                err.to_string()
            );
        } else {
            panic!("did not return Err as expected")
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_get_opt_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.inject_type(TestService::new(expected.clone())).await?;

        let result = i.get_type_opt::<TestService>().await?.unwrap();

        assert_eq!(expected, result.id);

        Ok(())
    }

    #[tokio::test]
    async fn test_get_opt_vec_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.inject_type(vec![TestService::new(expected.clone())])
            .await?;

        let result = i.get_type_opt::<Vec<TestService>>().await?.unwrap();

        assert_eq!(expected, result[0].id);

        Ok(())
    }

    #[tokio::test]
    async fn test_get_opt_not_found() -> Result<()> {
        let i = Inject::default();

        let result = i.get_type_opt::<TestService>().await?;

        assert!(result.is_none());

        Ok(())
    }

    #[tokio::test]
    async fn test_get_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.inject_type(TestService::new(expected.clone())).await?;

        let result = i.get_type::<TestService>().await?;

        assert_eq!(expected, result.id);

        Ok(())
    }

    #[tokio::test]
    async fn test_dyn_get_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.inject_type::<Box<dyn HasId>>(Box::new(TestService::new(expected.clone())))
            .await?;

        let repo = i.get_type::<Box<dyn HasId>>().await?;

        assert_eq!(expected, repo.get_id());

        Ok(())
    }

    #[tokio::test]
    async fn test_get_not_found() -> Result<()> {
        let i = Inject::default();

        let result = i.get_type::<TestService>().await;

        if let Err(err) = result {
            let expected = format!(
                "{} was not found\n\nAvailable: (empty)",
                type_name::<TestService>(),
            );

            assert!(err.to_string().contains(&expected));
        } else {
            panic!("did not return Err as expected")
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_replace_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.inject_type(TestService::new(fake::uuid::UUIDv4.fake()))
            .await?;

        // Override the instance that was injected the first time
        i.replace_type(TestService {
            id: expected.clone(),
        })
        .await?;

        let result = i.get_type::<TestService>().await?;

        assert_eq!(expected, result.id);

        Ok(())
    }

    #[tokio::test]
    async fn test_replace_not_found() -> Result<()> {
        let i = Inject::default();

        i.inject_type(Box::new(TestService::new(fake::uuid::UUIDv4.fake())))
            .await?;
        i.inject_type::<Box<dyn HasId>>(Box::new(OtherService::new(fake::uuid::UUIDv4.fake())))
            .await?;

        // Override a type that doesn't have any instances yet
        let result = i
            .replace_type(Box::new(OtherService {
                other_id: fake::uuid::UUIDv4.fake(),
            }))
            .await;

        if let Err(err) = result {
            let message = err.to_string();

            assert!(message.contains(&format!(
                "{} was not found\n\nAvailable:",
                type_name::<Box<OtherService>>()
            )));

            assert!(message.contains(&format!("\n - {}", type_name::<Box<TestService>>())));
            assert!(message.contains(&format!("\n - {}", type_name::<Box<dyn HasId>>())));
        } else {
            panic!("did not return Err as expected")
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_provide_type_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        assert!(
            i.0.read()
                .await
                .contains_key(&Key::from_type_id::<TestService>()),
            "key does not exist in injection container"
        );

        let service = i.get_type::<TestService>().await?;

        assert_eq!(service.id, expected);

        Ok(())
    }

    #[tokio::test]
    async fn test_provide_type_multiple_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();
        let expected_other: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        i.provide_type::<OtherService>(OtherServiceProvider::new(expected_other.clone()))
            .await?;

        let service = i.get_type::<TestService>().await?;
        let other = i.get_type::<OtherService>().await?;

        assert_eq!(service.id, expected);
        assert_eq!(other.other_id, expected_other);

        Ok(())
    }

    #[tokio::test]
    async fn test_provide_type_dyn_success() -> Result<()> {
        let i = Inject::default();

        i.provide_type::<Box<dyn HasId>>(HasIdProvider::default())
            .await?;

        assert!(
            i.0.read()
                .await
                .contains_key(&Key::from_type_id::<Box<dyn HasId>>()),
            "key does not exist in injection container"
        );

        let service = i.get_type::<Box<dyn HasId>>().await?;

        assert_eq!(service.get_id(), "test-service");

        Ok(())
    }

    #[tokio::test]
    async fn test_provide_type_occupied() -> Result<()> {
        let i = Inject::default();

        let expected = format!("{} has already been provided", type_name::<TestService>());

        i.provide_type::<TestService>(TestServiceProvider::new(fake::uuid::UUIDv4.fake()))
            .await?;

        let result = i
            .provide_type::<TestService>(TestServiceProvider::new(fake::uuid::UUIDv4.fake()))
            .await;

        if let Err(err) = result {
            assert_eq!(err.to_string(), expected);
        } else {
            panic!("did not return Err as expected")
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_replace_type_with_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(fake::uuid::UUIDv4.fake()))
            .await?;

        // Retrieve the dependency once to trigger the Provider
        i.get_type::<TestService>().await?;

        // Override the instance that was injected the first time
        i.replace_type_with::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        let result = i.get_type::<TestService>().await?;

        assert_eq!(result.id, expected);

        Ok(())
    }

    #[tokio::test]
    async fn test_replace_type_with_multiple() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();
        let expected_other: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(fake::uuid::UUIDv4.fake()))
            .await?;

        i.provide_type::<OtherService>(OtherServiceProvider::new(fake::uuid::UUIDv4.fake()))
            .await?;

        // Retrieve the dependencies once to trigger the Providers
        i.get_type::<TestService>().await?;
        i.get_type::<OtherService>().await?;

        // Override the instances that were injected the first time
        i.replace_type_with::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        i.replace_type_with::<OtherService>(OtherServiceProvider::new(expected_other.clone()))
            .await?;

        let result = i.get_type::<TestService>().await?;
        let other = i.get_type::<OtherService>().await?;

        assert_eq!(result.id, expected);
        assert_eq!(other.other_id, expected_other);

        Ok(())
    }

    #[tokio::test]
    async fn test_replace_type_with_not_found() -> Result<()> {
        let i = Inject::default();

        let expected = format!(
            "{} was not found\n\nAvailable:\n - {}",
            type_name::<OtherService>(),
            type_name::<TestService>()
        );

        i.provide_type::<TestService>(TestServiceProvider::new(fake::uuid::UUIDv4.fake()))
            .await?;

        // Override a type that doesn't have any instances yet
        let result = i
            .replace_type_with::<OtherService>(OtherServiceProvider::new(fake::uuid::UUIDv4.fake()))
            .await;

        if let Err(err) = result {
            assert!(err.to_string().contains(&expected));
        } else {
            panic!("did not return Err as expected")
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_consume_type_provider_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        let result = i.consume_type::<TestService>().await?;

        assert_eq!(result.id, expected);

        assert!(
            !i.0.read()
                .await
                .contains_key(&Key::from_type_id::<TestService>()),
            "key still exists in injection container"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_consume_type_pending_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        // Trigger the Provider so that the value is Pending below
        i.get_type::<TestService>().await?;

        let result = i.consume_type::<TestService>().await?;

        assert_eq!(result.id, expected);

        assert!(
            !i.0.read()
                .await
                .contains_key(&Key::from_type_id::<TestService>()),
            "key still exists in injection container"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_consume_type_pending_multiple() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();
        let expected_other: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        i.provide_type::<OtherService>(OtherServiceProvider::new(expected_other.clone()))
            .await?;

        // Trigger the Providers so that the values are Pending below
        i.get_type::<TestService>().await?;
        i.get_type::<OtherService>().await?;

        let result = i.consume_type::<TestService>().await?;
        let other = i.consume_type::<OtherService>().await?;

        assert_eq!(result.id, expected);
        assert_eq!(other.other_id, expected_other);

        assert!(
            !i.0.read()
                .await
                .contains_key(&Key::from_type_id::<TestService>()),
            "key still exists in injection container"
        );

        assert!(
            !i.0.read()
                .await
                .contains_key(&Key::from_type_id::<OtherService>()),
            "key still exists in injection container"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_remove_type_provider_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        i.remove_type::<TestService>().await?;

        assert!(
            !i.0.read()
                .await
                .contains_key(&Key::from_type_id::<TestService>()),
            "key still exists in injection container"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_remove_type_pending_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        // Trigger the Provider so that the value is Pending below
        i.get_type::<TestService>().await?;

        i.remove_type::<TestService>().await?;

        assert!(
            !i.0.read()
                .await
                .contains_key(&Key::from_type_id::<TestService>()),
            "key still exists in injection container"
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_eject_key_pending_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.inject_type::<TestService>(TestService::new(expected.clone()))
            .await?;

        let service = i.eject_type::<TestService>().await?;

        // This is commented out because it demonstrates a case prevented by the compiler - usage
        // of the container after ejection.
        //
        // i.get_type::<TestService>().await?;

        assert_eq!(service.id, expected);

        Ok(())
    }

    #[tokio::test]
    async fn test_eject_key_provider_success() -> Result<()> {
        let i = Inject::default();

        let expected: String = fake::uuid::UUIDv4.fake();

        i.provide_type::<TestService>(TestServiceProvider::new(expected.clone()))
            .await?;

        let service = i.eject_type::<TestService>().await?;

        assert_eq!(service.id, expected);

        Ok(())
    }
}