app_ctx 0.1.5

An AppCtx implementation in Rust, like ApplicationContext in SpringBoot
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
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
mod error;

use crate::error::{AppContextDroppedError, BeanError};
use once_cell::sync::OnceCell;
use std::any::{type_name, Any};
use std::collections::HashMap;
use std::fmt::Debug;
use std::future::Future;
use std::marker::PhantomData;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};

/// metadata of a bean. it can be used as map key
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub struct BeanMetadata {
    /// typename of the bean, such as `XXXService`
    type_name: &'static str,
    /// an identifier for the bean, to distinguish different
    /// beans with same type name
    bean_name: &'static str,
}

impl BeanMetadata {
    pub(crate) fn build_meta<T>(name: &'static str) -> BeanMetadata {
        BeanMetadata {
            type_name: type_name::<T>(),
            bean_name: name,
        }
    }
}

/// A trait for beans which can be created from `AppContextBuilder`.
/// `ctx` is the AppContext for acquiring lazy-initialized beans,
/// and `extras` are extra params for this build.
pub trait BuildFromContext<E, CtxErr = (), InitErr = ()> {
    /// build the beans from
    fn build_from(ctx: &AppContextBuilder, extras: E) -> Result<Self, CtxErr>
    where
        Self: Sized;

    /// initialization method after all beans have been built.
    /// because of potential cyclic invocations during the initialization, only
    /// immutable references are allowed
    fn init_self(&self) -> Result<(), InitErr> {
        return Ok(());
    }
}

/// async implementation for building context
#[async_trait::async_trait]
pub trait BuildFromContextAsync<E, CtxErr = (), InitErr = ()> {
    async fn build_from(ctx: &AppContextBuilder, extras: E) -> Result<Self, CtxErr>
    where
        Self: Sized;

    /// initialization method after all beans have been built.
    /// because of potential cyclic invocations during the initialization, only
    /// immutable references are allowed
    async fn init_self(&self) -> Result<(), InitErr> {
        return Ok(());
    }
}

/// like `Class<T>` in java
pub struct BeanType<T>(PhantomData<T>);

pub trait BeanTypeOf<T> {
    const BEAN_TYPE: BeanType<T>;
}

impl<T> BeanTypeOf<T> for T {
    const BEAN_TYPE: BeanType<T> = BeanType(PhantomData);
}

/// make the usage easier
pub struct RefWrapper<T>(Arc<OnceCell<T>>);

impl<T> Deref for RefWrapper<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.0.get().expect("bean is not initialized properly")
    }
}

/// the weak reference of bean, avoiding circular references
pub struct BeanRef<T> {
    inner: Weak<OnceCell<T>>,
}

impl<T> BeanRef<T> {
    /// acquire the bean, if corresponding app context is dropped, `None`
    /// will be returned
    pub fn try_acquire(&self) -> Result<RefWrapper<T>, AppContextDroppedError> {
        self.inner
            .upgrade()
            .map(|c| RefWrapper(c))
            .ok_or(AppContextDroppedError)
    }

    /// acquire the bean, if corresponding app context is dropped,
    /// a panic will be thrown
    pub fn acquire(&self) -> RefWrapper<T> {
        self.try_acquire()
            .expect("app context is dropped, all beans are not acquirable")
    }

    /// check whether the `AppContext` related to this bean is dropped
    pub fn is_active(&self) -> bool {
        self.try_acquire().is_ok()
    }
}

/// a wrapper for `Arc<dyn Any +Send +Sync>`, to store helper data
pub struct BeanWrapper {
    bean: Arc<dyn Any + Send + Sync>,
    initialized: AtomicBool,
    meta: BeanMetadata,
}

impl Clone for BeanWrapper {
    fn clone(&self) -> Self {
        Self {
            bean: self.bean.clone(),
            initialized: AtomicBool::new(self.initialized.load(Ordering::Acquire)),
            meta: self.meta.clone(),
        }
    }
}

impl BeanWrapper {
    /// wrap a `OnceCell` and meta, to erase its type
    pub(crate) fn wrap<T>(bean: OnceCell<T>, meta: BeanMetadata) -> Self
    where
        T: Send + Sync + 'static,
    {
        Self {
            initialized: AtomicBool::new(bean.get().is_some()),
            bean: Arc::new(bean),
            meta,
        }
    }

    /// because we do not know its type, we cannot downcast
    /// it into OnceCell, so we need to use an extra field
    pub(crate) fn initialized(&self) -> bool {
        self.initialized.load(Ordering::Acquire)
    }

    /// build `BeanRef<T>` from inner arc
    pub(crate) fn build_bean_ref<T>(&self) -> BeanRef<T>
    where
        T: Send + Sync + 'static,
    {
        let weak_arc = self
            .bean
            .clone()
            .downcast::<OnceCell<T>>()
            .ok()
            .map(|c| Arc::downgrade(&c))
            .expect("bean type is not matched");
        BeanRef { inner: weak_arc }
    }

    /// wrap the bean into it
    pub(crate) fn set_inner<T>(&self, bean: T)
    where
        T: Send + Sync + 'static,
    {
        self.bean
            .clone()
            .downcast::<OnceCell<T>>()
            .ok()
            .map(|c| c.set(bean).ok())
            .flatten()
            .expect("bean is setted before");
        self.initialized.store(true, Ordering::Release);
    }
}

/// the inner storage for beans.
/// the `Arc<...>` stores beans with lazy initialization
pub struct AppContextInner {
    bean_map: HashMap<BeanMetadata, BeanWrapper>,
}

/// the context to store all beans.
/// `AppContext` owns the ownership of all registered beans.
/// When `AppContext` is dropped, all beans will be dropped too
pub struct AppContextBuilder {
    inner: Mutex<AppContextInner>,
    init_fn_map: HashMap<BeanMetadata, InitFnEnum>,
}

impl AppContextBuilder {
    /// init method
    pub fn new() -> Self {
        Self {
            inner: Mutex::new(AppContextInner {
                bean_map: Default::default(),
            }),
            init_fn_map: Default::default(),
        }
    }

    /// acquire the `BeanRef` of a bean.
    /// because of the initialization order, returned `BeanRef` may not be initialized.
    /// the method `acquire_bean_or_init` only requires immutable reference, so
    /// the beans which implements `BuildFromContext` can invoke it during the construction
    pub fn acquire_bean_or_init<T>(&self, _ty: BeanType<T>, name: &'static str) -> BeanRef<T>
    where
        T: Send + Sync + 'static,
    {
        let meta = BeanMetadata::build_meta::<T>(name);

        self.inner
            .lock()
            .expect("unexpected lock")
            .bean_map
            .entry(meta.clone())
            .or_insert(BeanWrapper::wrap(OnceCell::<T>::new(), meta))
            .build_bean_ref()
    }

    /// construct a bean and hand over to `AppContextBuilder`.
    /// the bean type must implement `BuildFromContext`
    pub fn construct_bean<T, E, Err, Err2>(
        mut self,
        _ty: BeanType<T>,
        name: &'static str,
        extras: E,
    ) -> Result<Self, Err>
    where
        T: Send + Sync + BuildFromContext<E, Err, Err2> + 'static,
        Err2: Send + Sync + 'static,
    {
        let meta = BeanMetadata::build_meta::<T>(name);
        let bean = T::build_from(&self, extras)?;
        self.inner
            .lock()
            .expect("unexpected lock")
            .bean_map
            .entry(meta.clone())
            .or_insert(BeanWrapper::wrap(OnceCell::<T>::new(), meta.clone()))
            .set_inner(bean);
        self.init_fn_map
            .insert(meta.clone(), build_init_fn::<E, Err, Err2, T>());
        Ok(self)
    }

    /// construct a bean and hand over to `AppContextBuilder`.
    /// the bean type must implement `BuildFromContextAsync`
    pub async fn construct_bean_async<T, E, Err, Err2>(
        mut self,
        _ty: BeanType<T>,
        name: &'static str,
        extras: E,
    ) -> Result<Self, Err>
    where
        T: Send + Sync + BuildFromContextAsync<E, Err, Err2> + 'static,
        Err2: Send + Sync + 'static,
    {
        let meta = BeanMetadata::build_meta::<T>(name);
        let bean = T::build_from(&self, extras).await?;
        self.inner
            .lock()
            .expect("unexpected lock")
            .bean_map
            .entry(meta.clone())
            .or_insert(BeanWrapper::wrap(OnceCell::<T>::new(), meta.clone()))
            .set_inner(bean);
        self.init_fn_map
            .insert(meta.clone(), build_init_fn_async::<E, Err, Err2, T>());
        Ok(self)
    }

    /// finish construction and create `AppContext` without Mutex.
    /// this method will go over all beans and ensure all beans are initialized,
    /// but the initialization method will not be ran
    pub fn build_without_init(self) -> Result<AppContext, BeanError> {
        if let Some((uninit_meta, _)) = self
            .inner
            .lock()
            .expect("unexpected lock")
            .bean_map
            .iter()
            .find(|(meta, bean)| !bean.initialized())
        {
            return Err(BeanError::NotInitialized(uninit_meta.clone()));
        }
        Ok(AppContext {
            inner: Arc::new(self.inner.into_inner().expect("unexpected lock")),
        })
    }

    pub fn build_non_async(self) -> Result<AppContext, BeanError> {
        {
            let wrapper = self.inner.lock().expect("unexpected lock");
            if let Some((uninit_meta, _)) = wrapper
                .bean_map
                .iter()
                .find(|(meta, bean)| !bean.initialized())
            {
                return Err(BeanError::NotInitialized(uninit_meta.clone()));
            }
            for (k, v) in self.init_fn_map {
                let wrapper_cloned = wrapper
                    .bean_map
                    .get(&k)
                    .expect("unexpected meta key error")
                    .clone();
                if let InitFnEnum::Sync(f) = v {
                    f(wrapper_cloned)?;
                } else {
                    return Err(BeanError::HasAsync(k));
                }
            }
        }
        Ok(AppContext {
            inner: Arc::new(self.inner.into_inner().expect("unexpected lock")),
        })
    }

    pub async fn build_all(self) -> Result<AppContext, BeanError> {
        {
            let wrapper = self.inner.lock().expect("unexpected lock");
            if let Some((uninit_meta, _)) = wrapper
                .bean_map
                .iter()
                .find(|(meta, bean)| !bean.initialized())
            {
                return Err(BeanError::NotInitialized(uninit_meta.clone()));
            }
            for (k, v) in self.init_fn_map {
                let wrapper_cloned = wrapper
                    .bean_map
                    .get(&k)
                    .expect("unexpected meta key error")
                    .clone();
                match v {
                    InitFnEnum::Sync(f) => {
                        f(wrapper_cloned)?;
                    }
                    InitFnEnum::Async(fut) => {
                        fut(wrapper_cloned).await?;
                    }
                }
            }
        }
        Ok(AppContext {
            inner: Arc::new(self.inner.into_inner().expect("unexpected lock")),
        })
    }
}

/// the wrapper of initialization function
pub(crate) type InitFn = Box<dyn Fn(BeanWrapper) -> Result<(), BeanError>>;
pub(crate) type InitFnAsync =
    Box<dyn Fn(BeanWrapper) -> Pin<Box<dyn Future<Output = Result<(), BeanError>>>>>;

pub(crate) enum InitFnEnum {
    Sync(InitFn),
    Async(InitFnAsync),
}

/// helper method to build `InitFn`
pub(crate) fn build_init_fn<Props, E1, E2, T>() -> InitFnEnum
where
    E2: Send + Sync + 'static,
    T: BuildFromContext<Props, E1, E2> + Send + Sync + 'static,
{
    InitFnEnum::Sync(Box::new(|wrap| {
        let r = wrap.build_bean_ref::<T>().acquire();
        match r.init_self() {
            Ok(_) => Ok(()),
            Err(e) => Err(BeanError::DuringInit(wrap.meta.clone(), Box::new(e))),
        }
    }))
}

/// helper method to build `InitFnAsync`
pub(crate) fn build_init_fn_async<Props, E1, E2, T>() -> InitFnEnum
where
    E2: Send + Sync + 'static,
    T: BuildFromContextAsync<Props, E1, E2> + Send + Sync + 'static,
{
    InitFnEnum::Async(Box::new(|wrap| {
        Box::pin(async move {
            let r = wrap.build_bean_ref::<T>().acquire();
            match r.init_self().await {
                Ok(_) => Ok(()),
                Err(e) => Err(BeanError::DuringInit(wrap.meta.clone(), Box::new(e))),
            }
        })
    }))
}

/// the context to store all beans.
/// `AppContext` owns the ownership of all registered beans.
/// When `AppContext` is dropped, all beans will be dropped too
pub struct AppContext {
    inner: Arc<AppContextInner>,
}

impl Clone for AppContext {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl AppContext {
    /// the method `try_acquire_bean` can be used to get bean from runtime,
    /// like `ApplicationContext` in SpringBoot
    pub fn try_acquire_bean<T>(&self, name: &'static str) -> Option<BeanRef<T>>
    where
        T: Send + Sync + 'static,
    {
        let meta = BeanMetadata::build_meta::<T>(name);

        self.inner
            .bean_map
            .get(&meta)
            .cloned()
            .map(|w| w.build_bean_ref())
    }

    pub fn acquire_bean<T>(&self, _ty: BeanType<T>, name: &'static str) -> BeanRef<T>
    where
        T: Send + Sync + 'static,
    {
        self.try_acquire_bean(name)
            .expect("bean is not initialized")
    }

    /// the method `try_acquire_beans_by_type` can be used to get multiple beans with same type
    pub fn acquire_beans_by_type<T>(&self, _ty: BeanType<T>) -> Vec<BeanRef<T>>
    where
        T: Send + Sync + 'static,
    {
        self.inner
            .bean_map
            .iter()
            .filter(|(k, v)| k.type_name == type_name::<T>())
            .map(|(k, v)| v.clone().build_bean_ref())
            .collect()
    }

    /// the method `try_acquire_beans_by_name` can be used to get multiple beans with same name
    pub fn acquire_beans_by_name<T>(&self, name: &'static str) -> Vec<BeanRef<T>>
    where
        T: Send + Sync + 'static,
    {
        self.inner
            .bean_map
            .iter()
            .filter(|(k, v)| k.bean_name == name)
            .map(|(k, v)| v.clone().build_bean_ref())
            .collect()
    }

    /// whether current `AppContext` do not contains any arc clone
    pub fn is_last_clone(&self)->bool{
        Arc::strong_count(&self.inner)==1
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::bail;
    use async_trait::async_trait;
    use std::time::Duration;

    pub struct ServiceA {
        svc_b: BeanRef<ServiceB>,

        dao: BeanRef<DaoC>,
    }

    impl ServiceA {
        pub fn check(&self) {
            println!("svc a is ready");
        }
    }

    impl Drop for ServiceA {
        fn drop(&mut self) {
            println!("svc a is dropped");
        }
    }

    impl BuildFromContext<(), ()> for ServiceA {
        fn build_from(ctx: &AppContextBuilder, extras: ()) -> Result<Self, ()> {
            Ok(ServiceA {
                svc_b: ctx.acquire_bean_or_init(ServiceB::BEAN_TYPE, "b"),

                dao: ctx.acquire_bean_or_init(DaoC::BEAN_TYPE, "c"),
            })
        }
    }

    pub struct ServiceB {
        svc_a: BeanRef<ServiceA>,

        dao: BeanRef<DaoC>,

        config_val: u32,
    }

    impl Drop for ServiceB {
        fn drop(&mut self) {
            println!("svc b is dropped");
        }
    }

    impl ServiceB {
        pub fn check(&self) {
            println!("svc b is ready");
        }
    }

    impl BuildFromContext<u32, (), anyhow::Error> for ServiceB {
        fn build_from(ctx: &AppContextBuilder, extras: u32) -> Result<Self, ()> {
            Ok(ServiceB {
                svc_a: ctx.acquire_bean_or_init(ServiceA::BEAN_TYPE, "a"),
                dao: ctx.acquire_bean_or_init(DaoC::BEAN_TYPE, "c"),
                config_val: extras,
            })
        }

        fn init_self(&self) -> Result<(), anyhow::Error> {
            Ok(())
        }
    }

    pub struct DaoC {
        inner_map: HashMap<String, String>,
    }

    impl Drop for DaoC {
        fn drop(&mut self) {
            println!("dao c is dropped");
        }
    }

    impl DaoC {
        pub fn check(&self) {
            println!("dao c is ready");
        }
    }

    impl BuildFromContext<HashMap<String, String>, ()> for DaoC {
        fn build_from(
            ctx: &AppContextBuilder,
            extras: HashMap<String, String>,
        ) -> Result<Self, ()> {
            Ok(DaoC { inner_map: extras })
        }
    }

    pub struct DaoD {
        inner_vec: Vec<i32>,
    }

    impl Drop for DaoD {
        fn drop(&mut self) {
            println!("dao d is droped");
        }
    }

    impl DaoD {
        pub async fn check(&self) {
            println!("dao d is ready");
        }
    }

    #[async_trait]
    impl BuildFromContextAsync<usize, String> for DaoD {
        async fn build_from(ctx: &AppContextBuilder, extras: usize) -> Result<Self, String> {
            Ok(DaoD {
                inner_vec: Vec::with_capacity(extras),
            })
        }

        async fn init_self(&self) -> Result<(), ()> {
            tokio::time::sleep(Duration::from_millis(500)).await;
            Ok(())
        }
    }

    #[tokio::test]
    async fn it_works() -> anyhow::Result<()> {
        let svc_a = {
            //register beans with circular references
            let ctx = AppContextBuilder::new()
                .construct_bean(ServiceA::BEAN_TYPE, "a", ())
                .unwrap()
                .construct_bean(ServiceB::BEAN_TYPE, "b", 32)
                .unwrap()
                .construct_bean(DaoC::BEAN_TYPE, "c", HashMap::new())
                .unwrap()
                .construct_bean_async(DaoD::BEAN_TYPE, "d", 5_usize)
                .await
                .unwrap()
                .build_all()
                .await?;

            //test each bean
            let svc_a = ctx.acquire_bean(ServiceA::BEAN_TYPE, "a");
            svc_a.acquire().check();

            let svc_b = ctx.acquire_bean(ServiceB::BEAN_TYPE, "b");
            svc_b.acquire().check();

            let dao_c = ctx.acquire_bean(DaoC::BEAN_TYPE, "c");
            dao_c.acquire().check();

            let dao_d = ctx.acquire_bean(DaoD::BEAN_TYPE, "d");
            dao_d.acquire().check().await;

            assert!(ctx.is_last_clone());
            //finally, all beans should be dropped

            svc_a
        };
        //if the app context is dropped, all beans become invalid
        assert!(!svc_a.is_active());

        //there will be an error if some beans are not set
        let ctx = AppContextBuilder::new()
            .construct_bean(ServiceA::BEAN_TYPE, "a", ())
            .unwrap()
            .build_without_init();
        assert!(ctx.is_err());

        Ok(())
    }
}