waddling-errors-macros 0.7.3

Procedural macros for structured error codes with compile-time validation and taxonomy enforcement
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
//! Browser-Server Catalog Example with i18n

// Primaries intentionally use CamelCase to match E.Component.Primary.SEQUENCE format
#![allow(non_upper_case_globals)]
//!
//! This example demonstrates the COMPLETE catalog pattern:
//! 1. Server defines errors with diag! macro + <catalog> format
//! 2. Catalog is AUTO-GENERATED with hash mappings
//! 3. Server sends COMPACT messages (50 bytes)
//! 4. Browser receives and EXPANDS using catalog
//! 5. SAME HASH works with different language catalogs!
//!
//! ## The Complete Flow:
//!
//! ```text
//! SERVER                          NETWORK                 BROWSER (English)
//! ══════                          ═══════                 ═════════════════
//! Error occurs
//!//! Create compact:
//! {"h":"jGKFp","f":{"temp":"45.2"}}
//! (50 bytes)
//!//! ─────────────────────────────→
//!                                 HTTP POST
//!//!                                                         Receives compact
//!//!                                                         Loads catalog (en)
//!//!                                                         Expands:
//!                                                         "Temperature 45.2°C
//!                                                          exceeds threshold"
//!//!                                                         Shows user in UI
//!
//! BROWSER (Spanish)
//! ═════════════════
//! Receives: {"h":"jGKFp","f":{"temp":"45.2"}}
//! Loads catalog (es)
//! Expands: "Temperatura 45.2°C supera el umbral"
//! Shows user in Spanish! 🌍
//! ```
//!
//! ## Running
//!
//! ```bash
//! cargo run --example browser_server_catalog --features metadata
//! ```

#[cfg(not(feature = "metadata"))]
compile_error!(
    "\n\n\
    ❌ This example requires 'metadata' features!\n\
    \n\
    Run with:\n\
    cargo run --example browser_server_catalog --features metadata\n\
    "
);

// Only compile the actual code when features are present
#[cfg(feature = "metadata")]
use std::collections::HashMap;
#[cfg(feature = "metadata")]
use waddling_errors_macros::{diag, setup};

// ============================================================================
// SETUP: Configure paths for waddling-errors
// This allows component/primary/sequence definitions to be in any module
// ============================================================================

#[cfg(feature = "metadata")]
setup! {
    components = crate::components,
    primaries = crate::primaries,
    sequences = crate::sequences,
}

// ============================================================================
// SERVER-SIDE: Error Definitions (Backend)
// ============================================================================

#[cfg(feature = "metadata")]
pub mod components {
    use waddling_errors_macros::component;

    component! {
        Api {
            docs: "API server errors",
        }
    }
}

#[cfg(feature = "metadata")]
pub mod primaries {
    use waddling_errors_macros::primary;

    primary! {
        Auth {
            docs: "Authentication errors",
        }
    }
}

#[cfg(feature = "metadata")]
pub mod sequences {
    use waddling_errors_macros::sequence;

    sequence! {
        TOKEN_EXPIRED(1) {
            description: "JWT token has expired",
            typical_severity: "Error",
            hints: ["Use refresh token", "Re-login"],
        },

        INVALID_CREDENTIALS(2) {
            description: "Username or password incorrect",
            typical_severity: "Error",
            hints: ["Check username and password", "Reset password if needed"],
        },

        RATE_LIMIT(3) {
            description: "Too many requests",
            typical_severity: "Warning",
            hints: ["Wait before retrying", "Reduce request frequency"],
        },
    }
}

// Define errors with <catalog> - auto-generates catalog entries!
#[cfg(feature = "metadata")]
diag! {
    strict(component, primary, sequence, naming, duplicates, sequence_values, string_values),
    <catalog>
    E.Api.Auth.TOKEN_EXPIRED: {
        message: "Your session has expired at {{expiry}}. Please login again.",
        fields: [expiry],
        hints: ["Click 'Login' button", "Use refresh token if available"],
        tags: ["auth", "session", "security"],
    },
    E.Api.Auth.INVALID_CREDENTIALS: {
        message: "Invalid username or password for user '{{pii/username}}'.",
        pii: [username],
        hints: ["Check your credentials", "Reset password if forgotten"],
        tags: ["auth", "login"],
    },
    W.Api.Auth.RATE_LIMIT: {
        message: "Rate limit exceeded. Try again in {{retry_after}} seconds.",
        fields: [retry_after],
        hints: ["Wait before retrying", "Contact support if persistent"],
        tags: ["rate-limit", "throttling"],
    }
}

// ============================================================================
// SHARED: Compact Message Protocol
// ============================================================================

/// Compact error sent over network (what server sends to browser)
#[cfg(feature = "metadata")]
#[derive(Debug, Clone)]
struct CompactError {
    /// Hash identifier (5 chars)
    h: String,
    /// Field values for message interpolation
    f: HashMap<String, String>,
}

#[cfg(feature = "metadata")]
impl CompactError {
    fn new(hash: &str) -> Self {
        Self {
            h: hash.to_string(),
            f: HashMap::new(),
        }
    }

    fn with_field(mut self, key: &str, value: &str) -> Self {
        self.f.insert(key.to_string(), value.to_string());
        self
    }

    fn to_json(&self) -> String {
        let mut json = format!("{{\"h\":\"{}\"", self.h);
        if !self.f.is_empty() {
            json.push_str(",\"f\":{");
            let mut first = true;
            for (k, v) in &self.f {
                if !first {
                    json.push(',');
                }
                json.push_str(&format!("\"{}\":\"{}\"", k, v));
                first = false;
            }
            json.push('}');
        }
        json.push('}');
        json
    }

    fn byte_size(&self) -> usize {
        self.to_json().len()
    }
}

// ============================================================================
// BROWSER-SIDE: Catalog Entry (simulates catalog.json)
// ============================================================================

#[cfg(feature = "metadata")]
#[derive(Debug, Clone)]
struct CatalogEntry {
    code: String,
    severity: String,
    message: String,
    hints: Vec<String>,
}

/// Browser-side catalog (loaded from catalog.json)
#[cfg(feature = "metadata")]
struct BrowserCatalog {
    #[allow(dead_code)]
    language: String,
    entries: HashMap<String, CatalogEntry>,
}

#[cfg(feature = "metadata")]
impl BrowserCatalog {
    fn new(language: &str) -> Self {
        Self {
            language: language.to_string(),
            entries: HashMap::new(),
        }
    }

    fn add_entry(&mut self, hash: &str, entry: CatalogEntry) {
        self.entries.insert(hash.to_string(), entry);
    }

    /// EXPANSION: Turn compact hash into full error message
    fn expand(&self, compact: &CompactError) -> Option<ExpandedError> {
        let entry = self.entries.get(&compact.h)?;

        // Interpolate message with field values (supports both {{field}} and {{pii/field}})
        let mut message = entry.message.clone();
        for (key, value) in &compact.f {
            // Try regular field placeholder: {{field}}
            let placeholder = format!("{{{{{}}}}}", key);
            message = message.replace(&placeholder, value);
            // Also try PII field placeholder: {{pii/field}}
            let pii_placeholder = format!("{{{{pii/{}}}}}", key);
            message = message.replace(&pii_placeholder, value);
        }

        Some(ExpandedError {
            hash: compact.h.clone(),
            code: entry.code.clone(),
            severity: entry.severity.clone(),
            message,
            hints: entry.hints.clone(),
        })
    }
}

#[derive(Debug)]
struct ExpandedError {
    #[allow(dead_code)]
    hash: String,
    code: String,
    severity: String,
    message: String,
    hints: Vec<String>,
}

impl ExpandedError {
    fn display(&self) -> String {
        let mut output = "╔═══════════════════════════════════════╗\n".to_string();
        output.push_str(&format!(
            "║ [{}] {}\n",
            self.severity.to_uppercase(),
            self.code
        ));
        output.push_str("╠═══════════════════════════════════════╣\n");
        output.push_str(&format!("{}\n", self.message));
        if !self.hints.is_empty() {
            output.push_str("╠═══════════════════════════════════════╣\n");
            output.push_str("║ 💡 Suggestions:\n");
            for hint in &self.hints {
                output.push_str(&format!("║   • {}\n", hint));
            }
        }
        output.push_str("╚═══════════════════════════════════════╝\n");
        output
    }
}

// ============================================================================
// DEMO: Server → Browser Flow
// ============================================================================

#[cfg(feature = "metadata")]
fn main() {
    println!("🌐 Browser-Server Catalog Example");
    println!("═══════════════════════════════════════════════════════\n");

    // ========================================================================
    // STEP 1: Browser loads catalogs (one-time, at startup)
    // ========================================================================
    println!("📥 STEP 1: Browser Loads Catalogs");
    println!("───────────────────────────────────────────────────────\n");

    // English catalog (generated from server's diag! macros)
    let mut catalog_en = BrowserCatalog::new("en");
    catalog_en.add_entry(
        E_API_AUTH_TOKEN_EXPIRED_HASH,
        CatalogEntry {
            code: "E.API.AUTH.TOKEN_EXPIRED".to_string(),
            severity: "Error".to_string(),
            message: "Your session has expired at {{expiry}}. Please login again.".to_string(),
            hints: vec![
                "Click 'Login' button".to_string(),
                "Use refresh token if available".to_string(),
            ],
        },
    );

    // Spanish catalog (same hashes, different messages!)
    let mut catalog_es = BrowserCatalog::new("es");
    catalog_es.add_entry(
        E_API_AUTH_TOKEN_EXPIRED_HASH,
        CatalogEntry {
            code: "E.API.AUTH.TOKEN_EXPIRED".to_string(),
            severity: "Error".to_string(),
            message: "Tu sesión ha expirado a las {{expiry}}. Por favor, inicia sesión nuevamente."
                .to_string(),
            hints: vec![
                "Haz clic en el botón 'Iniciar sesión'".to_string(),
                "Usa el token de actualización si está disponible".to_string(),
            ],
        },
    );

    // French catalog
    let mut catalog_fr = BrowserCatalog::new("fr");
    catalog_fr.add_entry(
        E_API_AUTH_TOKEN_EXPIRED_HASH,
        CatalogEntry {
            code: "E.API.AUTH.TOKEN_EXPIRED".to_string(),
            severity: "Error".to_string(),
            message: "Votre session a expiré à {{expiry}}. Veuillez vous reconnecter.".to_string(),
            hints: vec![
                "Cliquez sur le bouton 'Connexion'".to_string(),
                "Utilisez le jeton de rafraîchissement si disponible".to_string(),
            ],
        },
    );

    println!("✅ Loaded 3 catalogs: English, Spanish, French");
    println!("   (In real app: downloaded from /api/catalog.json?lang=XX)\n");

    // ========================================================================
    // STEP 2: Server creates and sends compact error
    // ========================================================================
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("📤 STEP 2: Server Sends Compact Error");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");

    println!("🖥️  SERVER: Token validation failed for user session");
    println!("    Creating compact error...\n");

    let compact = CompactError::new(E_API_AUTH_TOKEN_EXPIRED_HASH)
        .with_field("expiry", "2024-11-19 15:30:00 UTC");

    println!("📦 SERVER → BROWSER (over network):");
    println!("   {}", compact.to_json());
    println!(
        "   Size: {} bytes (vs ~300 bytes for full error!)\n",
        compact.byte_size()
    );

    // ========================================================================
    // STEP 3: Browser receives and expands (different languages!)
    // ========================================================================
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("📥 STEP 3: Browser Receives & Expands");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");

    // English browser
    println!("🌍 Browser #1: English User");
    println!("   Receives: {}", compact.to_json());
    println!("   Expands with English catalog:\n");
    if let Some(expanded) = catalog_en.expand(&compact) {
        println!("{}", expanded.display());
    }

    // Spanish browser (SAME HASH!)
    println!("🌍 Browser #2: Spanish User");
    println!("   Receives: {}", compact.to_json());
    println!("   Expands with Spanish catalog:\n");
    if let Some(expanded) = catalog_es.expand(&compact) {
        println!("{}", expanded.display());
    }

    // French browser (SAME HASH!)
    println!("🌍 Browser #3: French User");
    println!("   Receives: {}", compact.to_json());
    println!("   Expands with French catalog:\n");
    if let Some(expanded) = catalog_fr.expand(&compact) {
        println!("{}", expanded.display());
    }

    // ========================================================================
    // STEP 4: Show the value
    // ========================================================================
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("💰 Value Proposition");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");

    let compact_size = compact.byte_size();
    let full_size = 350; // Typical full JSON error with all fields

    println!("📊 Bandwidth Savings:");
    println!("   Traditional (full error): ~{} bytes", full_size);
    println!("   With catalog (compact):   {} bytes", compact_size);
    println!(
        "   Savings: {:.1}% ({} bytes per error)\n",
        ((full_size - compact_size) as f64 / full_size as f64) * 100.0,
        full_size - compact_size
    );

    println!("🌐 i18n Benefits:");
    println!("   • Server sends language-agnostic hash");
    println!("   • Browser picks language catalog");
    println!("   • No server-side translation needed!");
    println!("   • User sees error in their language instantly\n");

    println!("🚀 Performance:");
    println!("   • Catalog loaded once (cached)");
    println!("   • Compact messages = faster API responses");
    println!("   • Works offline (catalog bundled)\n");

    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("✅ Key Takeaways");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");

    println!("1. 🎯 Define errors ONCE on server with <catalog>");
    println!("   diag! {{");
    println!("       <catalog>  // Auto-generates catalog");
    println!("       E.API.AUTH.TOKEN_EXPIRED: {{ ... }}");
    println!("   }}\n");

    println!(
        "2. 📦 Server sends compact: {{\"h\":\"{}\",\"f\":{{...}}}}",
        E_API_AUTH_TOKEN_EXPIRED_HASH
    );
    println!(
        "   ({} bytes instead of {} bytes)\n",
        compact_size, full_size
    );

    println!("3. 🌍 Browser expands with language-specific catalog");
    println!("   - English browser → English message");
    println!("   - Spanish browser → Spanish message");
    println!("   - Same hash, different languages!\n");

    println!("4. ⚡ Benefits:");
    println!("   • 80%+ bandwidth savings");
    println!("   • Client-side i18n (no server translation)");
    println!("   • Offline-capable (catalog cached)");
    println!("   • Type-safe hashes (compile-time constants)");
    println!("   • Zero runtime cost on server\n");

    println!("🎉 This is the power of the catalog pattern!");
}

// Dummy main when features are missing - compile_error above will show the message
#[cfg(not(feature = "metadata"))]
fn main() {}