ntex-service 4.6.0

ntex service
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
//! Shared configuration for services
#![allow(
    clippy::should_implement_trait,
    clippy::new_ret_no_self,
    clippy::missing_panics_doc
)]
use std::any::{Any, TypeId};
use std::cell::{RefCell, UnsafeCell};
use std::sync::{Arc, atomic::AtomicUsize, atomic::Ordering};
use std::{fmt, hash::Hash, hash::Hasher, marker::PhantomData, mem, ops, ptr, rc};

type Key = (usize, TypeId);
type HashMap<K, V> = std::collections::HashMap<K, V, foldhash::fast::RandomState>;

thread_local! {
    static DEFAULT_CFG: Arc<Storage> = {
        let mut st = Arc::new(Storage::new("--", "", false, CfgContext(ptr::null())));
        let p = Arc::as_ptr(&st);
        Arc::get_mut(&mut st).unwrap().ctx.update(p);
        st
    };
    static MAPPING: RefCell<HashMap<Key, Arc<dyn Any + Send + Sync>>> = {
        RefCell::new(HashMap::default())
    };
}
static IDX: AtomicUsize = AtomicUsize::new(0);
const KIND_ARC: usize = 1;
const KIND_UNMASK: usize = !KIND_ARC;

pub trait Configuration: Default + Send + Sync + fmt::Debug + 'static {
    const NAME: &'static str;

    fn ctx(&self) -> &CfgContext;

    fn set_ctx(&mut self, ctx: CfgContext);
}

#[derive(Debug)]
struct Storage {
    id: usize,
    tag: &'static str,
    service: &'static str,
    ctx: CfgContext,
    building: bool,
    data: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl Storage {
    fn new(
        tag: &'static str,
        service: &'static str,
        building: bool,
        ctx: CfgContext,
    ) -> Self {
        let id = IDX.fetch_add(1, Ordering::SeqCst);
        Storage {
            id,
            ctx,
            tag,
            service,
            building,
            data: HashMap::default(),
        }
    }
}

#[derive(Debug)]
pub struct CfgContext(*const Storage);

unsafe impl Send for CfgContext {}
unsafe impl Sync for CfgContext {}

impl CfgContext {
    fn update(&mut self, new_p: *const Storage) {
        self.0 = new_p;
    }

    /// Unique id of the context.
    pub fn id(&self) -> usize {
        self.get_ref().id
    }

    #[inline]
    /// Context tag.
    pub fn tag(&self) -> &'static str {
        self.get_ref().tag
    }

    /// Service name.
    pub fn service(&self) -> &'static str {
        self.get_ref().service
    }

    /// Get a reference to a configuration.
    pub fn get<T>(&self) -> Cfg<T>
    where
        T: Configuration,
    {
        let inner: Arc<Storage> = unsafe { Arc::from_raw(self.0) };
        let cfg = get(&inner);
        mem::forget(inner);
        cfg
    }

    /// Get a shared configuration.
    pub fn shared(&self) -> SharedCfg {
        let inner: Arc<Storage> = unsafe { Arc::from_raw(self.0) };
        let shared = SharedCfg(inner.clone());
        mem::forget(inner);
        shared
    }

    fn get_ref(&self) -> &Storage {
        unsafe { self.0.as_ref().unwrap() }
    }
}

impl Default for CfgContext {
    #[inline]
    fn default() -> Self {
        CfgContext(DEFAULT_CFG.with(Arc::as_ptr))
    }
}

#[derive(Debug)]
pub struct Cfg<T: Configuration>(UnsafeCell<*const T>, PhantomData<rc::Rc<T>>);

impl<T: Configuration> Cfg<T> {
    fn new(ptr: *const T) -> Self {
        Self(UnsafeCell::new(ptr), PhantomData)
    }

    #[inline]
    /// Unique id of the configuration.
    pub fn id(&self) -> usize {
        self.get_ref().ctx().id()
    }

    #[inline]
    /// Context tag.
    pub fn tag(&self) -> &'static str {
        self.get_ref().ctx().tag()
    }

    /// Service name.
    pub fn service(&self) -> &'static str {
        self.get_ref().ctx().service()
    }

    /// Get a shared configuration.
    pub fn shared(&self) -> SharedCfg {
        self.get_ref().ctx().shared()
    }

    fn get_ref(&self) -> &T {
        unsafe {
            (*self.0.get())
                .map_addr(|addr| addr & KIND_UNMASK)
                .as_ref()
                .unwrap()
        }
    }

    #[allow(clippy::needless_pass_by_value)]
    /// Replaces the inner value.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that no references to the inner `T` value
    /// exist at the time this function is called.
    pub unsafe fn replace(&self, cfg: Cfg<T>) {
        unsafe {
            ptr::swap(self.0.get(), cfg.0.get());
        }
    }

    #[doc(hidden)]
    #[deprecated(since = "4.5.0")]
    #[must_use]
    pub fn into_static(&self) -> Cfg<T> {
        self.ctx().get()
    }
}

impl<T: Configuration> Drop for Cfg<T> {
    fn drop(&mut self) {
        unsafe {
            let addr = (*self.0.get()).map_addr(|addr| addr & KIND_UNMASK);
            Arc::decrement_strong_count(addr.as_ref().unwrap().ctx().0);

            if ((*self.0.get()).addr() & KIND_ARC) != 0 {
                Arc::from_raw(addr);
            }
        }
    }
}

impl<T: Configuration> Clone for Cfg<T> {
    #[inline]
    fn clone(&self) -> Self {
        self.ctx().get()
    }
}

impl<'a, T: Configuration> From<&'a T> for Cfg<T> {
    #[inline]
    fn from(cfg: &'a T) -> Self {
        cfg.ctx().get()
    }
}

impl<T: Configuration> ops::Deref for Cfg<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.get_ref()
    }
}

impl<T: Configuration> Default for Cfg<T> {
    #[inline]
    fn default() -> Self {
        SharedCfg::default().get()
    }
}

#[derive(Clone, Debug)]
/// Shared configuration
pub struct SharedCfg(Arc<Storage>);

#[derive(Debug)]
pub struct SharedCfgBuilder {
    ctx: CfgContext,
    storage: Arc<Storage>,
}

impl Eq for SharedCfg {}

impl PartialEq for SharedCfg {
    fn eq(&self, other: &Self) -> bool {
        ptr::from_ref(self.0.as_ref()) == ptr::from_ref(other.0.as_ref())
    }
}

impl Hash for SharedCfg {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.id.hash(state);
    }
}

impl SharedCfg {
    /// Construct new configuration
    pub fn new(tag: &'static str) -> SharedCfgBuilder {
        SharedCfgBuilder::new(tag)
    }

    #[inline]
    /// Get unique shared cfg id
    pub fn id(&self) -> usize {
        self.0.id
    }

    #[inline]
    /// Get tag.
    pub fn tag(&self) -> &'static str {
        self.0.tag
    }

    /// Service name.
    pub fn service(&self) -> &'static str {
        self.0.service
    }

    /// Get a reference to a previously inserted on configuration.
    ///
    /// # Panics
    ///
    /// if shared config is in building stage
    pub fn get<T>(&self) -> Cfg<T>
    where
        T: Configuration,
    {
        get(&self.0)
    }
}

impl Default for SharedCfg {
    #[inline]
    fn default() -> Self {
        Self(DEFAULT_CFG.with(Clone::clone))
    }
}

impl<T: Configuration> From<SharedCfg> for Cfg<T> {
    #[inline]
    fn from(cfg: SharedCfg) -> Self {
        cfg.get()
    }
}

impl SharedCfgBuilder {
    fn new(tag: &'static str) -> SharedCfgBuilder {
        let mut storage = Arc::new(Storage::new(tag, tag, true, CfgContext::default()));
        let ctx = CfgContext(Arc::as_ptr(&storage));
        Arc::get_mut(&mut storage).unwrap().ctx.update(ctx.0);

        SharedCfgBuilder { ctx, storage }
    }

    #[must_use]
    /// Set service name.
    pub fn service(mut self, name: &'static str) -> Self {
        Arc::get_mut(&mut self.storage).unwrap().service = name;
        self
    }

    #[must_use]
    /// Insert a type into this configuration.
    ///
    /// If a config of this type already existed, it will
    /// be replaced.
    pub fn add<T: Configuration>(mut self, mut val: T) -> Self {
        val.set_ctx(CfgContext(self.ctx.0));
        Arc::get_mut(&mut self.storage)
            .unwrap()
            .data
            .insert(TypeId::of::<T>(), Box::new(val));
        self
    }

    #[must_use]
    /// Build `SharedCfg` instance.
    pub fn build(self) -> SharedCfg {
        self.into()
    }
}

impl From<SharedCfgBuilder> for SharedCfg {
    fn from(mut cfg: SharedCfgBuilder) -> SharedCfg {
        let st = Arc::get_mut(&mut cfg.storage).unwrap();
        st.building = false;
        SharedCfg(cfg.storage)
    }
}

fn get<T>(st: &Arc<Storage>) -> Cfg<T>
where
    T: Configuration,
{
    assert!(
        !st.building,
        "{}: Cannot access shared config while building",
        st.tag
    );

    // increase arc refs for storage instead of actual item
    // CfgContext and Cfg::shared() relayes on Arc<Storage>
    mem::forget(st.clone());

    let tp = TypeId::of::<T>();
    if let Some(arc) = st.data.get(&tp) {
        Cfg::new(arc.as_ref().downcast_ref::<T>().unwrap())
    } else {
        MAPPING.with(|store| {
            let key = (st.id, tp);
            if let Some(arc) = store.borrow().get(&key) {
                Cfg::new(
                    Arc::into_raw(arc.clone())
                        .cast::<T>()
                        .map_addr(|addr| addr ^ KIND_ARC),
                )
            } else {
                log::info!(
                    "{}: Configuration {:?} does not exist, using default",
                    st.tag,
                    T::NAME
                );
                let mut val = T::default();
                val.set_ctx(CfgContext(st.ctx.0));
                let arc = Arc::new(val);
                store.borrow_mut().insert(key, arc.clone());
                Cfg::new(
                    Arc::into_raw(arc)
                        .cast::<T>()
                        .map_addr(|addr| addr ^ KIND_ARC),
                )
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[allow(clippy::should_panic_without_expect)]
    #[should_panic]
    fn access_cfg_in_building_state() {
        #[derive(Debug)]
        struct TestCfg {
            config: CfgContext,
        }
        impl TestCfg {
            fn new() -> Self {
                Self {
                    config: CfgContext::default(),
                }
            }
        }
        impl Default for TestCfg {
            fn default() -> Self {
                panic!()
            }
        }
        impl Configuration for TestCfg {
            const NAME: &str = "TEST";
            fn ctx(&self) -> &CfgContext {
                &self.config
            }
            fn set_ctx(&mut self, ctx: CfgContext) {
                let _ = ctx.shared().get::<TestCfg>();
                self.config = ctx;
            }
        }
        let _ = TestCfg::new().ctx();
        let _ = SharedCfg::new("TEST").add(TestCfg::new());
    }

    #[test]
    fn shared_cfg() {
        #[derive(Default, Debug)]
        struct TestCfg {
            config: CfgContext,
        }
        impl Configuration for TestCfg {
            const NAME: &str = "TEST";
            fn ctx(&self) -> &CfgContext {
                &self.config
            }
            fn set_ctx(&mut self, ctx: CfgContext) {
                self.config = ctx;
            }
        }

        let cfg: SharedCfg = SharedCfg::new("TEST")
            .add(TestCfg::default())
            .service("SVC")
            .into();

        assert_eq!(cfg.tag(), "TEST");
        assert_eq!(cfg.service(), "SVC");
        let t = cfg.get::<TestCfg>();
        assert_eq!(t.tag(), "TEST");
        assert_eq!(t.service(), "SVC");
        assert_eq!(t.shared(), cfg);
        let t: Cfg<TestCfg> = Cfg::default();
        assert_eq!(t.tag(), "--");
        assert_eq!(t.service(), "");
        assert_eq!(t.ctx().id(), t.id());

        let t: Cfg<TestCfg> = t.ctx().get();
        assert_eq!(t.tag(), "--");
        assert_eq!(t.ctx().id(), t.id());

        let cfg = SharedCfg::new("TEST2").build();
        let t = cfg.get::<TestCfg>();
        assert_eq!(t.tag(), "TEST2");
        assert_eq!(t.id(), cfg.id());
        drop(cfg);

        let cfg2 = t.shared();
        let t2 = cfg2.get::<TestCfg>();
        assert_eq!(t2.tag(), "TEST2");
        assert_eq!(t2.id(), cfg2.id());
        unsafe { t2.replace(SharedCfg::from(SharedCfg::new("TEST3")).get::<TestCfg>()) };

        let cfg2 = t2.shared();
        let t3 = cfg2.get::<TestCfg>();
        assert_eq!(t3.tag(), "TEST3");
        assert_eq!(t3.id(), cfg2.id());

        let t = SharedCfg::from(SharedCfg::new("TEST4").add(TestCfg::default()))
            .get::<TestCfg>();
        let cfg = t.shared();
        assert_eq!(t.id(), cfg.id());
        let t2 = t.clone();
        assert_eq!(t2.id(), cfg.id());
        assert_eq!(t2.tag(), "TEST4");

        let t3 = t.ctx().get::<TestCfg>();
        assert_eq!(t3.id(), cfg.id());
        assert_eq!(t3.tag(), "TEST4");
    }
}