ntex_service/cfg.rs
1//! Typed, shared configuration for services.
2//!
3//! [`SharedCfg`] stores configuration values by their concrete type. Start
4//! with [`SharedCfg::new`], insert values through [`SharedCfgBuilder::add`],
5//! and finish with [`SharedCfgBuilder::build`]. Adding the same type again
6//! replaces its previous value.
7//!
8//! Each value implements [`Configuration`] and stores a [`CfgContext`].
9//! The builder associates that context with the collection, providing access
10//! to its tag, service name, and other configuration types.
11//! [`SharedCfg::get`] returns a [`Cfg<T>`] handle that dereferences to `T`.
12//! If a type was not inserted, lookup creates its default value and caches it
13//! for that collection on the calling thread.
14//!
15//! The built collection can be shared across threads, while typed [`Cfg`]
16//! handles are local to the thread that obtains them. Configuration is
17//! separate from the state passed to [`crate::Service`] operations; a state
18//! value can carry whichever configuration handles the service needs.
19//!
20//! A [`CfgContext`] keeps the id, tag, and service name of its collection
21//! readable, but does not keep the collection alive. Lookups through a
22//! context panic while the collection is being built and after it has been
23//! dropped; [`SharedCfg`] and [`Cfg`] handles keep it alive.
24//!
25//! # Example
26//!
27//! ```
28//! use ntex_service::cfg::{CfgContext, Configuration, SharedCfg};
29//!
30//! #[derive(Debug, Default)]
31//! struct Limits {
32//! ctx: CfgContext,
33//! max_requests: usize,
34//! }
35//!
36//! impl Configuration for Limits {
37//! const NAME: &'static str = "limits";
38//!
39//! fn ctx(&self) -> &CfgContext {
40//! &self.ctx
41//! }
42//!
43//! fn set_ctx(&mut self, ctx: CfgContext) {
44//! self.ctx = ctx;
45//! }
46//! }
47//!
48//! let shared = SharedCfg::new("listener")
49//! .service("example")
50//! .add(Limits {
51//! max_requests: 32,
52//! ..Limits::default()
53//! })
54//! .build();
55//! let limits = shared.get::<Limits>();
56//! assert_eq!(limits.max_requests, 32);
57//! assert_eq!(limits.tag(), "listener");
58//! assert_eq!(limits.service(), "example");
59//! ```
60//!
61//! # Framework guide
62//!
63//! See [Service State](https://docs.ntex.rs/3-state.html) for passing shared
64//! data to services.
65
66#![forbid(unsafe_code)]
67#![allow(clippy::should_implement_trait, clippy::new_ret_no_self)]
68use std::any::{Any, TypeId};
69use std::cell::RefCell;
70use std::collections::hash_map::Entry;
71use std::sync::{Arc, LazyLock, OnceLock, Weak, atomic::AtomicUsize, atomic::Ordering};
72use std::{fmt, hash::Hash, hash::Hasher, marker::PhantomData, ops, rc};
73
74type Key = (usize, TypeId);
75type HashMap<K, V> = std::collections::HashMap<K, V, foldhash::fast::RandomState>;
76type ConfigMap = HashMap<TypeId, Arc<dyn Any + Send + Sync>>;
77
78const DEFAULT_ID: usize = 0;
79const DEFAULT_TAG: &str = "--";
80const DEFAULT_SERVICE: &str = "";
81
82// Process-wide and never dropped, so a default `CfgContext` needs no handle to
83// it and can be sent to, and outlive, any thread.
84static DEFAULT_CFG: LazyLock<Arc<Storage>> = LazyLock::new(|| {
85 Arc::new(Storage {
86 id: DEFAULT_ID,
87 tag: DEFAULT_TAG,
88 service: DEFAULT_SERVICE,
89 ctx: CfgContext(None),
90 data: ConfigMap::default(),
91 })
92});
93
94thread_local! {
95 static MAPPING: RefCell<HashMap<Key, Arc<dyn Any + Send + Sync>>> = {
96 RefCell::new(HashMap::default())
97 };
98}
99// `DEFAULT_ID` is reserved for the default configuration.
100static IDX: AtomicUsize = AtomicUsize::new(DEFAULT_ID + 1);
101
102/// A value that can be stored in [`SharedCfg`].
103///
104/// [`Default`] supplies the value returned when a shared configuration does
105/// not contain this type; see [`SharedCfg::get`]. Each thread creates its own
106/// default, so it should be deterministic and must not stand in for a value
107/// the application is required to provide.
108pub trait Configuration: Default + Send + Sync + fmt::Debug + 'static {
109 /// Human-readable configuration name used in diagnostics.
110 const NAME: &'static str;
111
112 /// Returns the shared context associated with this value.
113 fn ctx(&self) -> &CfgContext;
114
115 /// Associates this value with a shared configuration context.
116 ///
117 /// [`SharedCfgBuilder::add`] calls this before the configuration is
118 /// built, so [`CfgContext::get`] and [`CfgContext::shared`] panic here;
119 /// store the context and use it later.
120 fn set_ctx(&mut self, ctx: CfgContext);
121}
122
123#[derive(Debug)]
124struct Storage {
125 id: usize,
126 tag: &'static str,
127 service: &'static str,
128 ctx: CfgContext,
129 data: ConfigMap,
130}
131
132/// The identity of a built or building configuration, shared by its builder,
133/// its storage, and every context handed to its values.
134#[derive(Debug)]
135struct ContextInner {
136 id: usize,
137 tag: &'static str,
138 published: OnceLock<Published>,
139}
140
141/// Set once, when the builder finishes.
142#[derive(Debug)]
143struct Published {
144 storage: Weak<Storage>,
145 service: &'static str,
146}
147
148impl ContextInner {
149 fn storage(&self) -> Arc<Storage> {
150 let Some(published) = self.published.get() else {
151 building(self.tag)
152 };
153 match published.storage.upgrade() {
154 Some(storage) => storage,
155 None => expired(self.tag),
156 }
157 }
158}
159
160#[cold]
161#[inline(never)]
162fn building(tag: &str) -> ! {
163 panic!("{tag}: Cannot access shared config while building")
164}
165
166#[cold]
167#[inline(never)]
168fn expired(tag: &str) -> ! {
169 panic!("{tag}: Cannot access shared config after it was dropped")
170}
171
172#[derive(Debug)]
173/// Metadata and lookup access for a shared configuration.
174///
175/// The id, tag, and service name stay readable for as long as the context
176/// exists. Lookups need the configuration itself, see [`CfgContext::get`].
177pub struct CfgContext(Option<Arc<ContextInner>>);
178
179impl CfgContext {
180 /// Returns the unique identifier of the shared configuration.
181 pub fn id(&self) -> usize {
182 self.0.as_ref().map_or(DEFAULT_ID, |inner| inner.id)
183 }
184
185 #[inline]
186 /// Returns the configuration tag.
187 pub fn tag(&self) -> &'static str {
188 self.0.as_ref().map_or(DEFAULT_TAG, |inner| inner.tag)
189 }
190
191 /// Returns the configured service name.
192 ///
193 /// Returns the tag while the configuration is being built.
194 pub fn service(&self) -> &'static str {
195 match &self.0 {
196 Some(inner) => inner.published.get().map_or(inner.tag, |p| p.service),
197 None => DEFAULT_SERVICE,
198 }
199 }
200
201 /// Returns a typed configuration value from the same shared configuration.
202 ///
203 /// A missing value falls back to a per-thread default, as described in
204 /// [`SharedCfg::get`].
205 ///
206 /// # Panics
207 ///
208 /// Panics while the shared configuration is being built, for example from
209 /// [`Configuration::set_ctx`] during [`SharedCfgBuilder::add`] or after its
210 /// builder was dropped, and after the shared configuration was dropped.
211 pub fn get<T>(&self) -> Cfg<T>
212 where
213 T: Configuration,
214 {
215 get(self.storage())
216 }
217
218 /// Returns a handle to the complete shared configuration.
219 ///
220 /// # Panics
221 ///
222 /// Panics in the same cases as [`CfgContext::get`].
223 pub fn shared(&self) -> SharedCfg {
224 SharedCfg(self.storage())
225 }
226
227 fn storage(&self) -> Arc<Storage> {
228 match &self.0 {
229 Some(inner) => inner.storage(),
230 None => Arc::clone(&DEFAULT_CFG),
231 }
232 }
233}
234
235impl Default for CfgContext {
236 #[inline]
237 fn default() -> Self {
238 CfgContext(None)
239 }
240}
241
242#[derive(Debug)]
243/// A typed handle to a value in a [`SharedCfg`].
244pub struct Cfg<T: Configuration> {
245 value: Arc<T>,
246 // The owner `get` was given, so releasing it never depends on the
247 // user's `Configuration::ctx`.
248 storage: Arc<Storage>,
249 local: PhantomData<rc::Rc<T>>,
250}
251
252impl<T: Configuration> Cfg<T> {
253 #[inline]
254 /// Returns the unique identifier of the shared configuration.
255 pub fn id(&self) -> usize {
256 self.storage.id
257 }
258
259 #[inline]
260 /// Returns the configuration tag.
261 pub fn tag(&self) -> &'static str {
262 self.storage.tag
263 }
264
265 /// Returns the configured service name.
266 pub fn service(&self) -> &'static str {
267 self.storage.service
268 }
269
270 /// Returns a handle to the complete shared configuration.
271 pub fn shared(&self) -> SharedCfg {
272 SharedCfg(self.storage.clone())
273 }
274
275 /// Returns another typed value from the same shared configuration.
276 ///
277 /// A missing value falls back to a per-thread default, as described in
278 /// [`SharedCfg::get`].
279 pub fn get_shared<U>(&self) -> Cfg<U>
280 where
281 U: Configuration,
282 {
283 get(self.storage.clone())
284 }
285}
286
287impl<T: Configuration> Clone for Cfg<T> {
288 #[inline]
289 fn clone(&self) -> Self {
290 Self {
291 value: self.value.clone(),
292 storage: self.storage.clone(),
293 local: PhantomData,
294 }
295 }
296}
297
298/// Wraps a standalone value in a new shared configuration tagged `--`.
299///
300/// There is no conversion from `&T`: a borrowed value cannot be moved into a
301/// configuration. Pass the value by value, clone an existing [`Cfg`] handle,
302/// or look up the registered value with `value.ctx().get::<T>()`.
303impl<T: Configuration> From<T> for Cfg<T> {
304 #[inline]
305 fn from(cfg: T) -> Self {
306 SharedCfg::new("--").add(cfg).build().get()
307 }
308}
309
310impl<T: Configuration> ops::Deref for Cfg<T> {
311 type Target = T;
312
313 #[inline]
314 fn deref(&self) -> &T {
315 &self.value
316 }
317}
318
319impl<T: Configuration> Default for Cfg<T> {
320 #[inline]
321 fn default() -> Self {
322 SharedCfg::default().get()
323 }
324}
325
326#[derive(Clone, Debug)]
327/// An immutable collection of typed configuration values.
328pub struct SharedCfg(Arc<Storage>);
329
330#[derive(Debug)]
331/// Builder for [`SharedCfg`].
332pub struct SharedCfgBuilder {
333 ctx: Arc<ContextInner>,
334 service: &'static str,
335 data: ConfigMap,
336}
337
338impl Eq for SharedCfg {}
339
340impl PartialEq for SharedCfg {
341 fn eq(&self, other: &Self) -> bool {
342 Arc::ptr_eq(&self.0, &other.0)
343 }
344}
345
346impl Hash for SharedCfg {
347 fn hash<H: Hasher>(&self, state: &mut H) {
348 self.0.id.hash(state);
349 }
350}
351
352impl SharedCfg {
353 /// Starts building a shared configuration with the given tag.
354 pub fn new(tag: &'static str) -> SharedCfgBuilder {
355 SharedCfgBuilder::new(tag)
356 }
357
358 #[inline]
359 /// Returns the unique identifier of this configuration.
360 pub fn id(&self) -> usize {
361 self.0.id
362 }
363
364 #[inline]
365 /// Returns the configuration tag.
366 pub fn tag(&self) -> &'static str {
367 self.0.tag
368 }
369
370 /// Returns the configured service name.
371 pub fn service(&self) -> &'static str {
372 self.0.service
373 }
374
375 /// Returns the configuration value of type `T`, or its default.
376 ///
377 /// A value added with [`SharedCfgBuilder::add`] is the same instance on
378 /// every thread. When `T` was not added, the first lookup on a thread
379 /// creates `T::default()`, logs it at `info` level, and caches it for this
380 /// shared configuration on that thread. Later lookups on the same thread,
381 /// including through [`CfgContext::get`] and [`Cfg::get_shared`], return
382 /// the cached value; other threads create their own.
383 ///
384 /// A missing value is not an error, and the returned handle does not show
385 /// whether the value was added or defaulted. Framework components rely on
386 /// this to fall back to their defaults. Add configuration your application
387 /// requires explicitly, and validate it where you build the
388 /// [`SharedCfg`].
389 ///
390 /// # Panics
391 ///
392 /// A panic in `T::default()` or [`Configuration::set_ctx`] while creating
393 /// the default propagates to the caller, and nothing is cached.
394 pub fn get<T>(&self) -> Cfg<T>
395 where
396 T: Configuration,
397 {
398 get(self.0.clone())
399 }
400}
401
402impl Default for SharedCfg {
403 #[inline]
404 fn default() -> Self {
405 Self(Arc::clone(&DEFAULT_CFG))
406 }
407}
408
409impl<'a> From<&'a SharedCfg> for SharedCfg {
410 fn from(cfg: &'a SharedCfg) -> SharedCfg {
411 cfg.clone()
412 }
413}
414
415impl<T: Configuration> From<SharedCfg> for Cfg<T> {
416 #[inline]
417 fn from(cfg: SharedCfg) -> Self {
418 cfg.get()
419 }
420}
421
422impl<'a, T: Configuration> From<&'a SharedCfg> for Cfg<T> {
423 #[inline]
424 fn from(cfg: &'a SharedCfg) -> Self {
425 cfg.get()
426 }
427}
428
429impl<T: Configuration> From<SharedCfgBuilder> for Cfg<T> {
430 #[inline]
431 fn from(cfg: SharedCfgBuilder) -> Self {
432 cfg.build().get()
433 }
434}
435
436impl<T: Configuration> From<T> for SharedCfg {
437 #[inline]
438 fn from(cfg: T) -> Self {
439 SharedCfg::new("--").add(cfg).build()
440 }
441}
442
443impl<T: Configuration> From<Cfg<T>> for SharedCfg {
444 #[inline]
445 fn from(cfg: Cfg<T>) -> Self {
446 cfg.shared()
447 }
448}
449
450impl SharedCfgBuilder {
451 fn new(tag: &'static str) -> SharedCfgBuilder {
452 let ctx = ContextInner {
453 id: IDX.fetch_add(1, Ordering::SeqCst),
454 tag,
455 published: OnceLock::new(),
456 };
457 SharedCfgBuilder {
458 ctx: Arc::new(ctx),
459 service: tag,
460 data: ConfigMap::default(),
461 }
462 }
463
464 #[must_use]
465 /// Sets the service name.
466 pub fn service(mut self, name: &'static str) -> Self {
467 self.service = name;
468 self
469 }
470
471 #[must_use]
472 /// Inserts a typed value into this configuration.
473 ///
474 /// Replaces the existing value when the same type was already inserted.
475 pub fn add<T: Configuration>(mut self, mut val: T) -> Self {
476 val.set_ctx(CfgContext(Some(self.ctx.clone())));
477 self.data.insert(TypeId::of::<T>(), Arc::new(val));
478 self
479 }
480
481 #[must_use]
482 /// Finishes building and returns the shared configuration.
483 pub fn build(self) -> SharedCfg {
484 self.into()
485 }
486}
487
488impl From<SharedCfgBuilder> for SharedCfg {
489 fn from(cfg: SharedCfgBuilder) -> SharedCfg {
490 let SharedCfgBuilder { ctx, service, data } = cfg;
491 let storage = Arc::new(Storage {
492 id: ctx.id,
493 tag: ctx.tag,
494 service,
495 ctx: CfgContext(Some(ctx.clone())),
496 data,
497 });
498 let published = ctx.published.set(Published {
499 storage: Arc::downgrade(&storage),
500 service,
501 });
502 debug_assert!(published.is_ok(), "a builder is built only once");
503 SharedCfg(storage)
504 }
505}
506
507/// Looks up `T` and moves `st` into the returned handle as its owner.
508fn get<T>(st: Arc<Storage>) -> Cfg<T>
509where
510 T: Configuration,
511{
512 let val = match st.data.get(&TypeId::of::<T>()) {
513 Some(val) => val.clone(),
514 None => get_default::<T>(&st),
515 };
516 Cfg {
517 // values are keyed by their `TypeId`
518 value: val.downcast::<T>().unwrap(),
519 storage: st,
520 local: PhantomData,
521 }
522}
523
524/// Returns the default `T` cached for `st` on this thread, creating it first.
525///
526/// No cache borrow is held while user code runs or a value is dropped.
527fn get_default<T>(st: &Storage) -> Arc<dyn Any + Send + Sync>
528where
529 T: Configuration,
530{
531 let key = (st.id, TypeId::of::<T>());
532 if let Some(val) = MAPPING.with(|store| store.borrow().get(&key).cloned()) {
533 return val;
534 }
535
536 log::info!(
537 "{}: Configuration {:?} does not exist, using default",
538 st.tag,
539 T::NAME
540 );
541 let mut val = T::default();
542 val.set_ctx(CfgContext(st.ctx.0.clone()));
543 let val: Arc<dyn Any + Send + Sync> = Arc::new(val);
544
545 // `Default` or `set_ctx` may have cached this key already; keep that value
546 // and drop ours after the borrow ends.
547 let (cached, unused) = MAPPING.with(|store| match store.borrow_mut().entry(key) {
548 Entry::Occupied(entry) => (entry.get().clone(), Some(val)),
549 Entry::Vacant(entry) => (entry.insert(val).clone(), None),
550 });
551 drop(unused);
552 cached
553}
554
555#[cfg(test)]
556#[path = "../tests/unit/cfg.rs"]
557mod tests;