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
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
//! Catalog Renderer - Efficient Documentation Distribution
//!
//! This module provides a renderer that generates a catalog (lookup table)
//! mapping error hashes to their documentation. This enables:
//!
//! - **Compact network payloads**: Send hash + fields instead of full error
//! - **Client-side i18n**: Translate catalog locally
//! - **Offline support**: Cache catalog for offline use
//! - **IoT efficiency**: Devices send tiny payloads, server expands with catalog
//!
//! ## Use Cases
//!
//! ### 1. IoT Devices
//! ```text
//! Device: Sends "hCF3I,45.2" (12 bytes)
//! Server: Has catalog, expands to "E.SENSOR.TEMP.OVERHEAT: temp=45.2°C"
//! ```
//!
//! ### 2. Mobile Apps
//! ```text
//! Initial: Download catalog once (50 KB)
//! Ongoing: API sends {"h": "hCF3I", "f": {...}} (40 bytes)
//! App: Looks up hash in cached catalog
//! ```
//!
//! ### 3. Multi-language Support
//! ```text
//! English catalog: {"hCF3I": {"message": "Token expired"}}
//! Spanish catalog: {"hCF3I": {"message": "Token expirado"}}
//! Client picks language-specific catalog
//! ```

use crate::doc_generator::{DocRegistry, renderer::Renderer, types::ErrorDoc};
use crate::traits::Role;
use std::format;
#[cfg(feature = "runtime-hash")]
use std::fs::File;
#[cfg(feature = "runtime-hash")]
use std::io::Write;
use std::path::Path;
use std::string::String;

/// Catalog format type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CatalogFormat {
    /// Full format with all documentation fields
    Full,
    /// Compact format with minimal fields for production
    Compact,
    /// Minimal format with only essential fields (smallest)
    Minimal,
}

/// Catalog renderer for generating hash-to-error lookup tables
///
/// This renderer creates a JSON catalog that maps error hashes to their
/// documentation, enabling efficient error transmission and client-side expansion.
///
/// ## Output Format (Full)
///
/// ```json
/// {
///   "version": "1.0.0",
///   "generated": "2024-11-19T15:00:00Z",
///   "algorithm": "base62-ahash-v1",
///   "role": "Public",
///   "errors": {
///     "hCF3I": {
///       "code": "E.AUTH.TOKEN.001",
///       "severity": "Error",
///       "message": "Token expired at {expiry}",
///       "hints": ["Use refresh token endpoint"],
///       "tags": ["auth", "security"],
///       "docs_url": "https://docs.example.com/errors/E.AUTH.TOKEN.001"
///     }
///   }
/// }
/// ```
///
/// ## Output Format (Compact)
///
/// ```json
/// {
///   "v": "1.0.0",
///   "a": "base62-ahash-v1",
///   "e": {
///     "hCF3I": ["E.AUTH.TOKEN.001", "E", "Token expired at {expiry}"]
///   }
/// }
/// ```
///
/// ## Output Format (Minimal)
///
/// ```json
/// {
///   "hCF3I": ["E.AUTH.TOKEN.001", "Token expired at {expiry}"]
/// }
/// ```
pub struct CatalogRenderer {
    format: CatalogFormat,
    include_hints: bool,
    include_tags: bool,
    include_docs_url: bool,
}

impl CatalogRenderer {
    /// Create a new catalog renderer with full format
    pub fn new() -> Self {
        Self {
            format: CatalogFormat::Full,
            include_hints: true,
            include_tags: true,
            include_docs_url: true,
        }
    }

    /// Create a catalog renderer with compact format
    pub fn compact() -> Self {
        Self {
            format: CatalogFormat::Compact,
            include_hints: true,
            include_tags: false,
            include_docs_url: false,
        }
    }

    /// Create a catalog renderer with minimal format (smallest size)
    pub fn minimal() -> Self {
        Self {
            format: CatalogFormat::Minimal,
            include_hints: false,
            include_tags: false,
            include_docs_url: false,
        }
    }

    /// Set the catalog format
    pub fn with_format(mut self, format: CatalogFormat) -> Self {
        self.format = format;
        self
    }

    /// Set whether to include hints
    pub fn with_hints(mut self, include: bool) -> Self {
        self.include_hints = include;
        self
    }

    /// Set whether to include tags
    pub fn with_tags(mut self, include: bool) -> Self {
        self.include_tags = include;
        self
    }

    /// Set whether to include docs URL
    pub fn with_docs_url(mut self, include: bool) -> Self {
        self.include_docs_url = include;
        self
    }

    /// Render catalog in full format (WDP Part 9a compliant)
    ///
    /// Output format:
    /// ```json
    /// {
    ///   "version": "1.0.0",
    ///   "generated": "2024-01-15T10:30:00Z",
    ///   "namespace": "auth_service",       // optional
    ///   "namespace_hash": "h4tYw2",        // optional
    ///   "diags": {
    ///     "jGKFp": {
    ///       "code": "E.AUTH.TOKEN.001",
    ///       "severity": "E",
    ///       "message": "Token expired at {{timestamp}}",
    ///       "description": "The JWT token has exceeded its TTL",
    ///       "hints": ["Use /auth/refresh endpoint"],
    ///       "tags": ["auth", "security"],
    ///       "fields": ["timestamp"]
    ///     }
    ///   }
    /// }
    /// ```
    #[allow(dead_code, unused_variables, unused_mut)]
    fn render_full(
        &self,
        registry: &DocRegistry,
        errors: &[&ErrorDoc],
        filter_role: Option<Role>,
    ) -> String {
        let mut output = String::from("{\n");
        output.push_str(&format!("  \"version\": \"{}\",\n", registry.version()));

        // Generate timestamp (fallback to 0 if system time is before UNIX_EPOCH)
        let timestamp = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
            Ok(dur) => dur.as_secs(),
            Err(_) => 0,
        };
        output.push_str(&format!("  \"generated\": \"{}\",\n", timestamp));

        // Check if we have namespace info from the first error (all should share same namespace)
        // Use registry.first_error() for deterministic access (lexicographically smallest code)
        #[cfg(feature = "runtime-hash")]
        if let Some(first_error) = registry.first_error()
            && let Some(ns) = &first_error.namespace
        {
            output.push_str(&format!("  \"namespace\": \"{}\",\n", escape_json(ns)));
            if let Some(ns_hash) = &first_error.namespace_hash {
                output.push_str(&format!("  \"namespace_hash\": \"{}\",\n", ns_hash));
            }
        }

        if let Some(role) = filter_role {
            output.push_str(&format!("  \"role\": \"{:?}\",\n", role));
        }

        // WDP 9a: Use "diags" not "errors"
        output.push_str("  \"diags\": {\n");

        let mut first = true;
        for error in errors {
            #[cfg(feature = "runtime-hash")]
            {
                // Use combined_id() for namespace-aware catalogs
                if let Some(key) = error.combined_id() {
                    if !first {
                        output.push_str(",\n");
                    }
                    first = false;

                    output.push_str(&format!("    \"{}\": {{\n", key));
                    output.push_str(&format!("      \"code\": \"{}\",\n", error.code));
                    output.push_str(&format!("      \"severity\": \"{}\",\n", error.severity));

                    // WDP 9a: message is the template with {{field}} placeholders
                    let message_template = convert_to_wdp_placeholders(&error.message);
                    output.push_str(&format!(
                        "      \"message\": \"{}\",\n",
                        escape_json(&message_template)
                    ));

                    // WDP 9a: description is the detailed explanation
                    if !error.description.is_empty() {
                        output.push_str(&format!(
                            "      \"description\": \"{}\",\n",
                            escape_json(&error.description)
                        ));
                    }

                    if self.include_hints {
                        let hints = filter_role
                            .map(|r| error.hints_for_role(r))
                            .unwrap_or_default();
                        output.push_str("      \"hints\": [");
                        for (i, hint) in hints.iter().enumerate() {
                            if i > 0 {
                                output.push_str(", ");
                            }
                            output.push_str(&format!("\"{}\"", escape_json(hint)));
                        }
                        output.push_str("],\n");
                    }

                    if self.include_tags {
                        let tags = filter_role
                            .map(|r| error.tags_for_role(r))
                            .unwrap_or_default();
                        output.push_str("      \"tags\": [");
                        for (i, tag) in tags.iter().enumerate() {
                            if i > 0 {
                                output.push_str(", ");
                            }
                            output.push_str(&format!("\"{}\"", escape_json(tag)));
                        }
                        output.push_str("],\n");
                    }

                    // WDP 9a: fields array listing placeholder names
                    if !error.fields.is_empty() {
                        output.push_str("      \"fields\": [");
                        for (i, field) in error.fields.iter().enumerate() {
                            if i > 0 {
                                output.push_str(", ");
                            }
                            output.push_str(&format!("\"{}\"", escape_json(field)));
                        }
                        output.push_str("],\n");
                    }

                    if self.include_docs_url
                        && let Some(url) = &error.docs_url
                    {
                        output.push_str(&format!("      \"docs_url\": \"{}\",\n", url));
                    }

                    // Remove trailing comma from last field
                    if output.ends_with(",\n") {
                        output.truncate(output.len() - 2);
                        output.push('\n');
                    }

                    output.push_str("    }");
                }
            }

            #[cfg(not(feature = "runtime-hash"))]
            {
                // Without hash feature, skip this error
                let _ = error;
            }
        }

        output.push_str("\n  }\n");
        output.push_str("}\n");
        output
    }

    /// Render catalog in compact format (WDP Part 9a compliant)
    ///
    /// Output format uses abbreviated field names:
    /// - `v` → version
    /// - `g` → generated
    /// - `ns` → namespace (optional)
    /// - `nsh` → namespace_hash (optional)
    /// - `wd` → diags
    /// - `c` → code, `s` → severity, `m` → message, `d` → description
    /// - `h` → hints, `t` → tags, `f` → fields
    #[allow(dead_code, unused_variables, unused_mut)]
    fn render_compact(
        &self,
        registry: &DocRegistry,
        errors: &[&ErrorDoc],
        filter_role: Option<Role>,
    ) -> String {
        let mut output = String::from("{\"v\":\"");
        output.push_str(registry.version());
        output.push('"');

        // Add namespace info if present
        // Use registry.first_error() for deterministic access (lexicographically smallest code)
        #[cfg(feature = "runtime-hash")]
        if let Some(first_error) = registry.first_error()
            && let Some(ns) = &first_error.namespace
        {
            output.push_str(",\"ns\":\"");
            output.push_str(&escape_json(ns));
            output.push('"');
            if let Some(ns_hash) = &first_error.namespace_hash {
                output.push_str(",\"nsh\":\"");
                output.push_str(ns_hash);
                output.push('"');
            }
        }

        // WDP 9a: Use "wd" for diags (compact)
        output.push_str(",\"wd\":{");

        let mut first = true;
        for error in errors {
            #[cfg(feature = "runtime-hash")]
            {
                if let Some(key) = error.combined_id() {
                    if !first {
                        output.push(',');
                    }
                    first = false;

                    output.push('"');
                    output.push_str(&key);
                    output.push_str("\":{\"c\":\"");
                    output.push_str(&error.code);
                    output.push_str("\",\"s\":\"");
                    output.push_str(&error.severity);
                    output.push_str("\",\"m\":\"");
                    let message_template = convert_to_wdp_placeholders(&error.message);
                    output.push_str(&escape_json(&message_template));
                    output.push('"');

                    if !error.description.is_empty() {
                        output.push_str(",\"d\":\"");
                        output.push_str(&escape_json(&error.description));
                        output.push('"');
                    }

                    if self.include_hints {
                        let hints = filter_role
                            .map(|r| error.hints_for_role(r))
                            .unwrap_or_default();
                        if !hints.is_empty() {
                            output.push_str(",\"h\":[");
                            for (i, hint) in hints.iter().enumerate() {
                                if i > 0 {
                                    output.push(',');
                                }
                                output.push('"');
                                output.push_str(&escape_json(hint));
                                output.push('"');
                            }
                            output.push(']');
                        }
                    }

                    if self.include_tags {
                        let tags = filter_role
                            .map(|r| error.tags_for_role(r))
                            .unwrap_or_default();
                        if !tags.is_empty() {
                            output.push_str(",\"t\":[");
                            for (i, tag) in tags.iter().enumerate() {
                                if i > 0 {
                                    output.push(',');
                                }
                                output.push('"');
                                output.push_str(&escape_json(tag));
                                output.push('"');
                            }
                            output.push(']');
                        }
                    }

                    if !error.fields.is_empty() {
                        output.push_str(",\"f\":[");
                        for (i, field) in error.fields.iter().enumerate() {
                            if i > 0 {
                                output.push(',');
                            }
                            output.push('"');
                            output.push_str(&escape_json(field));
                            output.push('"');
                        }
                        output.push(']');
                    }

                    output.push('}');
                }
            }

            #[cfg(not(feature = "runtime-hash"))]
            {
                let _ = error;
            }
        }

        output.push_str("}}");
        output
    }

    /// Render catalog in minimal format (WDP Part 9a compliant)
    ///
    /// Output format - array-based, smallest size:
    /// ```json
    /// {
    ///   "jGKFp": ["E.AUTH.TOKEN.001", "Token expired at {{timestamp}}"]
    /// }
    /// ```
    #[allow(dead_code, unused_variables, unused_mut)]
    fn render_minimal(&self, errors: &[&ErrorDoc], _filter_role: Option<Role>) -> String {
        let mut output = String::from("{");

        let mut first = true;
        for error in errors {
            #[cfg(feature = "runtime-hash")]
            {
                if let Some(key) = error.combined_id() {
                    if !first {
                        output.push(',');
                    }
                    first = false;

                    output.push('"');
                    output.push_str(&key);
                    output.push_str("\":[\"");
                    output.push_str(&error.code);
                    output.push_str("\",\"");
                    let message_template = convert_to_wdp_placeholders(&error.message);
                    output.push_str(&escape_json(&message_template));
                    output.push_str("\"]");
                }
            }

            #[cfg(not(feature = "runtime-hash"))]
            {
                let _ = error;
            }
        }

        output.push('}');
        output
    }
}

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

impl Renderer for CatalogRenderer {
    fn format_name(&self) -> &str {
        match self.format {
            CatalogFormat::Full => "catalog",
            CatalogFormat::Compact => "catalog-compact",
            CatalogFormat::Minimal => "catalog-min",
        }
    }

    #[allow(unused_variables)]
    fn render(
        &self,
        registry: &DocRegistry,
        errors: &[&ErrorDoc],
        output_path: &Path,
        filter_role: Option<Role>,
    ) -> std::io::Result<()> {
        #[cfg(not(feature = "runtime-hash"))]
        {
            Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "Catalog renderer requires the 'hash' feature to be enabled",
            ))
        }

        #[cfg(feature = "runtime-hash")]
        {
            let content = match self.format {
                CatalogFormat::Full => self.render_full(registry, errors, filter_role),
                CatalogFormat::Compact => self.render_compact(registry, errors, filter_role),
                CatalogFormat::Minimal => self.render_minimal(errors, filter_role),
            };

            let mut file = File::create(output_path)?;
            file.write_all(content.as_bytes())?;
            Ok(())
        }
    }
}

/// Escape JSON special characters per RFC 8259
///
/// Escapes:
/// - `"` → `\"`
/// - `\` → `\\`
/// - `/` → `\/` (prevents XSS when embedded in HTML script tags)
/// - Control characters U+0000-U+001F:
///   - `\b` (U+0008), `\t` (U+0009), `\n` (U+000A), `\f` (U+000C), `\r` (U+000D)
///   - Others as `\uXXXX`
#[allow(dead_code)]
fn escape_json(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 16);
    for c in s.chars() {
        match c {
            '"' => result.push_str("\\\""),
            '\\' => result.push_str("\\\\"),
            '/' => result.push_str("\\/"), // solidus - prevents </script> XSS in HTML embedding
            '\u{0008}' => result.push_str("\\b"), // backspace
            '\u{0009}' => result.push_str("\\t"), // tab
            '\u{000A}' => result.push_str("\\n"), // newline
            '\u{000C}' => result.push_str("\\f"), // form feed
            '\u{000D}' => result.push_str("\\r"), // carriage return
            // Other control characters (U+0000-U+001F except those above)
            c if c < '\u{0020}' => {
                result.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => result.push(c),
        }
    }
    result
}

/// Convert single-brace placeholders {field} to WDP double-brace {{field}}
///
/// WDP Part 9a requires double-brace syntax for field placeholders in messages.
/// This function converts existing single-brace templates to WDP format.
///
/// # Examples
/// - `"Token expired at {timestamp}"` → `"Token expired at {{timestamp}}"`
/// - `"User {user_id} not found"` → `"User {{user_id}} not found"`
#[allow(dead_code)]
fn convert_to_wdp_placeholders(message: &str) -> String {
    let mut result = String::with_capacity(message.len() * 2);
    let mut chars = message.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '{' {
            // Check if it's already double-braced
            if chars.peek() == Some(&'{') {
                // Already WDP format, keep as-is
                result.push('{');
                result.push(chars.next().unwrap());
            } else {
                // Single brace, convert to double
                result.push_str("{{");
            }
        } else if c == '}' {
            // Check if it's already double-braced
            if chars.peek() == Some(&'}') {
                // Already WDP format, keep as-is
                result.push('}');
                result.push(chars.next().unwrap());
            } else {
                // Single brace, convert to double
                result.push_str("}}");
            }
        } else {
            result.push(c);
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_escape_json() {
        // Basic strings unchanged
        assert_eq!(escape_json("hello"), "hello");

        // Quote and backslash escaping
        assert_eq!(escape_json("hello\"world"), "hello\\\"world");
        assert_eq!(escape_json("back\\slash"), "back\\\\slash");

        // Common control characters (shorthand escapes)
        assert_eq!(escape_json("line1\nline2"), "line1\\nline2");
        assert_eq!(escape_json("tab\there"), "tab\\there");
        assert_eq!(escape_json("return\rhere"), "return\\rhere");
        assert_eq!(escape_json("form\x0Cfeed"), "form\\ffeed");
        assert_eq!(escape_json("back\x08space"), "back\\bspace");

        // Other control characters (U+0000-U+001F) as \uXXXX
        assert_eq!(escape_json("null\x00char"), "null\\u0000char");
        assert_eq!(escape_json("bell\x07ring"), "bell\\u0007ring");
        assert_eq!(escape_json("escape\x1Bseq"), "escape\\u001bseq");

        // Combined escaping
        assert_eq!(
            escape_json("quote\"tab\tnull\x00end"),
            "quote\\\"tab\\tnull\\u0000end"
        );

        // Unicode passthrough (non-control chars are fine)
        assert_eq!(escape_json("日本語"), "日本語");
        assert_eq!(escape_json("emoji 🦆"), "emoji 🦆");
    }

    #[test]
    fn test_convert_to_wdp_placeholders() {
        // Single brace to double brace
        assert_eq!(
            convert_to_wdp_placeholders("Token expired at {timestamp}"),
            "Token expired at {{timestamp}}"
        );

        // Multiple fields
        assert_eq!(
            convert_to_wdp_placeholders("User {user_id} has {count} items"),
            "User {{user_id}} has {{count}} items"
        );

        // Already double-braced (WDP format) - keep as-is
        assert_eq!(
            convert_to_wdp_placeholders("Already {{formatted}}"),
            "Already {{formatted}}"
        );

        // No placeholders
        assert_eq!(
            convert_to_wdp_placeholders("No placeholders here"),
            "No placeholders here"
        );
    }

    #[test]
    fn test_catalog_format_types() {
        let full = CatalogRenderer::new();
        assert_eq!(full.format_name(), "catalog");

        let compact = CatalogRenderer::compact();
        assert_eq!(compact.format_name(), "catalog-compact");

        let minimal = CatalogRenderer::minimal();
        assert_eq!(minimal.format_name(), "catalog-min");
    }

    #[test]
    fn test_catalog_builder() {
        let renderer = CatalogRenderer::new()
            .with_format(CatalogFormat::Compact)
            .with_hints(false)
            .with_tags(false);

        assert_eq!(renderer.format, CatalogFormat::Compact);
        assert!(!renderer.include_hints);
        assert!(!renderer.include_tags);
    }
}