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
//! Builder pattern for creating ErrorDoc instances
//!
//! This module provides a clean builder API to construct ErrorDoc objects,
//! eliminating code duplication in the registry and providing better error handling.

#[cfg(feature = "std")]
use std::{
    format,
    string::{String, ToString},
    vec::Vec,
};

#[cfg(not(feature = "std"))]
use alloc::{
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};

use super::types::{CodeSnippet, ErrorDoc};
use crate::traits::Role;

/// Error that can occur when parsing an error code string
#[derive(Debug, Clone, PartialEq)]
pub enum ParseError {
    /// Error code format is invalid (must be SEVERITY.COMPONENT.PRIMARY.SEQUENCE)
    InvalidFormat,
    /// Sequence number is not a valid u16
    InvalidSequence(String),
}

impl core::fmt::Display for ParseError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ParseError::InvalidFormat => {
                write!(
                    f,
                    "Invalid error code format, expected: SEVERITY.COMPONENT.PRIMARY.SEQUENCE"
                )
            }
            ParseError::InvalidSequence(val) => {
                write!(f, "Invalid sequence number: {}", val)
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseError {}

/// Parsed components of an error code
#[derive(Debug, Clone)]
struct ErrorCodeParts {
    severity: String,
    component: String,
    primary: String,
    sequence: u16,
}

/// Parse error code string into components
///
/// # Format
///
/// Error codes must follow the format: `SEVERITY.COMPONENT.PRIMARY.SEQUENCE`
///
/// # Examples
///
/// ```ignore
/// let parts = parse_error_code("E.AUTH.TOKEN.001")?;
/// assert_eq!(parts.severity, "E");
/// assert_eq!(parts.component, "AUTH");
/// assert_eq!(parts.primary, "TOKEN");
/// assert_eq!(parts.sequence, 1);
/// ```
fn parse_error_code(code: &str) -> Result<ErrorCodeParts, ParseError> {
    let parts: Vec<&str> = code.split('.').collect();

    if parts.len() != 4 {
        return Err(ParseError::InvalidFormat);
    }

    let sequence = parts[3]
        .parse::<u16>()
        .map_err(|_| ParseError::InvalidSequence(parts[3].to_string()))?;

    Ok(ErrorCodeParts {
        severity: parts[0].to_string(),
        component: parts[1].to_string(),
        primary: parts[2].to_string(),
        sequence,
    })
}

/// Builder for constructing ErrorDoc instances
///
/// Provides a fluent API for building error documentation with proper validation
/// and automatic hash generation.
///
/// # Examples
///
/// ```ignore
/// use waddling_errors::doc_generator::ErrorDocBuilder;
///
/// let error = ErrorDocBuilder::from_code("E.AUTH.TOKEN.001")?
///     .with_description("Invalid token")
///     .with_hints(&["Check token format", "Verify expiration"])
///     .with_tags(&["auth", "security"])
///     .with_role(Role::Public)
///     .build();
/// ```
#[derive(Debug)]
pub struct ErrorDocBuilder {
    // Core fields
    code: String,
    severity: String,
    component: String,
    primary: String,
    sequence: u16,

    // Content fields
    description: String,
    message: String,
    fields: Vec<String>,
    introduced: Option<String>,
    deprecated: Option<String>,
    docs_url: Option<String>,

    // Namespace fields (WDP Part 7)
    namespace: Option<String>,

    // Role-gated fields
    hints_gated: Vec<(String, String)>,
    tags_gated: Vec<(String, String)>,
    related_codes_gated: Vec<(String, String)>,
    see_also_gated: Vec<(String, String)>,

    // Metadata
    role: Option<String>,
    code_snippets: Vec<CodeSnippet>,

    // Version tracking
    version: Option<String>,
}

impl ErrorDocBuilder {
    /// Create a new builder from an error code string
    ///
    /// Parses the code and validates format. Returns error if code is invalid.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let builder = ErrorDocBuilder::from_code("E.AUTH.TOKEN.001")?;
    /// ```
    pub fn from_code(code: impl Into<String>) -> Result<Self, ParseError> {
        let code_str = code.into();
        let parts = parse_error_code(&code_str)?;

        Ok(Self {
            code: code_str,
            severity: parts.severity,
            component: parts.component,
            primary: parts.primary,
            sequence: parts.sequence,
            description: String::new(),
            message: String::new(),
            fields: Vec::new(),
            namespace: None,
            introduced: None,
            deprecated: None,
            docs_url: None,
            hints_gated: Vec::new(),
            tags_gated: Vec::new(),
            related_codes_gated: Vec::new(),
            see_also_gated: Vec::new(),
            role: None,
            code_snippets: Vec::new(),
            version: None,
        })
    }

    /// Create a builder from already-parsed components
    ///
    /// Useful when components are already available (e.g., from Code<C, P>)
    pub fn from_components(
        severity: impl Into<String>,
        component: impl Into<String>,
        primary: impl Into<String>,
        sequence: u16,
    ) -> Self {
        let severity_str = severity.into();
        let component_str = component.into();
        let primary_str = primary.into();
        let code = format!(
            "{}.{}.{}.{:03}",
            severity_str, component_str, primary_str, sequence
        );

        Self {
            code,
            severity: severity_str,
            component: component_str,
            primary: primary_str,
            sequence,
            description: String::new(),
            message: String::new(),
            fields: Vec::new(),
            namespace: None,
            introduced: None,
            deprecated: None,
            docs_url: None,
            hints_gated: Vec::new(),
            tags_gated: Vec::new(),
            related_codes_gated: Vec::new(),
            see_also_gated: Vec::new(),
            role: None,
            code_snippets: Vec::new(),
            version: None,
        }
    }

    /// Set the error description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Set the message template (with {{field}} placeholders)
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = message.into();
        self
    }

    /// Set the field names used in message placeholders
    pub fn with_fields(mut self, fields: Vec<String>) -> Self {
        self.fields = fields;
        self
    }

    /// Set the namespace identifier (WDP Part 7)
    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }

    /// Set when this error was introduced
    pub fn with_introduced(mut self, version: impl Into<String>) -> Self {
        self.introduced = Some(version.into());
        self
    }

    /// Set when this error was deprecated
    pub fn with_deprecated(mut self, version: impl Into<String>) -> Self {
        self.deprecated = Some(version.into());
        self
    }

    /// Set documentation URL
    pub fn with_docs_url(mut self, url: impl Into<String>) -> Self {
        self.docs_url = Some(url.into());
        self
    }

    /// Set version for version tracking
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// Add role-gated hints
    pub fn with_hints_gated(mut self, hints: Vec<(String, String)>) -> Self {
        self.hints_gated = hints;
        self
    }

    /// Add a single gated hint
    pub fn add_hint_gated(mut self, hint: impl Into<String>, role: impl Into<String>) -> Self {
        self.hints_gated.push((hint.into(), role.into()));
        self
    }

    /// Add role-gated tags
    pub fn with_tags_gated(mut self, tags: Vec<(String, String)>) -> Self {
        self.tags_gated = tags;
        self
    }

    /// Add a single gated tag
    pub fn add_tag_gated(mut self, tag: impl Into<String>, role: impl Into<String>) -> Self {
        self.tags_gated.push((tag.into(), role.into()));
        self
    }

    /// Add role-gated related codes
    pub fn with_related_codes_gated(mut self, codes: Vec<(String, String)>) -> Self {
        self.related_codes_gated = codes;
        self
    }

    /// Add a single gated related code
    pub fn add_related_code_gated(
        mut self,
        code: impl Into<String>,
        role: impl Into<String>,
    ) -> Self {
        self.related_codes_gated.push((code.into(), role.into()));
        self
    }

    /// Add role-gated see also references
    pub fn with_see_also_gated(mut self, refs: Vec<(String, String)>) -> Self {
        self.see_also_gated = refs;
        self
    }

    /// Add a single gated see also reference
    pub fn add_see_also_gated(
        mut self,
        reference: impl Into<String>,
        role: impl Into<String>,
    ) -> Self {
        self.see_also_gated.push((reference.into(), role.into()));
        self
    }

    /// Set the visibility role
    pub fn with_role(mut self, role: Role) -> Self {
        self.role = Some(format!("{:?}", role));
        self
    }

    /// Add code snippets
    pub fn with_code_snippets(mut self, snippets: Vec<CodeSnippet>) -> Self {
        self.code_snippets = snippets;
        self
    }

    /// Add a single code snippet
    pub fn add_code_snippet(mut self, snippet: CodeSnippet) -> Self {
        self.code_snippets.push(snippet);
        self
    }

    /// Build the final ErrorDoc
    ///
    /// Hash is automatically computed if the hash feature is enabled.
    pub fn build(self) -> ErrorDoc {
        // Auto-compute hash if feature is enabled using WDP-conformant function
        #[cfg(feature = "runtime-hash")]
        let hash: Option<String> = {
            use waddling_errors_hash::compute_wdp_hash;
            Some(compute_wdp_hash(&self.code))
        };

        // Auto-compute namespace hash if namespace is set
        #[cfg(feature = "runtime-hash")]
        let namespace_hash: Option<String> = self.namespace.as_ref().map(|ns| {
            use waddling_errors_hash::compute_wdp_namespace_hash;
            compute_wdp_namespace_hash(ns)
        });

        let mut error_doc = ErrorDoc::new(
            self.code,
            self.severity,
            self.component,
            self.primary,
            self.sequence,
            self.description,
            self.message,
            self.fields,
            self.namespace,
            #[cfg(feature = "runtime-hash")]
            namespace_hash,
            self.introduced.or(self.version),
            self.deprecated,
            self.docs_url,
            self.role,
            #[cfg(feature = "runtime-hash")]
            hash,
            self.code_snippets,
        );

        // Populate gated fields
        error_doc.hints_gated = self.hints_gated;
        error_doc.tags_gated = self.tags_gated;
        error_doc.related_codes_gated = self.related_codes_gated;
        error_doc.see_also_gated = self.see_also_gated;

        error_doc
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(not(feature = "std"))]
    use alloc::{vec, vec::Vec};

    #[test]
    fn test_parse_valid_code() {
        let parts = parse_error_code("E.AUTH.TOKEN.001").unwrap();
        assert_eq!(parts.severity, "E");
        assert_eq!(parts.component, "AUTH");
        assert_eq!(parts.primary, "TOKEN");
        assert_eq!(parts.sequence, 1);
    }

    #[test]
    fn test_parse_invalid_format() {
        assert!(matches!(
            parse_error_code("E.AUTH.TOKEN"),
            Err(ParseError::InvalidFormat)
        ));
    }

    #[test]
    fn test_parse_invalid_sequence() {
        assert!(matches!(
            parse_error_code("E.AUTH.TOKEN.ABC"),
            Err(ParseError::InvalidSequence(_))
        ));
    }

    #[test]
    fn test_builder_from_code() {
        let error = ErrorDocBuilder::from_code("E.AUTH.TOKEN.001")
            .unwrap()
            .with_description("Token missing")
            .add_hint_gated("Check header", "Public")
            .build();

        assert_eq!(error.code, "E.AUTH.TOKEN.001");
        assert_eq!(error.severity, "E");
        assert_eq!(error.component, "AUTH");
        assert_eq!(error.primary, "TOKEN");
        assert_eq!(error.sequence, 1);
        assert_eq!(error.description, "Token missing");
        assert_eq!(error.hints_gated.len(), 1);
        assert_eq!(error.hints_gated[0].0, "Check header");
        assert_eq!(error.hints_gated[0].1, "Public");
    }

    #[test]
    fn test_builder_from_components() {
        let error = ErrorDocBuilder::from_components("E", "AUTH", "TOKEN", 1)
            .with_description("Token missing")
            .build();

        assert_eq!(error.code, "E.AUTH.TOKEN.001");
        assert_eq!(error.description, "Token missing");
    }

    #[test]
    fn test_builder_with_gated_fields() {
        let error = ErrorDocBuilder::from_code("E.AUTH.TOKEN.001")
            .unwrap()
            .add_hint_gated("Public hint", "Public")
            .add_hint_gated("Internal hint", "Internal")
            .add_tag_gated("security", "Public")
            .build();

        assert_eq!(error.hints_gated.len(), 2);
        assert_eq!(error.tags_gated.len(), 1);
    }

    #[test]
    fn test_builder_with_role() {
        let error = ErrorDocBuilder::from_code("E.AUTH.TOKEN.001")
            .unwrap()
            .with_role(Role::Public)
            .build();

        assert_eq!(error.role, Some("Public".to_string()));
    }

    #[test]
    #[cfg(feature = "runtime-hash")]
    fn test_hash_auto_generated() {
        let error = ErrorDocBuilder::from_code("E.AUTH.TOKEN.001")
            .unwrap()
            .build();

        assert!(error.hash.is_some());
        assert_eq!(error.hash.unwrap().len(), 5);
    }
}