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
#[cfg(feature = "std")]
use std::string::String;

/// Metadata for sequence definitions (only available with `metadata` feature)
///
/// This struct is used by the `sequence!` macro to store compile-time metadata
/// about sequence numbers, which can be used for documentation generation and
/// enhanced error messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SequenceMetadata {
    /// The sequence number (1-999)
    pub number: u16,

    /// The constant name of the sequence (e.g., "MISSING")
    pub name: &'static str,

    /// Optional description of what this sequence represents
    pub description: Option<&'static str>,

    /// Typical severity level for errors in this sequence
    pub typical_severity: Option<&'static str>,

    /// Hints for resolving errors in this sequence
    pub hints: &'static [&'static str],

    /// Related error codes or sequences
    pub related: &'static [&'static str],

    /// Version/date when this sequence was introduced
    pub introduced: Option<&'static str>,
}

impl SequenceMetadata {
    /// Check if this sequence has any metadata beyond just the number and name
    pub const fn has_metadata(&self) -> bool {
        self.description.is_some()
            || self.typical_severity.is_some()
            || !self.hints.is_empty()
            || !self.related.is_empty()
            || self.introduced.is_some()
    }
}

/// Runtime diagnostic metadata for error handling
///
/// This struct contains ONLY the essential information needed at runtime for
/// error handling, categorization, and user-facing messages. Documentation-heavy
/// fields (descriptions, code examples) are NOT included to minimize binary size.
///
/// Use this for production error handling where documentation is not needed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticRuntime {
    /// The severity level (Error, Warning, Info, etc.)
    pub severity: crate::Severity,

    /// Optional namespace identifier for multi-service environments
    ///
    /// When set, enables WDP Part 7 combined IDs (e.g., "nsHash-codeHash").
    /// Format: lowercase with underscores (e.g., "auth_service", "payment_lib")
    pub namespace: Option<&'static str>,

    /// Pre-computed 5-character base62 namespace hash (WDP Part 7)
    ///
    /// Computed using xxHash64 with seed "wdp-ns-v1" at compile time.
    /// Only present when `namespace` is set.
    pub namespace_hash: Option<&'static str>,

    /// The component identifier
    pub component: &'static str,

    /// The primary category identifier
    pub primary: &'static str,

    /// The sequence identifier (constant name like "MISSING")
    pub sequence: &'static str,

    /// The sequence numeric value (e.g., 1 for MISSING)
    pub sequence_value: u16,

    /// The full error code string (e.g., "E.CRYPTO.SALT.001")
    pub code: &'static str,

    /// Message template with {{field}} placeholders
    ///
    /// Use `{{field}}` for regular fields and `{{pii/field}}` for PII fields.
    /// Example: `"Token for {{pii/email}} expired at {{timestamp}}"`
    pub message: &'static str,

    /// Non-PII field names used in the message template
    ///
    /// These are referenced as `{{field}}` in the message and sent in the `f` object
    /// in the wire protocol.
    pub fields: &'static [&'static str],

    /// PII field names used in the message template
    ///
    /// These are referenced as `{{pii/field}}` in the message and sent in the
    /// `pii.data` object in the wire protocol. Clients should handle these with
    /// appropriate access control and redaction.
    pub pii_fields: &'static [&'static str],

    /// Whether this diagnostic contains PII placeholders
    ///
    /// Automatically derived from whether `pii_fields` is non-empty.
    /// Useful for quick filtering and compliance checks.
    pub contains_pii: bool,

    /// Role-based visibility: "Public", "Developer", or "Internal"
    pub role: Option<&'static str>,

    /// Tags for categorization and filtering
    pub tags: &'static [&'static str],

    /// Related error codes for cross-referencing
    pub related_codes: &'static [&'static str],

    /// Runtime hints (end-user facing)
    pub hints_runtime: &'static [&'static str],

    /// Hints available in both runtime and compile-time contexts
    pub hints_both: &'static [&'static str],

    /// Role-gated hints for runtime context (for doc generation)
    /// Format: [("hint", "Public"), ("hint2", "Developer"), ...]
    #[cfg(feature = "metadata")]
    pub hints_runtime_gated: &'static [(&'static str, &'static str)],

    /// Role-gated hints for both contexts (for doc generation)
    /// Format: [("hint", "Public"), ("hint2", "Developer"), ...]
    #[cfg(feature = "metadata")]
    pub hints_both_gated: &'static [(&'static str, &'static str)],

    /// Role-gated tags (for doc generation)
    /// Format: [("tag", "Public"), ("tag2", "Developer"), ...]
    #[cfg(feature = "metadata")]
    pub tags_gated: &'static [(&'static str, &'static str)],

    /// Role-gated related codes (for doc generation)
    /// Format: [("code", "Public"), ("code2", "Developer"), ...]
    #[cfg(feature = "metadata")]
    pub related_codes_gated: &'static [(&'static str, &'static str)],

    /// Pre-computed 5-character base62 hash
    ///
    /// This hash is computed at compile time using the global hash configuration
    /// and embedded as a constant. It provides a compact identifier for the error
    /// code that can be used in logs, catalogs, and network protocols.
    pub hash: &'static str,
}

/// A code snippet definition for documentation
///
/// This struct represents a single code example with rich metadata including
/// language, correct/incorrect code, explanation, and role-based visibility.
#[cfg(feature = "metadata")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodeSnippetDef {
    /// Programming language for syntax highlighting (e.g., "rust", "javascript", "python")
    pub language: Option<&'static str>,

    /// Code snippet showing incorrect usage
    pub wrong: Option<&'static str>,

    /// Code snippet showing correct usage
    pub correct: Option<&'static str>,

    /// Explanation of why the correct version is better
    pub explanation: Option<&'static str>,

    /// Role-based visibility: "Public", "Developer", or "Internal"
    pub role: &'static str,
}

/// Compile-time documentation metadata
///
/// This struct contains verbose documentation, code examples, and detailed
/// explanations that are ONLY used during documentation generation. These fields
/// are NOT included in runtime binaries when the `metadata` feature is disabled.
///
/// Use this for generating comprehensive documentation while keeping production
/// binaries lean.
#[cfg(feature = "metadata")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticDocs {
    /// Human-readable description (can be verbose)
    pub description: Option<&'static str>,

    /// Role-gated code snippets with rich metadata
    /// Multiple snippets allowed, each with its own role visibility
    pub code_snippets: &'static [CodeSnippetDef],

    /// URL to detailed documentation
    pub docs_url: Option<&'static str>,

    /// Version when this diagnostic was introduced
    pub introduced: Option<&'static str>,

    /// Version when this diagnostic was deprecated (if applicable)
    pub deprecated: Option<&'static str>,

    /// Compile-time hints (developer/documentation facing)
    pub hints_compiletime: &'static [&'static str],

    /// Related error codes for documentation cross-referencing
    pub see_also: &'static [&'static str],

    /// Role-gated hints for compile-time context (for doc generation)
    /// Format: [("hint", "Public"), ("hint2", "Developer"), ...]
    #[cfg(feature = "metadata")]
    pub hints_compiletime_gated: &'static [(&'static str, &'static str)],

    /// Role-gated see also (for doc generation)
    /// Format: [("code", "Public"), ("code2", "Developer"), ...]
    #[cfg(feature = "metadata")]
    pub see_also_gated: &'static [(&'static str, &'static str)],
}

/// Complete diagnostic with both runtime and documentation metadata
///
/// This combines DiagnosticRuntime (always present) with DiagnosticDocs
/// (only with metadata feature). Use this for comprehensive documentation
/// generation where all information is needed.
#[cfg(feature = "metadata")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticComplete {
    /// Runtime metadata (always present)
    pub runtime: DiagnosticRuntime,

    /// Compile-time documentation (only with metadata feature)
    pub docs: Option<DiagnosticDocs>,
}

#[cfg(feature = "metadata")]
impl crate::traits::ErrorMetadata for DiagnosticComplete {
    fn code(&self) -> &'static str {
        self.runtime.code
    }

    fn description(&self) -> Option<&'static str> {
        // First try to get from docs, then fall back to None
        self.docs.as_ref().and_then(|d| d.description)
    }

    fn hints(&self) -> &'static [&'static str] {
        // Combine runtime and docs hints
        // For now, return runtime hints + both contexts
        // Note: This is a limitation - we can't dynamically combine slices into a new static slice
        // So we'll return just the runtime hints
        self.runtime.hints_runtime
    }

    fn role(&self) -> crate::traits::Role {
        // Parse the role string from runtime metadata
        match self.runtime.role {
            Some("Public") => crate::traits::Role::Public,
            Some("Developer") => crate::traits::Role::Developer,
            Some("Internal") => crate::traits::Role::Internal,
            _ => crate::traits::Role::Public, // Default to Public
        }
    }

    fn docs_url(&self) -> Option<&'static str> {
        self.docs.as_ref().and_then(|d| d.docs_url)
    }

    fn examples(&self) -> &'static [&'static str] {
        // Return the message as an example
        &[]
    }

    fn related_codes(&self) -> &'static [&'static str] {
        // Combine runtime related_codes and docs see_also
        // For now, just return runtime related_codes
        self.runtime.related_codes
    }

    fn since_version(&self) -> Option<&'static str> {
        self.docs.as_ref().and_then(|d| d.introduced)
    }
}

/// Complete diagnostic metadata with full 4-part error code
///
/// **DEPRECATED**: Use `DiagnosticRuntime` for runtime error handling,
/// `DiagnosticDocs` for compile-time documentation, or `DiagnosticComplete`
/// for both. This struct is kept for backward compatibility.
///
/// This struct is generated by the `diag!` macro and provides comprehensive
/// documentation for a complete diagnostic definition. Unlike the individual
/// component/primary/sequence metadata, this represents a **complete error**
/// with all parts and usage information.
///
/// This is used **only for documentation generation** - frameworks like QuackPatch
/// build their own invocation layer on top of this metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticMetadata {
    /// The severity level (Error, Warning, Info, etc.)
    pub severity: crate::Severity,

    /// The component identifier
    pub component: &'static str,

    /// The primary category identifier
    pub primary: &'static str,

    /// The sequence identifier (constant name like "MISSING")
    pub sequence: &'static str,

    /// The sequence numeric value (e.g., 1 for MISSING)
    pub sequence_value: u16,

    /// Message template with {field} placeholders
    pub message: &'static str,

    /// Field names used in the message template
    pub fields: &'static [&'static str],

    /// Human-readable description of this diagnostic
    pub description: Option<&'static str>,

    /// Helpful hints for resolving this diagnostic
    pub hints: &'static [&'static str],

    /// Role-gated code snippets with rich metadata
    #[cfg(feature = "metadata")]
    pub code_snippets: &'static [CodeSnippetDef],

    /// Role-based visibility: "Public", "Developer", or "Internal"
    pub role: Option<&'static str>,

    /// Tags for categorization and filtering
    pub tags: &'static [&'static str],

    /// Related error codes for cross-referencing
    pub related_codes: &'static [&'static str],

    /// URL to detailed documentation
    pub docs_url: Option<&'static str>,

    /// Version when this diagnostic was introduced
    pub introduced: Option<&'static str>,

    /// Version when this diagnostic was deprecated (if applicable)
    pub deprecated: Option<&'static str>,
}

impl DiagnosticRuntime {
    /// Default values for metadata-gated fields (used with .. syntax in struct initialization)
    #[cfg(feature = "metadata")]
    pub const INIT_WITH_DEFAULTS: Self = Self {
        severity: crate::Severity::Error,
        namespace: None,
        namespace_hash: None,
        component: "",
        primary: "",
        sequence: "",
        sequence_value: 0,
        code: "",
        message: "",
        fields: &[],
        pii_fields: &[],
        contains_pii: false,
        role: None,
        tags: &[],
        related_codes: &[],
        hints_runtime: &[],
        hints_both: &[],
        hints_runtime_gated: &[],
        hints_both_gated: &[],
        tags_gated: &[],
        related_codes_gated: &[],
        hash: "",
    };

    /// Default values for non-metadata builds (used with .. syntax in struct initialization)
    #[cfg(not(feature = "metadata"))]
    pub const INIT_WITH_DEFAULTS: Self = Self {
        severity: crate::Severity::Error,
        namespace: None,
        namespace_hash: None,
        component: "",
        primary: "",
        sequence: "",
        sequence_value: 0,
        code: "",
        message: "",
        fields: &[],
        pii_fields: &[],
        contains_pii: false,
        role: None,
        tags: &[],
        related_codes: &[],
        hints_runtime: &[],
        hints_both: &[],
        hash: "",
    };

    /// Get the full diagnostic code as parts (severity, component, primary, sequence)
    pub const fn code_parts(&self) -> (&'static str, &'static str, &'static str, &'static str) {
        // Use single character severity codes (E, W, I, C, B, T, H, S, K)
        let severity_str = match self.severity {
            crate::Severity::Error => "E",
            crate::Severity::Warning => "W",
            crate::Severity::Info => "I",
            crate::Severity::Critical => "C",
            crate::Severity::Blocked => "B",
            crate::Severity::Trace => "T",
            crate::Severity::Help => "H",
            crate::Severity::Success => "S",
            crate::Severity::Completed => "K",
        };
        (severity_str, self.component, self.primary, self.sequence)
    }

    /// Get the full diagnostic code as a string (e.g., "E.Auth.InvalidCredentials.MISSING")
    ///
    /// Note: This uses the sequence NAME. For canonical format with numeric sequence,
    /// use `canonical_code()` instead.
    #[cfg(feature = "std")]
    pub fn full_code(&self) -> String {
        let (sev, comp, prim, seq) = self.code_parts();
        std::format!("{}.{}.{}.{}", sev, comp, prim, seq)
    }

    /// Get the canonical diagnostic code with zero-padded numeric sequence (e.g., "E.AUTH.TOKEN.001")
    ///
    /// This is the WDP-conformant format used in documentation and wire protocols.
    /// Component and primary are always uppercased to ensure canonical form.
    #[cfg(feature = "std")]
    pub fn canonical_code(&self) -> String {
        let severity_str = match self.severity {
            crate::Severity::Error => "E",
            crate::Severity::Warning => "W",
            crate::Severity::Info => "I",
            crate::Severity::Critical => "C",
            crate::Severity::Blocked => "B",
            crate::Severity::Trace => "T",
            crate::Severity::Help => "H",
            crate::Severity::Success => "S",
            crate::Severity::Completed => "K",
        };
        std::format!(
            "{}.{}.{}.{:03}",
            severity_str,
            self.component.to_ascii_uppercase(),
            self.primary.to_ascii_uppercase(),
            self.sequence_value
        )
    }

    /// Check if this diagnostic has field placeholders
    pub const fn has_fields(&self) -> bool {
        !self.fields.is_empty()
    }

    /// Check if this diagnostic has any hints (runtime or both)
    pub const fn has_hints(&self) -> bool {
        !self.hints_runtime.is_empty() || !self.hints_both.is_empty()
    }

    /// Get all runtime hints (combines runtime-specific and both)
    pub fn all_hints(&self) -> impl Iterator<Item = &&'static str> {
        self.hints_runtime.iter().chain(self.hints_both.iter())
    }

    /// Check if this diagnostic has a namespace
    pub const fn has_namespace(&self) -> bool {
        self.namespace.is_some()
    }

    /// Get the compact ID (5-character hash)
    ///
    /// Returns the pre-computed hash for this diagnostic code.
    pub const fn compact_id(&self) -> &'static str {
        self.hash
    }

    /// Get the combined ID (WDP Part 7 format: "nsHash-codeHash")
    ///
    /// Returns the 11-character combined ID if namespace is set,
    /// otherwise returns just the 5-character compact ID.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // With namespace: "h4tYw2-81E9g"
    /// // Without namespace: "81E9g"
    /// let id = diag.combined_id();
    /// ```
    #[cfg(feature = "std")]
    pub fn combined_id(&self) -> std::string::String {
        match self.namespace_hash {
            Some(ns_hash) => std::format!("{}-{}", ns_hash, self.hash),
            None => std::string::String::from(self.hash),
        }
    }
}

#[cfg(feature = "metadata")]
impl DiagnosticDocs {
    /// Check if this diagnostic has any hints (compile-time or both)
    pub const fn has_hints(&self) -> bool {
        !self.hints_compiletime.is_empty()
    }

    /// Check if this has any documentation beyond basic fields
    pub const fn has_comprehensive_docs(&self) -> bool {
        self.description.is_some()
            || !self.code_snippets.is_empty()
            || self.docs_url.is_some()
            || !self.hints_compiletime.is_empty()
    }
}

#[cfg(feature = "metadata")]
impl DiagnosticComplete {
    /// Get the full diagnostic code as parts (severity, component, primary, sequence)
    pub const fn code_parts(&self) -> (&'static str, &'static str, &'static str, &'static str) {
        self.runtime.code_parts()
    }

    /// Get the full diagnostic code as a string (uses sequence NAME)
    ///
    /// For canonical format with numeric sequence, use `canonical_code()` instead.
    #[cfg(feature = "std")]
    pub fn full_code(&self) -> String {
        self.runtime.full_code()
    }

    /// Get the canonical diagnostic code with zero-padded numeric sequence (e.g., "E.AUTH.TOKEN.001")
    ///
    /// This is the WDP-conformant format used in documentation and wire protocols.
    #[cfg(feature = "std")]
    pub fn canonical_code(&self) -> String {
        self.runtime.canonical_code()
    }

    /// Get all hints (runtime + both + compile-time)
    pub fn all_hints(&self) -> impl Iterator<Item = &'static str> + '_ {
        let runtime_hints = self.runtime.hints_runtime.iter().copied();
        let both_hints = self.runtime.hints_both.iter().copied();
        let compile_hints = self
            .docs
            .as_ref()
            .map(|d| d.hints_compiletime.iter().copied())
            .into_iter()
            .flatten();

        runtime_hints.chain(both_hints).chain(compile_hints)
    }
}

impl DiagnosticMetadata {
    /// Get the full diagnostic code as parts (severity, component, primary, sequence)
    pub const fn code_parts(&self) -> (&'static str, &'static str, &'static str, &'static str) {
        // Use single character severity codes (E, W, I, C, B, T, H, S, K)
        let severity_str = match self.severity {
            crate::Severity::Error => "E",
            crate::Severity::Warning => "W",
            crate::Severity::Info => "I",
            crate::Severity::Critical => "C",
            crate::Severity::Blocked => "B",
            crate::Severity::Trace => "T",
            crate::Severity::Help => "H",
            crate::Severity::Success => "S",
            crate::Severity::Completed => "K",
        };
        (severity_str, self.component, self.primary, self.sequence)
    }

    /// Get the full diagnostic code as a string (e.g., "Error.Auth.InvalidCredentials.MISSING")
    #[cfg(feature = "std")]
    pub fn full_code(&self) -> String {
        let (sev, comp, prim, seq) = self.code_parts();
        std::format!("{}.{}.{}.{}", sev, comp, prim, seq)
    }

    /// Check if this diagnostic has field placeholders
    pub const fn has_fields(&self) -> bool {
        !self.fields.is_empty()
    }

    /// Check if this diagnostic has hints
    pub const fn has_hints(&self) -> bool {
        !self.hints.is_empty()
    }
}