waddling-errors 0.7.3

Structured, secure-by-default diagnostic codes for distributed systems with no_std and role-based documentation
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
//! Global registry for automatic diagnostic, component, and primary registration
//!
//! This module provides infrastructure for diagnostics, components, and primaries
//! to auto-register themselves without any manual registration code.
//!
//! # Features
//!
//! - **Diagnostic Registration**: Auto-register diagnostics with format preferences
//! - **Component Registration**: Auto-register components with metadata
//! - **Primary Registration**: Auto-register primaries with metadata
//! - **Doc Generation Integration**: Bulk registration with `DocRegistry`
//!
//! # Usage with `ctor`
//!
//! When using the `auto-register` feature, macros will generate `#[ctor]` functions
//! that automatically register items at program initialization time:
//!
//! ```rust,ignore
//! component! {
//!     #[auto_register]
//!     Auth {
//!         description: "Authentication system",
//!         tags: ["security"]
//!     }
//! }
//! // Component is automatically registered at startup!
//! ```

use std::sync::Mutex;
use std::vec::Vec;

/// A diagnostic registration entry
#[cfg(feature = "metadata")]
#[derive(Debug, Clone)]
pub struct DiagnosticRegistration {
    pub diagnostic: &'static crate::metadata::DiagnosticComplete,
    pub formats: &'static [&'static str],
}

/// A component registration entry
#[cfg(feature = "metadata")]
#[derive(Debug, Clone)]
pub struct ComponentRegistration {
    pub name: &'static str,
    pub description: Option<&'static str>,
    pub examples: &'static [&'static str],
    pub tags: &'static [&'static str],
    pub related: &'static [&'static str],
    pub formats: &'static [&'static str],
    /// Internal: Module path where this component was defined (for deduplication)
    #[doc(hidden)]
    #[allow(dead_code)]
    pub(crate) module_path: &'static str,
    /// Internal: Crate name where this component was defined (for deduplication)
    #[doc(hidden)]
    #[allow(dead_code)]
    pub(crate) crate_name: &'static str,
}

/// A primary registration entry
#[cfg(feature = "metadata")]
#[derive(Debug, Clone)]
pub struct PrimaryRegistration {
    pub name: &'static str,
    pub description: Option<&'static str>,
    pub examples: &'static [&'static str],
    pub tags: &'static [&'static str],
    pub related: &'static [&'static str],
    /// Internal: Module path where this primary was defined (for deduplication)
    #[doc(hidden)]
    #[allow(dead_code)]
    pub(crate) module_path: &'static str,
    /// Internal: Crate name where this primary was defined (for deduplication)
    #[doc(hidden)]
    #[allow(dead_code)]
    pub(crate) crate_name: &'static str,
}

/// A sequence registration entry
#[cfg(feature = "metadata")]
#[derive(Debug, Clone)]
pub struct SequenceRegistration {
    pub name: &'static str,
    pub number: u16,
    pub description: Option<&'static str>,
    pub typical_severity: Option<&'static str>,
    pub hints: &'static [&'static str],
}

/// A component location registration entry
#[cfg(feature = "metadata")]
#[derive(Debug, Clone)]
pub struct ComponentLocationRegistration {
    pub component: &'static str,
    pub file: &'static str,
    pub role: Option<crate::traits::Role>,
}

// ============================================================================
// Global Registries
// ============================================================================

#[cfg(feature = "metadata")]
static DIAGNOSTIC_REGISTRY: Mutex<Option<Vec<DiagnosticRegistration>>> = Mutex::new(None);

#[cfg(feature = "metadata")]
static COMPONENT_REGISTRY: Mutex<Option<Vec<ComponentRegistration>>> = Mutex::new(None);

#[cfg(feature = "metadata")]
static PRIMARY_REGISTRY: Mutex<Option<Vec<PrimaryRegistration>>> = Mutex::new(None);

#[cfg(feature = "metadata")]
static SEQUENCE_REGISTRY: Mutex<Option<Vec<SequenceRegistration>>> = Mutex::new(None);

#[cfg(feature = "metadata")]
static COMPONENT_LOCATION_REGISTRY: Mutex<Option<Vec<ComponentLocationRegistration>>> =
    Mutex::new(None);

// ============================================================================
// Diagnostic Registration
// ============================================================================

/// Register a diagnostic at initialization time
///
/// This is typically called automatically by macro-generated code.
#[cfg(feature = "metadata")]
pub fn register_diagnostic(
    diagnostic: &'static crate::metadata::DiagnosticComplete,
    formats: &'static [&'static str],
) {
    let mut registry = DIAGNOSTIC_REGISTRY.lock().unwrap();
    if registry.is_none() {
        *registry = Some(Vec::new());
    }
    registry.as_mut().unwrap().push(DiagnosticRegistration {
        diagnostic,
        formats,
    });
}

/// Collect all registered diagnostics for documentation generation
///
/// This consumes the registry and returns all registered diagnostics.
/// Subsequent calls will return an empty vector unless new registrations occur.
#[cfg(all(feature = "metadata", feature = "doc-gen"))]
pub fn collect_all_diagnostics() -> Vec<DiagnosticRegistration> {
    let mut registry = DIAGNOSTIC_REGISTRY.lock().unwrap();
    registry.take().unwrap_or_default()
}

/// Get a snapshot of all registered diagnostics without consuming the registry
#[cfg(feature = "metadata")]
pub fn get_diagnostics() -> Vec<DiagnosticRegistration> {
    let registry = DIAGNOSTIC_REGISTRY.lock().unwrap();
    registry.as_ref().map(|v| v.clone()).unwrap_or_default()
}

/// Clear the diagnostic registry
#[cfg(feature = "metadata")]
pub fn clear_diagnostics() {
    let mut registry = DIAGNOSTIC_REGISTRY.lock().unwrap();
    *registry = Some(Vec::new());
}

// ============================================================================
// Component Registration
// ============================================================================

/// Register a component at initialization time
///
/// This is typically called automatically by macro-generated code.
#[cfg(feature = "metadata")]
#[allow(clippy::too_many_arguments)]
pub fn register_component(
    name: &'static str,
    description: Option<&'static str>,
    examples: &'static [&'static str],
    tags: &'static [&'static str],
    related: &'static [&'static str],
    formats: &'static [&'static str],
    module_path: &'static str,
    crate_name: &'static str,
) {
    let mut registry = COMPONENT_REGISTRY.lock().unwrap();
    if registry.is_none() {
        *registry = Some(Vec::new());
    }
    registry.as_mut().unwrap().push(ComponentRegistration {
        name,
        description,
        examples,
        tags,
        related,
        formats,
        module_path,
        crate_name,
    });
}

/// Collect all registered components
///
/// This consumes the registry and returns all registered components.
/// Subsequent calls will return an empty vector unless new registrations occur.
#[cfg(feature = "metadata")]
pub fn collect_all_components() -> Vec<ComponentRegistration> {
    let mut registry = COMPONENT_REGISTRY.lock().unwrap();
    registry.take().unwrap_or_default()
}

/// Get a snapshot of all registered components without consuming the registry
#[cfg(feature = "metadata")]
pub fn get_components() -> Vec<ComponentRegistration> {
    let registry = COMPONENT_REGISTRY.lock().unwrap();
    registry.as_ref().map(|v| v.clone()).unwrap_or_default()
}

/// Clear the component registry
#[cfg(feature = "metadata")]
pub fn clear_components() {
    let mut registry = COMPONENT_REGISTRY.lock().unwrap();
    *registry = Some(Vec::new());
}

/// Search components by name pattern (case-insensitive, supports wildcards)
#[cfg(feature = "metadata")]
pub fn search_components(pattern: &str) -> Vec<ComponentRegistration> {
    let components = get_components();
    if pattern == "*" {
        return components;
    }

    let pattern_upper = pattern.to_uppercase();
    components
        .into_iter()
        .filter(|c| {
            let name_upper = c.name.to_uppercase();
            if pattern_upper.contains('*') {
                // Simple wildcard matching
                let parts: Vec<&str> = pattern_upper.split('*').collect();
                if parts.len() == 2 && parts[0].is_empty() {
                    // Pattern: *SUFFIX
                    name_upper.ends_with(parts[1])
                } else if parts.len() == 2 && parts[1].is_empty() {
                    // Pattern: PREFIX*
                    name_upper.starts_with(parts[0])
                } else if parts.len() == 2 {
                    // Pattern: PREFIX*SUFFIX
                    name_upper.starts_with(parts[0]) && name_upper.ends_with(parts[1])
                } else {
                    // Complex pattern or multiple wildcards - fallback to contains
                    name_upper.contains(&pattern_upper.replace('*', ""))
                }
            } else {
                name_upper == pattern_upper
            }
        })
        .collect()
}

// ============================================================================
// Primary Registration
// ============================================================================

/// Register a primary at initialization time
///
/// This is typically called automatically by macro-generated code.
#[cfg(feature = "metadata")]
pub fn register_primary(
    name: &'static str,
    description: Option<&'static str>,
    examples: &'static [&'static str],
    tags: &'static [&'static str],
    related: &'static [&'static str],
    module_path: &'static str,
    crate_name: &'static str,
) {
    let mut registry = PRIMARY_REGISTRY.lock().unwrap();
    if registry.is_none() {
        *registry = Some(Vec::new());
    }
    registry.as_mut().unwrap().push(PrimaryRegistration {
        name,
        description,
        examples,
        tags,
        related,
        module_path,
        crate_name,
    });
}

/// Collect all registered primaries
///
/// This consumes the registry and returns all registered primaries.
/// Subsequent calls will return an empty vector unless new registrations occur.
#[cfg(feature = "metadata")]
pub fn collect_all_primaries() -> Vec<PrimaryRegistration> {
    let mut registry = PRIMARY_REGISTRY.lock().unwrap();
    registry.take().unwrap_or_default()
}

/// Get a snapshot of all registered primaries without consuming the registry
#[cfg(feature = "metadata")]
pub fn get_primaries() -> Vec<PrimaryRegistration> {
    let registry = PRIMARY_REGISTRY.lock().unwrap();
    registry.as_ref().map(|v| v.clone()).unwrap_or_default()
}

/// Clear the primary registry
#[cfg(feature = "metadata")]
pub fn clear_primaries() {
    let mut registry = PRIMARY_REGISTRY.lock().unwrap();
    *registry = Some(Vec::new());
}

/// Search primaries by name pattern (case-insensitive, supports wildcards)
#[cfg(feature = "metadata")]
pub fn search_primaries(pattern: &str) -> Vec<PrimaryRegistration> {
    let primaries = get_primaries();
    if pattern == "*" {
        return primaries;
    }

    let pattern_upper = pattern.to_uppercase();
    primaries
        .into_iter()
        .filter(|p| {
            let name_upper = p.name.to_uppercase();
            if pattern_upper.contains('*') {
                // Simple wildcard matching
                let parts: Vec<&str> = pattern_upper.split('*').collect();
                if parts.len() == 2 && parts[0].is_empty() {
                    // Pattern: *SUFFIX
                    name_upper.ends_with(parts[1])
                } else if parts.len() == 2 && parts[1].is_empty() {
                    // Pattern: PREFIX*
                    name_upper.starts_with(parts[0])
                } else if parts.len() == 2 {
                    // Pattern: PREFIX*SUFFIX
                    name_upper.starts_with(parts[0]) && name_upper.ends_with(parts[1])
                } else {
                    // Complex pattern or multiple wildcards - fallback to contains
                    name_upper.contains(&pattern_upper.replace('*', ""))
                }
            } else {
                name_upper == pattern_upper
            }
        })
        .collect()
}

// ============================================================================
// Sequence Registration
// ============================================================================

/// Register a sequence at initialization time
///
/// This is typically called automatically by macro-generated code.
#[cfg(feature = "metadata")]
pub fn register_sequence(
    name: &'static str,
    number: u16,
    description: Option<&'static str>,
    typical_severity: Option<&'static str>,
    hints: &'static [&'static str],
) {
    let mut registry = SEQUENCE_REGISTRY.lock().unwrap();
    if registry.is_none() {
        *registry = Some(Vec::new());
    }
    registry.as_mut().unwrap().push(SequenceRegistration {
        name,
        number,
        description,
        typical_severity,
        hints,
    });
}

/// Collect all registered sequences
///
/// This consumes the registry and returns all registered sequences.
/// Subsequent calls will return an empty vector unless new registrations occur.
#[cfg(feature = "metadata")]
pub fn collect_all_sequences() -> Vec<SequenceRegistration> {
    let mut registry = SEQUENCE_REGISTRY.lock().unwrap();
    registry.take().unwrap_or_default()
}

/// Get a snapshot of all registered sequences without consuming the registry
#[cfg(feature = "metadata")]
pub fn get_sequences() -> Vec<SequenceRegistration> {
    let registry = SEQUENCE_REGISTRY.lock().unwrap();
    registry.as_ref().map(|v| v.clone()).unwrap_or_default()
}

/// Clear the sequence registry
#[cfg(feature = "metadata")]
pub fn clear_sequences() {
    let mut registry = SEQUENCE_REGISTRY.lock().unwrap();
    *registry = Some(Vec::new());
}

// ============================================================================
// Component Location Registration
// ============================================================================

/// Register a component location at initialization time
///
/// This is typically called automatically by `component_location!` macro-generated code.
#[cfg(feature = "metadata")]
pub fn register_component_location(
    component: &'static str,
    file: &'static str,
    role: Option<crate::traits::Role>,
) {
    let mut registry = COMPONENT_LOCATION_REGISTRY.lock().unwrap();
    if registry.is_none() {
        *registry = Some(Vec::new());
    }
    registry
        .as_mut()
        .unwrap()
        .push(ComponentLocationRegistration {
            component,
            file,
            role,
        });
}

/// Collect all registered component locations
///
/// This consumes the registry and returns all registered locations.
/// Subsequent calls will return an empty vector unless new registrations occur.
#[cfg(feature = "metadata")]
pub fn collect_all_component_locations() -> Vec<ComponentLocationRegistration> {
    let mut registry = COMPONENT_LOCATION_REGISTRY.lock().unwrap();
    registry.take().unwrap_or_default()
}

/// Get a snapshot of all registered component locations without consuming the registry
#[cfg(feature = "metadata")]
pub fn get_component_locations() -> Vec<ComponentLocationRegistration> {
    let registry = COMPONENT_LOCATION_REGISTRY.lock().unwrap();
    registry.as_ref().map(|v| v.clone()).unwrap_or_default()
}

/// Clear the component location registry
#[cfg(feature = "metadata")]
pub fn clear_component_locations() {
    let mut registry = COMPONENT_LOCATION_REGISTRY.lock().unwrap();
    *registry = Some(Vec::new());
}

// ============================================================================
// Doc Generation Integration
// ============================================================================

/// Register all collected diagnostics with a DocRegistry
///
/// This function registers all auto-registered diagnostics, components, primaries,
/// and sequences with the provided DocRegistry. The format hints from `<json>`, `<html>`,
/// etc. in the diag! macro are preserved, enabling format-based filtering during render.
#[cfg(all(feature = "metadata", feature = "doc-gen", not(target_arch = "wasm32")))]
pub fn register_all_with_doc_gen(doc_gen: &mut crate::doc_generator::DocRegistry) {
    let diagnostics = get_diagnostics();
    for entry in &diagnostics {
        // Use the new method that preserves format hints
        doc_gen.register_diagnostic_complete_with_formats(entry.diagnostic, entry.formats);
    }

    let components = get_components();
    for comp in &components {
        doc_gen.register_component(comp.name, comp.description, comp.examples, comp.tags);
    }

    let primaries = get_primaries();
    for prim in &primaries {
        doc_gen.register_primary(prim.name, prim.description, prim.examples, prim.related);
    }

    let sequences = get_sequences();
    for seq in &sequences {
        doc_gen.register_sequence(
            seq.name,
            seq.number,
            seq.description,
            seq.typical_severity,
            seq.hints,
        );
    }

    // Register component locations (from component_location! macro)
    let locations = get_component_locations();
    for loc in &locations {
        doc_gen.register_component_location_with_role(loc.component, loc.file, loc.role);
    }
}

/// Get statistics about registered items
///
/// Returns (diagnostics, components, primaries, sequences, component_locations)
#[cfg(feature = "metadata")]
pub fn statistics() -> (usize, usize, usize, usize, usize) {
    let diagnostics = get_diagnostics().len();
    let components = get_components().len();
    let primaries = get_primaries().len();
    let sequences = get_sequences().len();
    let locations = get_component_locations().len();
    (diagnostics, components, primaries, sequences, locations)
}

// ============================================================================
// Hidden Implementation Details (for macro use)
// ============================================================================

#[cfg(feature = "metadata")]
#[doc(hidden)]
pub struct DiagnosticRegistrar {
    _private: (),
}

#[cfg(feature = "metadata")]
impl DiagnosticRegistrar {
    pub const fn new(
        _diagnostic: &'static crate::metadata::DiagnosticComplete,
        _formats: &'static [&'static str],
    ) -> Self {
        // Use a const fn to trigger registration via static initialization
        // The actual registration happens in the static variable's initialization
        Self { _private: () }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(all(test, feature = "metadata"))]
mod tests {
    use super::*;

    #[test]
    fn test_component_registration() {
        clear_components();

        register_component(
            "TEST_COMP",
            Some("Test component"),
            &["Example 1"],
            &["test"],
            &[],
            &["json"],
            "test::module",
            "test_crate",
        );

        let components = get_components();
        assert_eq!(components.len(), 1);
        assert_eq!(components[0].name, "TEST_COMP");
        assert_eq!(components[0].description, Some("Test component"));
    }

    #[test]
    fn test_primary_registration() {
        clear_primaries();

        register_primary(
            "TEST_PRIM",
            Some("Test primary"),
            &["Example 1"],
            &["test"],
            &[],
            "test::module",
            "test_crate",
        );

        let primaries = get_primaries();
        assert_eq!(primaries.len(), 1);
        assert_eq!(primaries[0].name, "TEST_PRIM");
        assert_eq!(primaries[0].description, Some("Test primary"));
    }

    #[test]
    fn test_search_components() {
        clear_components();

        register_component("AUTH", Some("Auth"), &[], &[], &[], &[], "test", "test");
        register_component("DATABASE", Some("DB"), &[], &[], &[], &[], "test", "test");
        register_component("API", Some("API"), &[], &[], &[], &[], "test", "test");

        // Exact match
        let results = search_components("AUTH");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "AUTH");

        // Wildcard prefix
        let results = search_components("A*");
        assert_eq!(results.len(), 2); // AUTH and API

        // Wildcard suffix
        let results = search_components("*BASE");
        assert_eq!(results.len(), 1); // DATABASE

        // Match all
        let results = search_components("*");
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn test_search_primaries() {
        clear_primaries();

        register_primary("TOKEN", Some("Token"), &[], &[], &[], "test", "test");
        register_primary("SESSION", Some("Session"), &[], &[], &[], "test", "test");
        register_primary("TIMEOUT", Some("Timeout"), &[], &[], &[], "test", "test");

        // Exact match
        let results = search_primaries("TOKEN");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "TOKEN");

        // Wildcard pattern
        let results = search_primaries("*OUT");
        assert_eq!(results.len(), 1); // TIMEOUT

        // Match all
        let results = search_primaries("*");
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn test_statistics() {
        clear_diagnostics();
        clear_components();
        clear_primaries();
        clear_sequences();

        register_component("C1", None, &[], &[], &[], &[], "test", "test");
        register_component("C2", None, &[], &[], &[], &[], "test", "test");
        register_primary("P1", None, &[], &[], &[], "test", "test");
        register_sequence("S1", 1, None, None, &[]);

        let (diags, comps, prims, seqs, _locs) = statistics();
        assert_eq!(diags, 0);
        assert_eq!(comps, 2);
        assert_eq!(prims, 1);
        assert_eq!(seqs, 1);
    }

    #[test]
    fn test_sequence_registration() {
        clear_sequences();

        register_sequence(
            "MISSING",
            1,
            Some("Required item"),
            Some("Error"),
            &["hint1"],
        );

        let sequences = get_sequences();
        assert_eq!(sequences.len(), 1);
        assert_eq!(sequences[0].name, "MISSING");
        assert_eq!(sequences[0].number, 1);
        assert_eq!(sequences[0].description, Some("Required item"));
    }
}