dcontext 0.5.0

Distributed context propagation for Rust — scoped, type-safe, serializable
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

use crate::error::ContextError;
use crate::value::ContextValue;

/// Type alias for versioned deserializer functions.
type DeserializeFn = Box<dyn Fn(&[u8]) -> Result<Box<dyn ContextValue>, ContextError> + Send + Sync>;

/// Type alias for custom serializer functions (Arc so it can be cloned without a lock).
type SerializeFn = Arc<dyn Fn(&dyn ContextValue) -> Result<Vec<u8>, ContextError> + Send + Sync>;

type RegistryMap = HashMap<&'static str, Registration>;

/// Metadata stored for each registered context key.
pub(crate) struct Registration {
    pub key: &'static str,
    pub type_id: TypeId,
    /// The current (latest) version used for serialization.
    pub key_version: u32,
    /// Versioned deserializers: wire_version → deserializer function.
    pub deserializers: HashMap<u32, DeserializeFn>,
    pub type_name: &'static str,
    /// If true, this key is excluded from serialization.
    pub local_only: bool,
    /// Custom serializer. If None, uses ContextValue::serialize_value() (bincode).
    pub serialize_fn: Option<SerializeFn>,
    /// If true, the effective value is eagerly copied into each new scope
    /// on scope entry. This gives O(1) reads at the cost of an Arc::clone
    /// per scope entry. Suitable for lightweight values (request IDs, trace IDs).
    /// Default: false (reads walk the parent scope chain, O(depth)).
    pub cached: bool,
    /// Extensible metadata: any crate can attach typed metadata to a registration.
    /// Keyed by TypeId of the metadata type.
    pub metadata: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

// ── Two-phase storage ──────────────────────────────────────────
//
// Build phase  : RegistryBuilder collects registrations (no locks).
// Frozen phase : initialize(builder) moves them into FROZEN (OnceLock).
//                All subsequent reads are lock-free.
//
// Tests use BUILD (Mutex) via pub(crate) free-standing functions,
// so they work without calling initialize().

/// Immutable map used after `initialize()`. Lock-free reads.
static FROZEN: OnceLock<RegistryMap> = OnceLock::new();

/// Mutable map used by tests (via pub(crate) free-standing functions).
/// Not used in production — only a fallback when FROZEN is not set.
static BUILD: std::sync::LazyLock<Mutex<Option<RegistryMap>>> =
    std::sync::LazyLock::new(|| Mutex::new(Some(HashMap::new())));

fn lock_build() -> std::sync::MutexGuard<'static, Option<RegistryMap>> {
    BUILD.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}

// ── Registration options ───────────────────────────────────────

/// Builder for configuring per-key registration options.
///
/// Obtained via the callback in [`RegistryBuilder::try_register_with`].
///
/// # Examples
///
/// ```rust,ignore
/// builder.register_with::<Config>("config", |opts| opts
///     .version(1)
///     .codec(
///         |val| serde_json::to_vec(val).map_err(|e| e.to_string()),
///         |bytes| serde_json::from_slice(bytes).map_err(|e| e.to_string()),
///     )
/// );
/// ```
pub struct RegistrationOptions<T: 'static> {
    version: u32,
    local_only: bool,
    cached: bool,
    encode: Option<Box<dyn Fn(&T) -> Result<Vec<u8>, String> + Send + Sync>>,
    decode: Option<Box<dyn Fn(&[u8]) -> Result<T, String> + Send + Sync>>,
    metadata: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl<T: 'static> RegistrationOptions<T> {
    fn new() -> Self {
        Self {
            version: 1,
            local_only: false,
            cached: false,
            encode: None,
            decode: None,
            metadata: HashMap::new(),
        }
    }

    /// Set the wire format version (default: 1).
    pub fn version(mut self, v: u32) -> Self {
        self.version = v;
        self
    }

    /// Mark as local-only: propagates via snapshot/attach but excluded from
    /// serialization. The type does not need `Serialize`/`DeserializeOwned`.
    pub fn local_only(mut self) -> Self {
        self.local_only = true;
        self
    }

    /// Enable per-scope caching: the effective value is eagerly copied (Arc::clone)
    /// into each new scope on entry, giving O(1) reads. Best for lightweight values
    /// like request IDs or trace IDs. Without this, reads walk the parent scope
    /// chain (O(depth)).
    pub fn cached(mut self) -> Self {
        self.cached = true;
        self
    }

    /// Use a custom serialization codec instead of bincode.
    /// Both `encode` and `decode` must be provided together.
    pub fn codec(
        mut self,
        encode: impl Fn(&T) -> Result<Vec<u8>, String> + Send + Sync + 'static,
        decode: impl Fn(&[u8]) -> Result<T, String> + Send + Sync + 'static,
    ) -> Self {
        self.encode = Some(Box::new(encode));
        self.decode = Some(Box::new(decode));
        self
    }

    /// Attach typed metadata to this registration. Any crate can define its
    /// own metadata type and attach it here. Only one value per metadata type
    /// is stored; a second call with the same `M` overwrites the previous value.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use dcontext_tracing::LogField;
    ///
    /// builder.register_with::<RequestId>("request_id", |opts| {
    ///     opts.cached().with_metadata(LogField::display::<RequestId>("rid"))
    /// });
    /// ```
    pub fn with_metadata<M: Any + Send + Sync + 'static>(mut self, value: M) -> Self {
        self.metadata.insert(TypeId::of::<M>(), Box::new(value));
        self
    }
}

// ── Private implementation functions ───────────────────────────
//
// Shared logic used by both RegistryBuilder and free-standing test helpers.

fn do_register_with<T>(
    registry: &mut RegistryMap,
    key: &'static str,
    configure: impl FnOnce(RegistrationOptions<T>) -> RegistrationOptions<T>,
) -> Result<(), ContextError>
where
    T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    let opts = configure(RegistrationOptions::new());

    if opts.local_only {
        if opts.encode.is_some() || opts.decode.is_some() {
            return Err(ContextError::SerializationFailed(
                "local_only and codec are mutually exclusive: \
                 local-only entries are excluded from serialization"
                    .into(),
            ));
        }
        if opts.version != 1 {
            return Err(ContextError::SerializationFailed(
                "local_only and version are mutually exclusive: \
                 local-only entries have no wire format"
                    .into(),
            ));
        }
    }

    let tid = TypeId::of::<T>();

    if let Some(existing) = registry.get(key) {
        if existing.type_id == tid {
            return Ok(()); // idempotent
        }
        return Err(ContextError::AlreadyRegistered(key.to_string()));
    }

    let mut deserializers: HashMap<u32, DeserializeFn> = HashMap::new();

    if !opts.local_only {
        if let Some(decode) = opts.decode {
            deserializers.insert(
                opts.version,
                Box::new(move |bytes: &[u8]| -> Result<Box<dyn ContextValue>, ContextError> {
                    decode(bytes)
                        .map(|v| Box::new(v) as Box<dyn ContextValue>)
                        .map_err(ContextError::DeserializationFailed)
                }),
            );
        } else {
            deserializers.insert(
                opts.version,
                Box::new(|bytes: &[u8]| -> Result<Box<dyn ContextValue>, ContextError> {
                    bincode::deserialize::<T>(bytes)
                        .map(|v| Box::new(v) as Box<dyn ContextValue>)
                        .map_err(|e| ContextError::DeserializationFailed(e.to_string()))
                }),
            );
        }
    }

    let serialize_fn = opts.encode.map(|encode| -> SerializeFn {
        Arc::new(move |val: &dyn ContextValue| {
            let typed = val.as_any().downcast_ref::<T>().ok_or_else(|| {
                ContextError::SerializationFailed(
                    "type mismatch during custom serialization".into(),
                )
            })?;
            encode(typed).map_err(ContextError::SerializationFailed)
        })
    });

    registry.insert(
        key,
        Registration {
            key,
            type_id: tid,
            key_version: opts.version,
            deserializers,
            type_name: std::any::type_name::<T>(),
            local_only: opts.local_only,
            serialize_fn,
            cached: opts.cached,
            metadata: opts.metadata,
        },
    );
    Ok(())
}

fn do_register_local<T>(
    registry: &mut RegistryMap,
    key: &'static str,
) -> Result<(), ContextError>
where
    T: Clone + Default + Send + Sync + 'static,
{
    let tid = TypeId::of::<T>();

    if let Some(existing) = registry.get(key) {
        if existing.type_id == tid {
            return Ok(());
        }
        return Err(ContextError::AlreadyRegistered(key.to_string()));
    }

    registry.insert(
        key,
        Registration {
            key,
            type_id: tid,
            key_version: 0,
            deserializers: HashMap::new(),
            type_name: std::any::type_name::<T>(),
            local_only: true,
            serialize_fn: None,
            cached: false,
            metadata: HashMap::new(),
        },
    );
    Ok(())
}

fn do_register_migration<TOld, TCurrent>(
    registry: &mut RegistryMap,
    key: &'static str,
    old_version: u32,
    migrate: impl Fn(TOld) -> TCurrent + Send + Sync + 'static,
) -> Result<(), ContextError>
where
    TOld: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    TCurrent: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    let reg = registry.get_mut(key).ok_or_else(|| {
        ContextError::NotRegistered(key.to_string())
    })?;

    if reg.type_id != TypeId::of::<TCurrent>() {
        return Err(ContextError::TypeMismatch(
            key.to_string(),
            reg.type_name.to_string(),
            std::any::type_name::<TCurrent>().to_string(),
        ));
    }

    if reg.local_only {
        return Err(ContextError::SerializationFailed(format!(
            "cannot register migration for local-only key '{}'", key
        )));
    }

    if old_version == reg.key_version {
        return Err(ContextError::DeserializationFailed(format!(
            "cannot register migration for key '{}' at current version {} \
             (would overwrite the native deserializer)",
            key, old_version
        )));
    }

    reg.deserializers.insert(
        old_version,
        Box::new(move |bytes: &[u8]| -> Result<Box<dyn ContextValue>, ContextError> {
            let old_val = bincode::deserialize::<TOld>(bytes)
                .map_err(|e| ContextError::DeserializationFailed(e.to_string()))?;
            let current_val = migrate(old_val);
            Ok(Box::new(current_val) as Box<dyn ContextValue>)
        }),
    );

    Ok(())
}

// ── RegistryBuilder ────────────────────────────────────────────

/// Collects context registrations during application startup.
///
/// Create a builder, register all context types, then call
/// [`initialize`] to freeze the registry for lock-free reads.
///
/// # Examples
///
/// ```rust,ignore
/// use dcontext::{RegistryBuilder, initialize};
///
/// let mut builder = RegistryBuilder::new();
/// builder.register::<RequestId>("request_id");
/// builder.register_with::<TraceV2>("trace", |o| o.version(2));
/// builder.register_migration::<TraceV1, TraceV2>("trace", 1, migrate_fn);
///
/// initialize(builder); // freeze — all reads lock-free after this
/// ```
pub struct RegistryBuilder {
    map: RegistryMap,
}

impl RegistryBuilder {
    /// Create an empty builder.
    pub fn new() -> Self {
        Self { map: HashMap::new() }
    }

    /// Register a context type with default options (version 1, bincode codec).
    pub fn register<T>(&mut self, key: &'static str)
    where
        T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    {
        self.try_register::<T>(key).expect("RegistryBuilder::register failed");
    }

    /// Register a context type. Returns Err on conflict.
    pub fn try_register<T>(&mut self, key: &'static str) -> Result<(), ContextError>
    where
        T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    {
        do_register_with::<T>(&mut self.map, key, |opts| opts)
    }

    /// Register with custom options via builder callback.
    pub fn register_with<T>(
        &mut self,
        key: &'static str,
        configure: impl FnOnce(RegistrationOptions<T>) -> RegistrationOptions<T>,
    )
    where
        T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    {
        self.try_register_with::<T>(key, configure)
            .expect("RegistryBuilder::register_with failed");
    }

    /// Register with custom options. Returns Err on conflict.
    pub fn try_register_with<T>(
        &mut self,
        key: &'static str,
        configure: impl FnOnce(RegistrationOptions<T>) -> RegistrationOptions<T>,
    ) -> Result<(), ContextError>
    where
        T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    {
        do_register_with(&mut self.map, key, configure)
    }

    /// Register a local-only context type (no Serialize/DeserializeOwned needed).
    pub fn register_local<T>(&mut self, key: &'static str)
    where
        T: Clone + Default + Send + Sync + 'static,
    {
        self.try_register_local::<T>(key)
            .expect("RegistryBuilder::register_local failed");
    }

    /// Register a local-only type. Returns Err on conflict.
    pub fn try_register_local<T>(&mut self, key: &'static str) -> Result<(), ContextError>
    where
        T: Clone + Default + Send + Sync + 'static,
    {
        do_register_local::<T>(&mut self.map, key)
    }

    /// Register a migration deserializer for an older wire version.
    pub fn register_migration<TOld, TCurrent>(
        &mut self,
        key: &'static str,
        old_version: u32,
        migrate: impl Fn(TOld) -> TCurrent + Send + Sync + 'static,
    )
    where
        TOld: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
        TCurrent: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    {
        self.try_register_migration::<TOld, TCurrent>(key, old_version, migrate)
            .expect("RegistryBuilder::register_migration failed");
    }

    /// Register a migration. Returns Err on conflict or if key not found.
    pub fn try_register_migration<TOld, TCurrent>(
        &mut self,
        key: &'static str,
        old_version: u32,
        migrate: impl Fn(TOld) -> TCurrent + Send + Sync + 'static,
    ) -> Result<(), ContextError>
    where
        TOld: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
        TCurrent: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    {
        do_register_migration(&mut self.map, key, old_version, migrate)
    }
}

impl Default for RegistryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ── Initialization ─────────────────────────────────────────────

/// Freeze the registry. Consumes the builder and makes all reads lock-free.
///
/// Call this once after all registrations, before any context operations.
///
/// ```rust,ignore
/// let mut builder = dcontext::RegistryBuilder::new();
/// builder.register::<RequestId>("request_id");
/// builder.register_with::<TraceV2>("trace", |o| o.version(2));
/// builder.register_migration::<TraceV1, TraceV2>("trace", 1, migrate_fn);
///
/// dcontext::initialize(builder); // freeze
/// ```
pub fn initialize(builder: RegistryBuilder) {
    try_initialize(builder).expect("dcontext::initialize called more than once");
}

/// Try to freeze the registry. Returns `Err` if already initialized.
pub fn try_initialize(builder: RegistryBuilder) -> Result<(), ContextError> {
    FROZEN.set(builder.map).map_err(|_| ContextError::RegistryFrozen)
}

// ── Free-standing registration functions (for tests) ───────────
//
// Tests run in the same process and cannot call initialize() per-test
// (OnceLock is one-shot). These functions write to the BUILD mutex,
// and read functions fall back to BUILD when FROZEN is not set.

#[cfg(test)]
pub(crate) fn try_register<T>(key: &'static str) -> Result<(), ContextError>
where
    T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    try_register_with::<T>(key, |opts| opts)
}

#[cfg(test)]
pub(crate) fn try_register_with<T>(
    key: &'static str,
    configure: impl FnOnce(RegistrationOptions<T>) -> RegistrationOptions<T>,
) -> Result<(), ContextError>
where
    T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    let mut guard = lock_build();
    let registry = guard.as_mut().ok_or(ContextError::RegistryFrozen)?;
    do_register_with(registry, key, configure)
}

#[cfg(test)]
pub(crate) fn register<T>(key: &'static str)
where
    T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    try_register::<T>(key).expect("dcontext::register failed");
}

#[cfg(test)]
pub(crate) fn register_with<T>(
    key: &'static str,
    configure: impl FnOnce(RegistrationOptions<T>) -> RegistrationOptions<T>,
)
where
    T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    try_register_with::<T>(key, configure).expect("dcontext::register_with failed");
}

#[cfg(test)]
pub(crate) fn try_register_local<T>(key: &'static str) -> Result<(), ContextError>
where
    T: Clone + Default + Send + Sync + 'static,
{
    let mut guard = lock_build();
    let registry = guard.as_mut().ok_or(ContextError::RegistryFrozen)?;
    do_register_local::<T>(registry, key)
}

#[cfg(test)]
pub(crate) fn register_local<T>(key: &'static str)
where
    T: Clone + Default + Send + Sync + 'static,
{
    try_register_local::<T>(key).expect("dcontext::register_local failed");
}

#[cfg(test)]
pub(crate) fn try_register_migration<TOld, TCurrent>(
    key: &'static str,
    old_version: u32,
    migrate: impl Fn(TOld) -> TCurrent + Send + Sync + 'static,
) -> Result<(), ContextError>
where
    TOld: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    TCurrent: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    let mut guard = lock_build();
    let registry = guard.as_mut().ok_or(ContextError::RegistryFrozen)?;
    do_register_migration(registry, key, old_version, migrate)
}

#[cfg(test)]
pub(crate) fn register_migration<TOld, TCurrent>(
    key: &'static str,
    old_version: u32,
    migrate: impl Fn(TOld) -> TCurrent + Send + Sync + 'static,
)
where
    TOld: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
    TCurrent: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    try_register_migration::<TOld, TCurrent>(key, old_version, migrate)
        .expect("dcontext::register_migration failed");
}

// ── Read functions (lock-free after initialize) ────────────────

/// Look up a registration by key. Returns None if not registered.
///
/// After [`initialize`]: lock-free (OnceLock deref + HashMap lookup).
/// Before [`initialize`]: acquires Mutex (correct, but slower — for tests).
pub(crate) fn with_registration<R>(
    key: &str,
    f: impl FnOnce(&Registration) -> R,
) -> Option<R> {
    if let Some(frozen) = FROZEN.get() {
        return frozen.get(key).map(f);
    }
    let guard = lock_build();
    guard.as_ref().and_then(|map| map.get(key).map(f))
}

/// Info needed by `serialize_context`, fetched in a single lookup.
pub(crate) struct SerializationInfo {
    pub local_only: bool,
    pub key_version: u32,
    pub serialize_fn: Option<SerializeFn>,
}

/// Single-lookup extraction of everything `serialize_context` needs.
pub(crate) fn get_serialization_info(key: &str) -> Option<SerializationInfo> {
    let extract = |r: &Registration| SerializationInfo {
        local_only: r.local_only,
        key_version: r.key_version,
        serialize_fn: r.serialize_fn.clone(),
    };

    if let Some(frozen) = FROZEN.get() {
        return frozen.get(key).map(extract);
    }
    let guard = lock_build();
    guard.as_ref().and_then(|map| map.get(key).map(extract))
}

/// Return registered keys that have per-scope caching enabled.
/// These keys will have their effective values eagerly copied into each
/// new scope on entry, giving O(1) reads.
pub(crate) fn cached_keys() -> Vec<&'static str> {
    let filter = |map: &RegistryMap| -> Vec<&'static str> {
        map.iter()
            .filter(|(_, r)| r.cached)
            .map(|(&k, _)| k)
            .collect()
    };
    if let Some(frozen) = FROZEN.get() {
        return filter(frozen);
    }
    let guard = lock_build();
    guard.as_ref().map_or_else(Vec::new, filter)
}

// ── Metadata query API ─────────────────────────────────────────

/// Access typed metadata for a registered key via callback.
///
/// Returns `None` if the key is not registered or has no metadata of type `M`.
/// After [`initialize`]: lock-free. Before: acquires Mutex.
pub fn with_metadata<M: 'static, R>(
    key: &str,
    f: impl FnOnce(&M) -> R,
) -> Option<R> {
    with_registration(key, |r| {
        r.metadata
            .get(&TypeId::of::<M>())
            .and_then(|boxed| boxed.downcast_ref::<M>())
            .map(f)
    })
    .flatten()
}

/// Iterate over all registered keys that have metadata of type `M`.
///
/// Calls `f(key, metadata)` for each matching key and collects the results.
/// After [`initialize`]: lock-free. Before: acquires Mutex.
pub fn keys_with_metadata<M: 'static, R>(
    f: impl Fn(&'static str, &M) -> R,
) -> Vec<R> {
    let collect = |map: &RegistryMap| -> Vec<R> {
        map.iter()
            .filter_map(|(&key, reg)| {
                reg.metadata
                    .get(&TypeId::of::<M>())
                    .and_then(|boxed| boxed.downcast_ref::<M>())
                    .map(|meta| f(key, meta))
            })
            .collect()
    };
    if let Some(frozen) = FROZEN.get() {
        return collect(frozen);
    }
    let guard = lock_build();
    guard.as_ref().map_or_else(Vec::new, collect)
}

#[cfg(test)]
pub(crate) fn is_registered(key: &str) -> bool {
    if let Some(frozen) = FROZEN.get() {
        return frozen.contains_key(key);
    }
    let guard = lock_build();
    guard.as_ref().map_or(false, |map| map.contains_key(key))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Clone, Default, Debug, Serialize, Deserialize)]
    struct TestVal(String);

    #[derive(Clone, Default, Debug, Serialize, Deserialize)]
    struct OtherVal(u64);

    fn unique_reg_key(name: &str) -> &'static str {
        let s = format!("reg_test_{}", name);
        Box::leak(s.into_boxed_str())
    }

    #[test]
    fn register_and_lookup() {
        let key = unique_reg_key("lookup");
        try_register::<TestVal>(key).unwrap();
        assert!(is_registered(key));
        assert!(!is_registered("reg_test_missing_xxx"));
    }

    #[test]
    fn idempotent_registration() {
        let key = unique_reg_key("idem");
        try_register::<TestVal>(key).unwrap();
        try_register::<TestVal>(key).unwrap();
    }

    #[test]
    fn conflicting_registration() {
        let key = unique_reg_key("conflict");
        try_register::<TestVal>(key).unwrap();
        let err = try_register::<OtherVal>(key).unwrap_err();
        assert!(matches!(err, ContextError::AlreadyRegistered(_)));
    }
}