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
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
//! # Granular Validation Demo
//!
//! This example demonstrates the complete error code system with:
//! 1. Centralized sequences (like constants)
//! 2. Centralized primaries (like constants)
//! 3. Distributed components (enums in separate modules, re-exported via hub)
//! 4. diag! granular validation modes - choose exactly what you want validated
//!
//! ## Key Concepts
//!
//! - **Sequences Hub**: All sequences defined at `crate::sequences`
//! - **Primaries Hub**: All primaries defined at `crate::primaries`
//! - **Components Hub**: Components defined in modules, re-exported at `crate::components`
//! - **Granular Validation**: `strict(sequence, primary, component)` - validate what you need
//! - **Relaxed Mode**: No validation for maximum flexibility
//!
//! ## Running
//!
//! ```bash
//! cargo run --example strict_validation_demo --features metadata
//! ```

// Compile-time feature check with helpful error message
#[cfg(not(feature = "metadata"))]
compile_error!(
    "\n\n\
    ❌ This example requires the 'metadata' feature!\n\
    \n\
    The diag! macro generates DiagnosticRuntime structs that include\n\
    role-gated fields (hints_runtime_gated, hints_both_gated, etc.)\n\
    which are only compiled when the 'metadata' feature is enabled.\n\
    \n\
    Run this example with:\n\
    \n\
    cargo run --example strict_validation_demo --features metadata\n\
    \n\
    Or use --all-features to enable everything:\n\
    \n\
    cargo run --example strict_validation_demo --all-features\n\
    "
);

// Setup paths for waddling-errors (required for strict validation)
use waddling_errors_macros::setup;
setup! {
    components = crate::components,
    primaries = crate::primaries,
    sequences = crate::sequences,
}

// ============================================================================
// STEP 1: Define Sequences (Centralized Hub)
// ============================================================================

/// Central sequence hub - all sequences defined here
pub mod sequences {
    use waddling_errors_macros::sequence;

    sequence! {
        // Input validation (001-010)
        MISSING(1) {
            description: "Required parameter is absent",
            typical_severity: "Error",
            hints: [
                "Check if parameter was provided",
                "Verify required fields are set",
            ],
        },

        INVALID(3) {
            description: "Validation failed",
            typical_severity: "Error",
            hints: [
                "Review validation rules",
                "Check input format",
            ],
        },

        // Access control (008-010)
        DENIED(8) {
            description: "Access denied",
            typical_severity: "Error",
            hints: [
                "Verify permissions",
                "Check authorization",
            ],
        },

        // Timing (017-020)
        EXPIRED(17) {
            description: "Token or session expired",
            typical_severity: "Error",
            hints: [
                "Refresh token",
                "Re-authenticate",
            ],
        },

        // Resources (021-030)
        NOT_FOUND(21) {
            description: "Resource not found",
            typical_severity: "Error",
            hints: [
                "Verify resource ID",
                "Check if resource was deleted",
            ],
        },

        CONFLICT(23) {
            description: "Concurrent modification conflict",
            typical_severity: "Error",
            hints: [
                "Retry with latest version",
                "Use optimistic locking",
            ],
        },

        EXHAUSTED(26) {
            description: "Resource pool exhausted",
            typical_severity: "Critical",
            hints: [
                "Scale up resources",
                "Review capacity planning",
            ],
        },
    }
}

// ============================================================================
// STEP 2: Define Primaries (Centralized Hub)
// ============================================================================

/// Central primaries hub - all primary categories defined here
pub mod primaries {
    use waddling_errors_macros::primary;

    primary! {
        pub enum Primary {
            Token {
                description: "Authentication token errors",
                examples: [
                    "Missing JWT token",
                    "Invalid token signature",
                    "Expired token",
                ],
                tags: ["authentication", "jwt", "security"],
                related: ["Permission"],
            },

            Permission {
                description: "Authorization and permission errors",
                examples: [
                    "Insufficient permissions",
                    "Role not assigned",
                    "Scope not granted",
                ],
                tags: ["authorization", "rbac", "security"],
                related: ["Token"],
            },

            Connection {
                description: "Database connection errors",
                examples: [
                    "Connection pool exhausted",
                    "Connection timeout",
                    "Connection refused",
                ],
                tags: ["database", "networking"],
            },

            Query {
                description: "Database query errors",
                examples: [
                    "Query timeout",
                    "Constraint violation",
                    "Deadlock detected",
                ],
                tags: ["database", "sql"],
                related: ["Connection"],
            },
        }
    }
}

// ============================================================================
// STEP 3: Define Components (Distributed, Re-exported via Hub)
// ============================================================================

/// Auth component - defined in its own module
mod auth_component {
    use waddling_errors_macros::component;

    component! {
        pub enum Component {
            Auth {
                docs: "Authentication and authorization system",
                tags: ["security", "authentication"],
                examples: [
                    "E.Auth.Token.001 - JWT token missing",
                    "E.Auth.Permission.008 - Access denied",
                ],
            },
        }
    }
}

/// Database component - defined in its own module
mod database_component {
    use waddling_errors_macros::component;

    component! {
        pub enum Component {
            Database {
                docs: "Database operations and connections",
                tags: ["database", "storage"],
                examples: [
                    "E.Database.Connection.026 - Pool exhausted",
                    "E.Database.Query.023 - Conflict detected",
                ],
            },
        }
    }
}

/// Components hub - re-exports all components (REQUIRED for strict mode)
/// Re-exports string constants for hash computation in diag!
pub mod components {
    // String constant re-exports (for hash computation in diag!)
    pub use crate::auth_component::Auth;
    pub use crate::database_component::Database;
}

// ============================================================================
// STEP 4: Define Diagnostics with Different Validation Strategies
// ============================================================================

/// Full strict validation - validates everything
mod full_strict_diagnostics {
    use waddling_errors_macros::diag;

    diag! {
        strict(sequence, primary, component),  // <-- Validate all three

        // Auth errors (using AUTH component value)
        E.Auth.Token.MISSING: {
            message: "JWT token missing from Authorization header",
            description: "The request lacks a required JWT authentication token",
            hints: [
                "Add Authorization: Bearer <token> header",
                "Verify token is included in request",
            ],
            tags: ["authentication", "jwt"],
            related_codes: ["E.Auth.Token.INVALID", "E.Auth.Token.EXPIRED"],
        },

        E.Auth.Token.INVALID: {
            message: "JWT token signature validation failed",
            description: "Token signature is invalid or corrupted",
            hints: [
                "Verify signing key is correct",
                "Check token hasn't been tampered with",
            ],
            tags: ["authentication", "jwt", "security"],
            related_codes: ["E.Auth.Token.MISSING"],
        },

        E.Auth.Token.EXPIRED: {
            message: "JWT token has expired",
            description: "Token is past its expiration time",
            hints: [
                "Refresh authentication token",
                "Use refresh token to obtain new access token",
            ],
            tags: ["authentication", "jwt"],
            related_codes: ["E.Auth.Token.MISSING"],
        },

        E.Auth.Permission.DENIED: {
            message: "Insufficient permissions for operation",
            description: "User lacks required permissions or role",
            hints: [
                "Verify user has required role",
                "Check permission scopes",
                "Contact administrator for access",
            ],
            tags: ["authorization", "rbac"],
        },

        // Database errors
        C.Database.Connection.EXHAUSTED: {
            message: "Database connection pool exhausted",
            description: "No available connections in the pool",
            hints: [
                "Scale up connection pool size",
                "Review connection leak detection",
                "Check for long-running transactions",
            ],
            tags: ["database", "performance", "capacity"],
        },

        E.Database.Query.CONFLICT: {
            message: "Concurrent modification detected",
            description: "Version conflict or optimistic lock failure",
            hints: [
                "Retry operation with latest version",
                "Implement exponential backoff",
                "Review transaction isolation level",
            ],
            tags: ["database", "concurrency"],
        },

        E.Database.Connection.NOT_FOUND: {
            message: "Database connection not found",
            description: "Requested connection ID does not exist",
            hints: [
                "Verify connection was established",
                "Check if connection was closed",
            ],
            tags: ["database"],
        },
    }

    pub use C_DATABASE_CONNECTION_EXHAUSTED as FULL_CRIT_DB_EXHAUSTED;
    pub use E_AUTH_TOKEN_INVALID as FULL_ERR_TOKEN_INVALID;
    pub use E_AUTH_TOKEN_MISSING as FULL_ERR_TOKEN_MISSING;
}

/// Sequence-only validation - most common use case
mod sequence_only_diagnostics {
    use waddling_errors_macros::diag;

    diag! {
        strict(sequence),  // <-- Only validate sequences (catches numeric typos)

        E.Auth.Token.MISSING: {
            message: "JWT token missing (sequence-only validation)",
            description: "This validates that MISSING exists in crate::sequences",
            hints: ["Add Authorization header"],
        },

        E.Database.Query.CONFLICT: {
            message: "Database conflict (sequence-only validation)",
            description: "This validates that CONFLICT exists in crate::sequences",
            hints: ["Retry with latest version"],
        },
    }

    pub use E_AUTH_TOKEN_MISSING as SEQ_ONLY_TOKEN_MISSING;
    pub use E_DATABASE_QUERY_CONFLICT as SEQ_ONLY_DB_CONFLICT;
}

/// Sequence + Primary validation - skip components if they're dynamic
mod sequence_primary_diagnostics {
    use waddling_errors_macros::diag;

    diag! {
        strict(sequence, primary),  // <-- Validate sequences and primaries

        E.Auth.Token.EXPIRED: {
            message: "Token expired (seq + primary validation)",
            description: "Validates TOKEN in primaries and EXPIRED in sequences",
            hints: ["Refresh token"],
        },

        E.Database.Connection.NOT_FOUND: {
            message: "Connection not found (seq + primary validation)",
            description: "Validates CONNECTION in primaries and NOT_FOUND in sequences",
            hints: ["Verify connection was established"],
        },
    }

    pub use E_AUTH_TOKEN_EXPIRED as SEQ_PRI_TOKEN_EXPIRED;
    pub use E_DATABASE_CONNECTION_NOT_FOUND as SEQ_PRI_DB_NOT_FOUND;
}

// ============================================================================
// STEP 5: Define Diagnostics with RELAXED Validation
// ============================================================================

/// Relaxed mode diagnostics - skips validation for flexibility
mod relaxed_diagnostics {
    use waddling_errors_macros::diag;

    diag! {
        relaxed,  // <-- RELAXED MODE: no validation (same as omitting it)

        E.Auth.Token.MISSING: {
            message: "Token missing (relaxed mode)",
            description: "This diagnostic doesn't validate references",
        },

        E.Database.Query.NOTFOUND: {
            message: "Query result not found (relaxed mode)",
            description: "Relaxed mode allows any sequence/primary/component names",
        },
    }

    pub use E_AUTH_TOKEN_MISSING as RELAXED_TOKEN_MISSING;
    pub use E_DATABASE_QUERY_NOTFOUND as RELAXED_QUERY_NOTFOUND;
}

// ============================================================================
// STEP 6: Demonstrate Usage
// ============================================================================

fn main() {
    println!("🦆 Granular Validation Demo");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("📚 This example demonstrates:\n");
    println!("  1. ✅ Centralized sequences at crate::sequences");
    println!("  2. ✅ Centralized primaries at crate::primaries");
    println!("  3. ✅ Distributed components re-exported via crate::components");
    println!("  4. ✅ diag! granular validation - choose what to validate\n");

    println!("═══════════════════════════════════════════════════════════");
    println!("🔍 FULL VALIDATION: strict(sequence, primary, component)");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("Validates all three at compile time:");
    println!("  ✓ Sequences exist in crate::sequences");
    println!("  ✓ Primaries exist in crate::primaries");
    println!("  ✓ Components exist in crate::components\n");

    use full_strict_diagnostics::*;

    println!("Examples:");
    println!(
        "  {} - {}",
        FULL_ERR_TOKEN_MISSING.code, FULL_ERR_TOKEN_MISSING.message
    );
    println!(
        "  {} - {}",
        FULL_ERR_TOKEN_INVALID.code, FULL_ERR_TOKEN_INVALID.message
    );
    println!(
        "  {} - {}",
        FULL_CRIT_DB_EXHAUSTED.code, FULL_CRIT_DB_EXHAUSTED.message
    );
    println!();

    println!("═══════════════════════════════════════════════════════════");
    println!("🔢 SEQUENCE-ONLY: strict(sequence)");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("Only validates sequences (most common use case):");
    println!("  ✓ Catches typos in sequence numbers");
    println!("  ✓ Ensures sequence constants exist");
    println!("  ⊘ Skips primary and component validation\n");

    use sequence_only_diagnostics::*;

    println!("Examples:");
    println!(
        "  {} - {}",
        SEQ_ONLY_TOKEN_MISSING.code, SEQ_ONLY_TOKEN_MISSING.message
    );
    println!(
        "  {} - {}",
        SEQ_ONLY_DB_CONFLICT.code, SEQ_ONLY_DB_CONFLICT.message
    );
    println!();

    println!("═══════════════════════════════════════════════════════════");
    println!("🎯 SEQUENCE + PRIMARY: strict(sequence, primary)");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("Validates sequences and primaries:");
    println!("  ✓ Validates sequence constants");
    println!("  ✓ Validates primary constants");
    println!("  ⊘ Skips component validation (useful for dynamic components)\n");

    use sequence_primary_diagnostics::*;

    println!("Examples:");
    println!(
        "  {} - {}",
        SEQ_PRI_TOKEN_EXPIRED.code, SEQ_PRI_TOKEN_EXPIRED.message
    );
    println!(
        "  {} - {}",
        SEQ_PRI_DB_NOT_FOUND.code, SEQ_PRI_DB_NOT_FOUND.message
    );
    println!();

    println!("═══════════════════════════════════════════════════════════");
    println!("🔓 RELAXED MODE DIAGNOSTICS");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("These diagnostics skip compile-time validation:");
    println!("  💡 No checks for sequence/primary existence");
    println!("  💡 Faster compilation, more flexible");
    println!("  💡 Useful when validation isn't needed or for dynamic scenarios\n");

    use relaxed_diagnostics::*;

    println!("Relaxed Diagnostics:");
    println!(
        "  {} - {}",
        RELAXED_TOKEN_MISSING.code, RELAXED_TOKEN_MISSING.message
    );
    println!(
        "  {} - {}",
        RELAXED_QUERY_NOTFOUND.code, RELAXED_QUERY_NOTFOUND.message
    );
    println!();

    println!("═══════════════════════════════════════════════════════════");
    println!("✨ KEY TAKEAWAYS");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("1. GRANULAR VALIDATION:");
    println!("   ✅ strict(sequence, primary, component) - validate everything");
    println!("   ✅ strict(sequence) - only validate sequences (most common)");
    println!("   ✅ strict(sequence, primary) - sequences + primaries");
    println!("   ✅ strict(component) - only components");
    println!("   ✅ relaxed - no validation (maximum flexibility)\n");

    println!("2. SEQUENCE HUB PATTERN:");
    println!("   ✅ Define all sequences in crate::sequences module");
    println!("   ✅ Use sequence! macro with imports for composition");
    println!("   ✅ strict(sequence) validates crate::sequences::NAME exists\n");

    println!("3. PRIMARY HUB PATTERN:");
    println!("   ✅ Define all primaries in crate::primaries module");
    println!("   ✅ primary! now generates constants (like sequence!)");
    println!("   ✅ Example: pub const TOKEN: &str = \"TOKEN\";");
    println!("   ✅ strict(primary) validates crate::primaries::NAME exists\n");

    println!("4. COMPONENT HUB PATTERN:");
    println!("   ✅ Define components in separate modules/files");
    println!("   ✅ Re-export all through crate::components hub");
    println!("   ✅ strict(component) validates crate::components::Name exists\n");

    println!("5. WHEN TO USE EACH MODE:");
    println!("   📌 strict(sequence) → Most common, catches numeric typos");
    println!("   📌 strict(sequence, primary) → When both hubs are set up");
    println!("   📌 strict(sequence, primary, component) → Full validation");
    println!("   📌 relaxed → Prototyping, dynamic code, maximum flexibility\n");

    println!("6. COMPILE-TIME SAFETY:");
    println!("   If you reference a non-existent sequence/primary/component,");
    println!("   the compiler will error immediately:");
    println!("   \"cannot find value `TYPO` in module `crate::sequences`\"");
    println!("   This catches errors at compile time, not runtime!\n");

    println!("═══════════════════════════════════════════════════════════");
    println!("🎯 RECOMMENDED PROJECT STRUCTURE");
    println!("═══════════════════════════════════════════════════════════\n");

    println!("src/");
    println!("  sequences/");
    println!("    mod.rs       - Hub that imports/defines all sequences");
    println!("    common.rs    - Shared sequences (MISSING, INVALID, etc.)");
    println!("    auth.rs      - Auth-specific sequences");
    println!("    database.rs  - Database-specific sequences");
    println!("  ");
    println!("  primaries.rs   - All primary categories (TOKEN, CONNECTION, etc.)");
    println!("  ");
    println!("  components/");
    println!("    mod.rs       - Hub that re-exports all components");
    println!("    auth.rs      - Auth component definition");
    println!("    database.rs  - Database component definition");
    println!("  ");
    println!("  errors/");
    println!("    auth.rs      - Auth error diagnostics (uses diag! strict)");
    println!("    database.rs  - Database error diagnostics (uses diag! strict)");
    println!("  ");
    println!("  lib.rs         - Re-exports sequences, primaries, components\n");

    println!("✅ Example complete! Check the source code for implementation details.");
}